-
-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathUrl.php
More file actions
452 lines (359 loc) · 9.95 KB
/
Url.php
File metadata and controls
452 lines (359 loc) · 9.95 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
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Http;
use Nette;
/**
* Mutable representation of a URL.
*
* <pre>
* scheme user password host port path query fragment
* | | | | | | | |
* /--\ /--\ /------\ /-------\ /--\/------------\ /--------\ /------\
* http://john:x0y17575@nette.org:8042/en/manual.php?name=param#fragment <-- absoluteUrl
* \______\__________________________/
* | |
* hostUrl authority
* </pre>
*
* @property string $scheme
* @property string $user
* @property string $password
* @property string $host
* @property int $port
* @property string $path
* @property string $query
* @property string $fragment
* @property-read string $absoluteUrl
* @property-read string $authority
* @property-read string $hostUrl
* @property-read string $basePath
* @property-read string $baseUrl
* @property-read string $relativeUrl
* @property-read array $queryParameters
*/
class Url implements \JsonSerializable
{
use Nette\SmartObject;
public static array $defaultPorts = [
'http' => 80,
'https' => 443,
'ftp' => 21,
];
private string $scheme = '';
private string $user = '';
private string $password = '';
private string $host = '';
private ?int $port = null;
private string $path = '';
private array $query = [];
private string $fragment = '';
/**
* @throws Nette\InvalidArgumentException if URL is malformed
*/
public function __construct(string|self|UrlImmutable|null $url = null)
{
if (is_string($url)) {
$p = @parse_url($url); // @ - is escalated to exception
if ($p === false) {
throw new Nette\InvalidArgumentException("Malformed or unsupported URI '$url'.");
}
$this->scheme = $p['scheme'] ?? '';
$this->port = $p['port'] ?? null;
$this->host = rawurldecode($p['host'] ?? '');
$this->user = rawurldecode($p['user'] ?? '');
$this->password = rawurldecode($p['pass'] ?? '');
$this->setPath($p['path'] ?? '');
$this->setQuery($p['query'] ?? []);
$this->fragment = rawurldecode($p['fragment'] ?? '');
} elseif ($url instanceof UrlImmutable || $url instanceof self) {
[$this->scheme, $this->user, $this->password, $this->host, $this->port, $this->path, $this->query, $this->fragment] = $url->export();
}
}
public function setScheme(string $scheme): static
{
$this->scheme = $scheme;
return $this;
}
public function getScheme(): string
{
return $this->scheme;
}
/** @deprecated */
public function setUser(string $user): static
{
$this->user = $user;
return $this;
}
/** @deprecated */
public function getUser(): string
{
return $this->user;
}
/** @deprecated */
public function setPassword(string $password): static
{
$this->password = $password;
return $this;
}
/** @deprecated */
public function getPassword(): string
{
return $this->password;
}
public function setHost(string $host): static
{
$this->host = $host;
$this->setPath($this->path);
return $this;
}
public function getHost(): string
{
return $this->host;
}
/**
* Returns the part of domain.
*/
public function getDomain(int $level = 2): string
{
$parts = ip2long($this->host)
? [$this->host]
: explode('.', $this->host);
$parts = $level >= 0
? array_slice($parts, -$level)
: array_slice($parts, 0, $level);
return implode('.', $parts);
}
public function setPort(int $port): static
{
$this->port = $port;
return $this;
}
public function getPort(): ?int
{
return $this->port ?: $this->getDefaultPort();
}
public function getDefaultPort(): ?int
{
return self::$defaultPorts[$this->scheme] ?? null;
}
public function setPath(string $path): static
{
$this->path = $path;
if ($this->host && !str_starts_with($this->path, '/')) {
$this->path = '/' . $this->path;
}
return $this;
}
public function getPath(): string
{
return $this->path;
}
public function setQuery(string|array $query): static
{
$this->query = is_array($query) ? $query : self::parseQuery($query);
return $this;
}
public function appendQuery(string|array $query): static
{
$this->query = is_array($query)
? $query + $this->query
: self::parseQuery($this->getQuery() . '&' . $query);
return $this;
}
public function getQuery(): string
{
return http_build_query($this->query, '', '&', PHP_QUERY_RFC3986);
}
public function getQueryParameters(): array
{
return $this->query;
}
public function getQueryParameter(string $name): mixed
{
return $this->query[$name] ?? null;
}
public function setQueryParameter(string $name, mixed $value): static
{
$this->query[$name] = $value;
return $this;
}
public function setFragment(string $fragment): static
{
$this->fragment = $fragment;
return $this;
}
public function getFragment(): string
{
return $this->fragment;
}
public function getAbsoluteUrl(): string
{
return $this->getHostUrl() . $this->path
. (($tmp = $this->getQuery()) ? '?' . $tmp : '')
. ($this->fragment === '' ? '' : '#' . $this->fragment);
}
/**
* Returns the [user[:pass]@]host[:port] part of URI.
*/
public function getAuthority(): string
{
return $this->host === ''
? ''
: ($this->user !== ''
? rawurlencode($this->user) . ($this->password === '' ? '' : ':' . rawurlencode($this->password)) . '@'
: '')
. $this->host
. ($this->port && $this->port !== $this->getDefaultPort()
? ':' . $this->port
: '');
}
/**
* Returns the scheme and authority part of URI.
*/
public function getHostUrl(): string
{
return ($this->scheme ? $this->scheme . ':' : '')
. (($authority = $this->getAuthority()) !== '' ? '//' . $authority : '');
}
/** @deprecated use UrlScript::getBasePath() instead */
public function getBasePath(): string
{
$pos = strrpos($this->path, '/');
return $pos === false ? '' : substr($this->path, 0, $pos + 1);
}
/** @deprecated use UrlScript::getBaseUrl() instead */
public function getBaseUrl(): string
{
return $this->getHostUrl() . $this->getBasePath();
}
/** @deprecated use UrlScript::getRelativeUrl() instead */
public function getRelativeUrl(): string
{
return substr($this->getAbsoluteUrl(), strlen($this->getBaseUrl()));
}
/**
* URL comparison.
*/
public function isEqual(string|self|UrlImmutable $url): bool
{
$url = new self($url);
$query = $url->query;
ksort($query);
$query2 = $this->query;
ksort($query2);
$host = rtrim($url->host, '.');
$host2 = rtrim($this->host, '.');
return $url->scheme === $this->scheme
&& (!strcasecmp($host, $host2)
|| self::idnHostToUnicode($host) === self::idnHostToUnicode($host2))
&& $url->getPort() === $this->getPort()
&& $url->user === $this->user
&& $url->password === $this->password
&& self::unescape($url->path, '%/') === self::unescape($this->path, '%/')
&& $query === $query2
&& $url->fragment === $this->fragment;
}
/**
* Transforms URL to canonical form.
*/
public function canonicalize(): static
{
$this->path = preg_replace_callback(
'#[^!$&\'()*+,/:;=@%"]+#',
fn(array $m): string => rawurlencode($m[0]),
self::unescape($this->path, '%/'),
);
$this->host = rtrim($this->host, '.');
$this->host = self::idnHostToUnicode(strtolower($this->host));
return $this;
}
public function __toString(): string
{
return $this->getAbsoluteUrl();
}
public function jsonSerialize(): string
{
return $this->getAbsoluteUrl();
}
/** @internal */
final public function export(): array
{
return [$this->scheme, $this->user, $this->password, $this->host, $this->port, $this->path, $this->query, $this->fragment];
}
/**
* Converts IDN ASCII host to UTF-8.
*/
private static function idnHostToUnicode(string $host): string
{
if (!str_contains($host, '--')) { // host does not contain IDN
return $host;
}
if (function_exists('idn_to_utf8') && defined('INTL_IDNA_VARIANT_UTS46')) {
return idn_to_utf8($host, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46) ?: $host;
}
trigger_error('PHP extension intl is not loaded or is too old', E_USER_WARNING);
}
/**
* Similar to rawurldecode, but preserves reserved chars encoded.
*/
public static function unescape(string $s, string $reserved = '%;/?:@&=+$,'): string
{
// reserved (@see RFC 2396) = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
// within a path segment, the characters "/", ";", "=", "?" are reserved
// within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", "$" are reserved.
if ($reserved !== '') {
$s = preg_replace_callback(
'#%(' . substr(chunk_split(bin2hex($reserved), 2, '|'), 0, -1) . ')#i',
fn(array $m): string => '%25' . strtoupper($m[1]),
$s,
);
}
return rawurldecode($s);
}
/**
* Parses query string. Is affected by directive arg_separator.input.
*/
public static function parseQuery(string $s): array
{
$s = str_replace(['%5B', '%5b'], '[', $s);
$sep = preg_quote(ini_get('arg_separator.input'));
$s = preg_replace("#([$sep])([^[$sep=]+)([^$sep]*)#", '&0[$2]$3', '&' . $s);
parse_str($s, $res);
return $res[0] ?? [];
}
/**
* Determines if URL is absolute, ie if it starts with a scheme followed by colon.
*/
public static function isAbsolute(string $url): bool
{
return (bool) preg_match('#^[a-z][a-z0-9+.-]*:#i', $url);
}
/**
* Normalizes a path by handling and removing relative path references like '.', '..' and directory traversal.
*/
public static function removeDotSegments(string $path): string
{
$prefix = $segment = '';
if (str_starts_with($path, '/')) {
$prefix = '/';
$path = substr($path, 1);
}
$segments = explode('/', $path);
$res = [];
foreach ($segments as $segment) {
if ($segment === '..') {
array_pop($res);
} elseif ($segment !== '.') {
$res[] = $segment;
}
}
if ($segment === '.' || $segment === '..') {
$res[] = '';
}
return $prefix . implode('/', $res);
}
}