-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
URI.php
1244 lines (1050 loc) · 25.4 KB
/
URI.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
/**
* This file is part of the CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CodeIgniter\HTTP;
use CodeIgniter\HTTP\Exceptions\HTTPException;
use Config\App;
use InvalidArgumentException;
/**
* Abstraction for a uniform resource identifier (URI).
*/
class URI
{
/**
* Sub-delimiters used in query strings and fragments.
*
* @const string
*/
const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;=';
/**
* Unreserved characters used in paths, query strings, and fragments.
*
* @const string
*/
const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~';
/**
* Current URI string
*
* @var string
*/
protected $uriString;
/**
* List of URI segments.
*
* Starts at 1 instead of 0
*
* @var array
*/
protected $segments = [];
/**
* The URI Scheme.
*
* @var string
*/
protected $scheme = 'http';
/**
* URI User Info
*
* @var string
*/
protected $user;
/**
* URI User Password
*
* @var string
*/
protected $password;
/**
* URI Host
*
* @var string
*/
protected $host;
/**
* URI Port
*
* @var integer
*/
protected $port;
/**
* URI path.
*
* @var string
*/
protected $path;
/**
* The name of any fragment.
*
* @var string
*/
protected $fragment = '';
/**
* The query string.
*
* @var array
*/
protected $query = [];
/**
* Default schemes/ports.
*
* @var array
*/
protected $defaultPorts = [
'http' => 80,
'https' => 443,
'ftp' => 21,
'sftp' => 22,
];
/**
* Whether passwords should be shown in userInfo/authority calls.
* Default to false because URIs often show up in logs
*
* @var boolean
*/
protected $showPassword = false;
/**
* If true, will continue instead of throwing exceptions.
*
* @var boolean
*/
protected $silent = false;
/**
* If true, will use raw query string.
*
* @var boolean
*/
protected $rawQueryString = false;
//--------------------------------------------------------------------
/**
* Constructor.
*
* @param string $uri
*
* @throws InvalidArgumentException
*/
public function __construct(string $uri = null)
{
if (! is_null($uri))
{
$this->setURI($uri);
}
}
//--------------------------------------------------------------------
/**
* If $silent == true, then will not throw exceptions and will
* attempt to continue gracefully.
*
* @param boolean $silent
*
* @return URI
*/
public function setSilent(bool $silent = true)
{
$this->silent = $silent;
return $this;
}
//--------------------------------------------------------------------
/**
* If $raw == true, then will use parseStr() method
* instead of native parse_str() function.
*
* @param boolean $raw
*
* @return URI
*/
public function useRawQueryString(bool $raw = true)
{
$this->rawQueryString = $raw;
return $this;
}
//--------------------------------------------------------------------
/**
* Sets and overwrites any current URI information.
*
* @param string|null $uri
*
* @return URI
*/
public function setURI(string $uri = null)
{
if (! is_null($uri))
{
$parts = parse_url($uri);
if ($parts === false)
{
if ($this->silent)
{
return $this;
}
throw HTTPException::forUnableToParseURI($uri);
}
$this->applyParts($parts);
}
return $this;
}
//--------------------------------------------------------------------
/**
* Retrieve the scheme component of the URI.
*
* If no scheme is present, this method MUST return an empty string.
*
* The value returned MUST be normalized to lowercase, per RFC 3986
* Section 3.1.
*
* The trailing ":" character is not part of the scheme and MUST NOT be
* added.
*
* @see https://tools.ietf.org/html/rfc3986#section-3.1
* @return string The URI scheme.
*/
public function getScheme(): string
{
return $this->scheme;
}
//--------------------------------------------------------------------
/**
* Retrieve the authority component of the URI.
*
* If no authority information is present, this method MUST return an empty
* string.
*
* The authority syntax of the URI is:
*
* <pre>
* [user-info@]host[:port]
* </pre>
*
* If the port component is not set or is the standard port for the current
* scheme, it SHOULD NOT be included.
*
* @see https://tools.ietf.org/html/rfc3986#section-3.2
*
* @param boolean $ignorePort
*
* @return string The URI authority, in "[user-info@]host[:port]" format.
*/
public function getAuthority(bool $ignorePort = false): string
{
if (empty($this->host))
{
return '';
}
$authority = $this->host;
if (! empty($this->getUserInfo()))
{
$authority = $this->getUserInfo() . '@' . $authority;
}
// Don't add port if it's a standard port for
// this scheme
if (! empty($this->port) && ! $ignorePort && $this->port !== $this->defaultPorts[$this->scheme])
{
$authority .= ':' . $this->port;
}
$this->showPassword = false;
return $authority;
}
//--------------------------------------------------------------------
/**
* Retrieve the user information component of the URI.
*
* If no user information is present, this method MUST return an empty
* string.
*
* If a user is present in the URI, this will return that value;
* additionally, if the password is also present, it will be appended to the
* user value, with a colon (":") separating the values.
*
* NOTE that be default, the password, if available, will NOT be shown
* as a security measure as discussed in RFC 3986, Section 7.5. If you know
* the password is not a security issue, you can force it to be shown
* with $this->showPassword();
*
* The trailing "@" character is not part of the user information and MUST
* NOT be added.
*
* @return string|null The URI user information, in "username[:password]" format.
*/
public function getUserInfo()
{
$userInfo = $this->user;
if ($this->showPassword === true && ! empty($this->password))
{
$userInfo .= ':' . $this->password;
}
return $userInfo;
}
//--------------------------------------------------------------------
/**
* Temporarily sets the URI to show a password in userInfo. Will
* reset itself after the first call to authority().
*
* @param boolean $val
*
* @return URI
*/
public function showPassword(bool $val = true)
{
$this->showPassword = $val;
return $this;
}
//--------------------------------------------------------------------
/**
* Retrieve the host component of the URI.
*
* If no host is present, this method MUST return an empty string.
*
* The value returned MUST be normalized to lowercase, per RFC 3986
* Section 3.2.2.
*
* @see http://tools.ietf.org/html/rfc3986#section-3.2.2
* @return string The URI host.
*/
public function getHost(): string
{
return $this->host;
}
//--------------------------------------------------------------------
/**
* Retrieve the port component of the URI.
*
* If a port is present, and it is non-standard for the current scheme,
* this method MUST return it as an integer. If the port is the standard port
* used with the current scheme, this method SHOULD return null.
*
* If no port is present, and no scheme is present, this method MUST return
* a null value.
*
* If no port is present, but a scheme is present, this method MAY return
* the standard port for that scheme, but SHOULD return null.
*
* @return null|integer The URI port.
*/
public function getPort()
{
return $this->port;
}
//--------------------------------------------------------------------
/**
* Retrieve the path component of the URI.
*
* The path can either be empty or absolute (starting with a slash) or
* rootless (not starting with a slash). Implementations MUST support all
* three syntaxes.
*
* Normally, the empty path "" and absolute path "/" are considered equal as
* defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically
* do this normalization because in contexts with a trimmed base path, e.g.
* the front controller, this difference becomes significant. It's the task
* of the user to handle both "" and "/".
*
* The value returned MUST be percent-encoded, but MUST NOT double-encode
* any characters. To determine what characters to encode, please refer to
* RFC 3986, Sections 2 and 3.3.
*
* As an example, if the value should include a slash ("/") not intended as
* delimiter between path segments, that value MUST be passed in encoded
* form (e.g., "%2F") to the instance.
*
* @see https://tools.ietf.org/html/rfc3986#section-2
* @see https://tools.ietf.org/html/rfc3986#section-3.3
* @return string The URI path.
*/
public function getPath(): string
{
return $this->path ?? '';
}
//--------------------------------------------------------------------
/**
* Retrieve the query string
*
* @param array $options
*
* @return string
*/
public function getQuery(array $options = []): string
{
$vars = $this->query;
if (array_key_exists('except', $options))
{
if (! is_array($options['except']))
{
$options['except'] = [$options['except']];
}
foreach ($options['except'] as $var)
{
unset($vars[$var]);
}
}
elseif (array_key_exists('only', $options))
{
$temp = [];
if (! is_array($options['only']))
{
$options['only'] = [$options['only']];
}
foreach ($options['only'] as $var)
{
if (array_key_exists($var, $vars))
{
$temp[$var] = $vars[$var];
}
}
$vars = $temp;
}
return empty($vars) ? '' : http_build_query($vars);
}
//--------------------------------------------------------------------
/**
* Retrieve a URI fragment
*
* @return string
*/
public function getFragment(): string
{
return $this->fragment ?? '';
}
//--------------------------------------------------------------------
/**
* Returns the segments of the path as an array.
*
* @return array
*/
public function getSegments(): array
{
return $this->segments;
}
//--------------------------------------------------------------------
/**
* Returns the value of a specific segment of the URI path.
*
* @param integer $number Segment number
* @param string $default Default value
*
* @return string The value of the segment. If no segment is found,
* throws InvalidArgumentError
*/
public function getSegment(int $number, string $default = ''): string
{
// The segment should treat the array as 1-based for the user
// but we still have to deal with a zero-based array.
$number -= 1;
if ($number > count($this->segments) && ! $this->silent)
{
throw HTTPException::forURISegmentOutOfRange($number);
}
return $this->segments[$number] ?? $default;
}
/**
* Set the value of a specific segment of the URI path.
* Allows to set only existing segments or add new one.
*
* @param integer $number
* @param mixed $value (string or int)
*
* @return $this
*/
public function setSegment(int $number, $value)
{
// The segment should treat the array as 1-based for the user
// but we still have to deal with a zero-based array.
$number -= 1;
if ($number > count($this->segments) + 1)
{
if ($this->silent)
{
return $this;
}
throw HTTPException::forURISegmentOutOfRange($number);
}
$this->segments[$number] = $value;
$this->refreshPath();
return $this;
}
//--------------------------------------------------------------------
/**
* Returns the total number of segments.
*
* @return integer
*/
public function getTotalSegments(): int
{
return count($this->segments);
}
//--------------------------------------------------------------------
/**
* Allow the URI to be output as a string by simply casting it to a string
* or echoing out.
*/
public function __toString(): string
{
// If hosted in a sub-folder, we will have additional
// segments that show up prior to the URI path we just
// grabbed from the request, so add it on if necessary.
$config = config(App::class);
$baseUri = new self($config->baseURL);
$basePath = trim($baseUri->getPath(), '/') . '/';
$path = $this->getPath();
$trimPath = ltrim($path, '/');
if ($basePath !== '/' && strpos($trimPath, $basePath) !== 0)
{
$path = $basePath . $trimPath;
}
// force https if needed
if ($config->forceGlobalSecureRequests)
{
$this->setScheme('https');
}
return static::createURIString(
$this->getScheme(), $this->getAuthority(), $path, // Absolute URIs should use a "/" for an empty path
$this->getQuery(), $this->getFragment()
);
}
//--------------------------------------------------------------------
/**
* Builds a representation of the string from the component parts.
*
* @param string $scheme
* @param string $authority
* @param string $path
* @param string $query
* @param string $fragment
*
* @return string
*/
public static function createURIString(string $scheme = null, string $authority = null, string $path = null, string $query = null, string $fragment = null): string
{
$uri = '';
if (! empty($scheme))
{
$uri .= $scheme . '://';
}
if (! empty($authority))
{
$uri .= $authority;
}
if ($path !== '')
{
$uri .= substr($uri, -1, 1) !== '/' ? '/' . ltrim($path, '/') : ltrim($path, '/');
}
if ($query)
{
$uri .= '?' . $query;
}
if ($fragment)
{
$uri .= '#' . $fragment;
}
return $uri;
}
//--------------------------------------------------------------------
/**
* Parses the given string an saves the appropriate authority pieces.
*
* @param string $str
*
* @return $this
*/
public function setAuthority(string $str)
{
$parts = parse_url($str);
if (! isset($parts['path']))
{
$parts['path'] = $this->getPath();
}
if (empty($parts['host']) && $parts['path'] !== '')
{
$parts['host'] = $parts['path'];
unset($parts['path']); // @phpstan-ignore-line
}
$this->applyParts($parts);
return $this;
}
//--------------------------------------------------------------------
/**
* Sets the scheme for this URI.
*
* Because of the large number of valid schemes we cannot limit this
* to only http or https.
*
* @see https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
*
* @param string $str
*
* @return $this
*/
public function setScheme(string $str)
{
$str = strtolower($str);
$str = preg_replace('#:(//)?$#', '', $str);
$this->scheme = $str;
return $this;
}
//--------------------------------------------------------------------
/**
* Sets the userInfo/Authority portion of the URI.
*
* @param string $user The user's username
* @param string $pass The user's password
*
* @return $this
*/
public function setUserInfo(string $user, string $pass)
{
$this->user = trim($user);
$this->password = trim($pass);
return $this;
}
//--------------------------------------------------------------------
/**
* Sets the host name to use.
*
* @param string $str
*
* @return $this
*/
public function setHost(string $str)
{
$this->host = trim($str);
return $this;
}
//--------------------------------------------------------------------
/**
* Sets the port portion of the URI.
*
* @param integer $port
*
* @return $this
*/
public function setPort(int $port = null)
{
if (is_null($port))
{
return $this;
}
if ($port <= 0 || $port > 65535)
{
if ($this->silent)
{
return $this;
}
throw HTTPException::forInvalidPort($port);
}
$this->port = $port;
return $this;
}
//--------------------------------------------------------------------
/**
* Sets the path portion of the URI.
*
* @param string $path
*
* @return $this
*/
public function setPath(string $path)
{
$this->path = $this->filterPath($path);
$tempPath = trim($this->path, '/');
$this->segments = ($tempPath === '') ? [] : explode('/', $tempPath);
return $this;
}
/**
* Sets the path portion of the URI based on segments.
*
* @return $this
*/
public function refreshPath()
{
$this->path = $this->filterPath(implode('/', $this->segments));
$tempPath = trim($this->path, '/');
$this->segments = ($tempPath === '') ? [] : explode('/', $tempPath);
return $this;
}
//--------------------------------------------------------------------
/**
* Sets the query portion of the URI, while attempting
* to clean the various parts of the query keys and values.
*
* @param string $query
*
* @return $this
*/
public function setQuery(string $query)
{
if (strpos($query, '#') !== false)
{
if ($this->silent)
{
return $this;
}
throw HTTPException::forMalformedQueryString();
}
// Can't have leading ?
if (! empty($query) && strpos($query, '?') === 0)
{
$query = substr($query, 1);
}
if ($this->rawQueryString)
{
$this->query = $this->parseStr($query);
}
else
{
parse_str($query, $this->query);
}
return $this;
}
//--------------------------------------------------------------------
/**
* A convenience method to pass an array of items in as the Query
* portion of the URI.
*
* @param array $query
*
* @return URI
*/
public function setQueryArray(array $query)
{
$query = http_build_query($query);
return $this->setQuery($query);
}
//--------------------------------------------------------------------
/**
* Adds a single new element to the query vars.
*
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function addQuery(string $key, $value = null)
{
$this->query[$key] = $value;
return $this;
}
//--------------------------------------------------------------------
/**
* Removes one or more query vars from the URI.
*
* @param string ...$params
*
* @return $this
*/
public function stripQuery(...$params)
{
foreach ($params as $param)
{
unset($this->query[$param]);
}
return $this;
}
//--------------------------------------------------------------------
/**
* Filters the query variables so that only the keys passed in
* are kept. The rest are removed from the object.
*
* @param string ...$params
*
* @return $this
*/
public function keepQuery(...$params)
{
$temp = [];
foreach ($this->query as $key => $value)
{
if (! in_array($key, $params, true))
{
continue;
}
$temp[$key] = $value;
}
$this->query = $temp;
return $this;
}
//--------------------------------------------------------------------
/**
* Sets the fragment portion of the URI.
*
* @see https://tools.ietf.org/html/rfc3986#section-3.5
*
* @param string $string
*
* @return $this
*/
public function setFragment(string $string)
{
$this->fragment = trim($string, '# ');
return $this;
}
//--------------------------------------------------------------------
/**
* Encodes any dangerous characters, and removes dot segments.
* While dot segments have valid uses according to the spec,
* this URI class does not allow them.
*
* @param string|null $path
*
* @return string
*/
protected function filterPath(string $path = null): string
{
$orig = $path;
// Decode/normalize percent-encoded chars so
// we can always have matching for Routes, etc.
$path = urldecode($path);
// Remove dot segments
$path = $this->removeDotSegments($path);
// Fix up some leading slash edge cases...
if (strpos($orig, './') === 0)
{
$path = '/' . $path;
}
if (strpos($orig, '../') === 0)
{
$path = '/' . $path;
}
// Encode characters
$path = preg_replace_callback(
'/(?:[^' . static::CHAR_UNRESERVED . ':@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/', function (array $matches) {
return rawurlencode($matches[0]);
}, $path
);
return $path;
}
//--------------------------------------------------------------------
/**
* Saves our parts from a parse_url call.
*
* @param array $parts
*/
protected function applyParts(array $parts)
{
if (! empty($parts['host']))
{
$this->host = $parts['host'];
}
if (! empty($parts['user']))
{
$this->user = $parts['user'];
}
if (isset($parts['path']) && $parts['path'] !== '')
{
$this->path = $this->filterPath($parts['path']);
}
if (! empty($parts['query']))
{
$this->setQuery($parts['query']);
}
if (! empty($parts['fragment']))
{
$this->fragment = $parts['fragment'];
}