<?php
namespace CodeIgniter\HTTP;
use CodeIgniter\HTTP\Exceptions\HTTPException;
class URI
{
const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;=';
const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~';
protected $uriString;
protected $segments = [];
protected $scheme = 'http';
protected $user;
protected $password;
protected $host;
protected $port;
protected $path;
protected $fragment = '';
protected $query = [];
protected $defaultPorts = [
'http' => 80,
'https' => 443,
'ftp' => 21,
'sftp' => 22,
];
protected $showPassword = false;
public function __construct(string $uri = null)
{
if (! is_null($uri))
{
$this->setURI($uri);
}
}
public function setURI(string $uri = null)
{
if (! is_null($uri))
{
$parts = parse_url($uri);
if ($parts === false)
{
throw HTTPException::forUnableToParseURI($uri);
}
$this->applyParts($parts);
}
return $this;
}
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;
}
if (! empty($this->port) && ! $ignorePort)
{
if ($this->port !== $this->defaultPorts[$this->scheme])
{
$authority .= ':' . $this->port;
}
}
$this->showPassword = false;
return $authority;
}
public function getUserInfo()
{
$userInfo = $this->user;
if ($this->showPassword === true && ! empty($this->password))
{
$userInfo .= ':' . $this->password;
}
return $userInfo;
}
public function showPassword(bool $val = true)
{
$this->showPassword = $val;
return $this;
}
public function getHost(): string
{
return $this->host;
}
public function getPort()
{
return $this->port;
}
public function getPath(): string
{
return (is_null($this->path)) ? '' : $this->path;
}
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);
}
public function getFragment(): string
{
return is_null($this->fragment) ? '' : $this->fragment;
}
public function getSegments(): array
{
return $this->segments;
}
public function getSegment(int $number): string
{
$number -= 1;
if ($number > count($this->segments))
{
throw HTTPException::forURISegmentOutOfRange($number);
}
return $this->segments[$number] ?? '';
}
public function setSegment(int $number, $value)
{
$number -= 1;
if ($number > count($this->segments) + 1)
{
throw HTTPException::forURISegmentOutOfRange($number);
}
$this->segments[$number] = $value;
$this->refreshPath();
return $this;
}
public function getTotalSegments(): int
{
return count($this->segments);
}
public function __toString(): string
{
return static::createURIString(
$this->getScheme(), $this->getAuthority(), $this->getPath(), $this->getQuery(), $this->getFragment()
);
}
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, '/') : $path;
}
if ($query)
{
$uri .= '?' . $query;
}
if ($fragment)
{
$uri .= '#' . $fragment;
}
return $uri;
}
public function setAuthority(string $str)
{
$parts = parse_url($str);
if (empty($parts['host']) && ! empty($parts['path']))
{
$parts['host'] = $parts['path'];
unset($parts['path']);
}
$this->applyParts($parts);
return $this;
}
public function setScheme(string $str)
{
$str = strtolower($str);
$str = preg_replace('#:
$this->scheme = $str;
return $this;
}
public function setUserInfo(string $user, string $pass)
{
$this->user = trim($user);
$this->password = trim($pass);
return $this;
}
public function setHost(string $str)
{
$this->host = trim($str);
return $this;
}
public function setPort(int $port = null)
{
if (is_null($port))
{
return $this;
}
if ($port <= 0 || $port > 65535)
{
throw HTTPException::forInvalidPort($port);
}
$this->port = $port;
return $this;
}
public function setPath(string $path)
{
$this->path = $this->filterPath($path);
$this->segments = explode('/', $this->path);
return $this;
}
public function refreshPath()
{
$this->path = $this->filterPath(implode('/', $this->segments));
$this->segments = explode('/', $this->path);
return $this;
}
public function setQuery(string $query)
{
if (strpos($query, '#') !== false)
{
throw HTTPException::forMalformedQueryString();
}
if (! empty($query) && strpos($query, '?') === 0)
{
$query = substr($query, 1);
}
$temp = explode('&', $query);
$parts = [];
foreach ($temp as $index => $part)
{
list($key, $value) = $this->splitQueryPart($part);
if (is_null($value))
{
$parts[$key] = null;
continue;
}
$parts[$this->decode($key)] = $this->decode($value);
}
$this->query = $parts;
return $this;
}
protected function decode(string $value): string
{
if (empty($value))
{
return $value;
}
$decoded = urldecode($value);
return strlen($decoded) < strlen($value) ? $decoded : $value;
}
protected function splitQueryPart(string $part)
{
$parts = explode('=', $part, 2);
if (count($parts) === 1)
{
$parts = null;
}
return $parts;
}
public function setQueryArray(array $query)
{
$query = http_build_query($query);
return $this->setQuery($query);
}
public function addQuery(string $key, $value = null)
{
$this->query[$key] = $value;
return $this;
}
public function stripQuery(...$params)
{
foreach ($params as $param)
{
unset($this->query[$param]);
}
return $this;
}
public function keepQuery(...$params)
{
$temp = [];
foreach ($this->query as $key => $value)
{
if (! in_array($key, $params))
{
continue;
}
$temp[$key] = $value;
}
$this->query = $temp;
return $this;
}
public function setFragment(string $string)
{
$this->fragment = trim($string, '# ');
return $this;
}
protected function filterPath(string $path = null): string
{
$orig = $path;
$path = urldecode($path);
$path = $this->removeDotSegments($path);
if (strpos($orig, './') === 0)
{
$path = '/' . $path;
}
if (strpos($orig, '../') === 0)
{
$path = '/' . $path;
}
$path = preg_replace_callback(
'/(?:[^' . static::CHAR_UNRESERVED . ':@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/', function (array $matches) {
return rawurlencode($matches[0]);
}, $path
);
return $path;
}
protected function applyParts(array $parts)
{
if (! empty($parts['host']))
{
$this->host = $parts['host'];
}
if (! empty($parts['user']))
{
$this->user = $parts['user'];
}
if (! empty($parts['path']))
{
$this->path = $this->filterPath($parts['path']);
}
if (! empty($parts['query']))
{
$this->setQuery($parts['query']);
}
if (! empty($parts['fragment']))
{
$this->fragment = $parts['fragment'];
}
if (isset($parts['scheme']))
{
$this->setScheme(rtrim($parts['scheme'], ':/'));
}
else
{
$this->setScheme('http');
}
if (isset($parts['port']))
{
if (! is_null($parts['port']))
{
$port = $parts['port'];
$this->port = $port;
}
}
if (isset($parts['pass']))
{
$this->password = $parts['pass'];
}
if (! empty($parts['path']))
{
$this->segments = explode('/', trim($parts['path'], '/'));
}
}
public function resolveRelativeURI(string $uri)
{
$relative = new URI();
$relative->setURI($uri);
if ($relative->getScheme() === $this->getScheme())
{
$relative->setScheme('');
}
$transformed = clone $relative;
if (! empty($relative->getAuthority()))
{
$transformed->setAuthority($relative->getAuthority())
->setPath($relative->getPath())
->setQuery($relative->getQuery());
}
else
{
if ($relative->getPath() === '')
{
$transformed->setPath($this->getPath());
if ($relative->getQuery())
{
$transformed->setQuery($relative->getQuery());
}
else
{
$transformed->setQuery($this->getQuery());
}
}
else
{
if (strpos($relative->getPath(), '/') === 0)
{
$transformed->setPath($relative->getPath());
}
else
{
$transformed->setPath($this->mergePaths($this, $relative));
}
$transformed->setQuery($relative->getQuery());
}
$transformed->setAuthority($this->getAuthority());
}
$transformed->setScheme($this->getScheme());
$transformed->setFragment($relative->getFragment());
return $transformed;
}
protected function mergePaths(URI $base, URI $reference): string
{
if (! empty($base->getAuthority()) && empty($base->getPath()))
{
return '/' . ltrim($reference->getPath(), '/ ');
}
$path = explode('/', $base->getPath());
if (empty($path[0]))
{
unset($path[0]);
}
array_pop($path);
array_push($path, $reference->getPath());
return implode('/', $path);
}
public function removeDotSegments(string $path): string
{
if (empty($path) || $path === '/')
{
return $path;
}
$output = [];
$input = explode('/', $path);
if (empty($input[0]))
{
unset($input[0]);
$input = array_values($input);
}
foreach ($input as $segment)
{
if ($segment === '..')
{
array_pop($output);
}
else if ($segment !== '.' && $segment !== '')
{
array_push($output, $segment);
}
}
$output = implode('/', $output);
$output = ltrim($output, '/ ');
if ($output !== '/')
{
if (strpos($path, '/') === 0)
{
$output = '/' . $output;
}
if (substr($path, -1, 1) === '/')
{
$output .= '/';
}
}
return $output;
}
}