Parse URL

@see {http://php.net/manual/en/function.parse-url.php#114817}
@see {https://github.com/jeremykendall/php-domain-parser/}

@param string $url URL.
@param int $component Component.
@return mixed Array, Component, or Null.
487852
public static function parse_url($url, int $component = -1) {
		ref\cast::string($url, true);
		ref\mb::trim($url);

		// Before we start, let's fix scheme-agnostic URLs.
		$url = \preg_replace('/^:?\/\//', 'https://', $url);

		// If an IPv6 address is passed on its own, we
		// need to shove it in brackets.
		if (\filter_var($url, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
			$url = "[$url]";
		}

		// The trick is to urlencode (most) parts before passing
		// them to the real parse_url().
		$encoded = \preg_replace_callback(
			'%([a-zA-Z][a-zA-Z0-9+\-.]*)?(:?//)?([^:/@?&=#\[\]]+)%usD',
			function ($matches) {
				$matches[3] = \urldecode($matches[3]);
				return $matches[1] . $matches[2] . $matches[3];
			},
			$url
		);

		// Before getting the real answer, make sure
		// there is a scheme, otherwise PHP will assume
		// all there is is a path, which is stupid.
		if (\PHP_URL_SCHEME !== $component) {
			$test = \parse_url($encoded, \PHP_URL_SCHEME);
			if (! $test) {
				$encoded = "blobfolio://$encoded";
			}
		}

		$parts = \parse_url($encoded, $component);

		// And now decode what we've been giving. Let's
		// also take a moment to translate Unicode hosts
		// to ASCII.
		if (\is_string($parts) && \PHP_URL_SCHEME !== $component) {
			$parts = \str_replace(' ', '+', \urldecode($parts));

			if (\PHP_URL_HOST === $component) {
				// Fix Unicode.
				if (\function_exists('idn_to_ascii')) {
					$parts = \explode('.', $parts);
					ref\file::idn_to_ascii($parts);
					$parts = \implode('.', $parts);
				}

				// Lowercase it.
				ref\mb::strtolower($parts, false);

				// Get rid of trailing periods.
				$parts = \ltrim($parts, '.');
				$parts = \rtrim($parts, '.');

				// Standardize IPv6 formatting.
				if (0 === \strpos($parts, '[')) {
					$parts = \str_replace(array('[', ']'), '', $parts);
					ref\sanitize::ip($parts, true);
					$parts = "[{$parts}]";
				}
			}
		}
		elseif (\is_array($parts)) {
			foreach ($parts as $k=>$v) {
				if (! \is_string($v)) {
					continue;
				}

				if ('scheme' !== $k) {
					$parts[$k] = \str_replace(' ', '+', \urldecode($v));
				}
				// Remove our pretend scheme.
				elseif ('blobfolio' === $v) {
					unset($parts[$k]);
					continue;
				}

				if ('host' === $k) {
					// Fix Unicode.
					if (\function_exists('idn_to_ascii')) {
						$parts[$k] = \explode('.', $parts[$k]);
						ref\file::idn_to_ascii($parts[$k]);
						$parts[$k] = \implode('.', $parts[$k]);
					}

					// Lowercase it.
					ref\mb::strtolower($parts[$k], false);

					// Get rid of trailing periods.
					$parts[$k] = \ltrim($parts[$k], '.');
					$parts[$k] = \rtrim($parts[$k], '.');

					// Standardize IPv6 formatting.
					if (0 === \strpos($parts[$k], '[')) {
						$parts[$k] = \str_replace(array('[', ']'), '', $parts[$k]);
						ref\sanitize::ip($parts[$k], true);
						$parts[$k] = "[{$parts[$k]}]";
					}
				}
			}
		}

		return $parts;
	}
1082149
public static function segmentUrl($url = null)
    {
        if (!is_null($url) && !empty($url)) {
            $url = $url;
        } else {
            $url = self::requestInstance()->getRequestUrl();
        }

        return explode('/', trim($url, '/'));
    }
1348129
private function parseUrl($url)
    {
        $parsed = parse_url($url);

        if ((count($parsed) === 1)
            && isset($parsed['path'])
            && (0 === strpos($parsed['path'], '?') || false !== strpos($parsed['path'], '&'))
        ) {
            $parsed = array(
                'query' => $parsed['path']
            );

            return $parsed;
        }

        return $parsed;
    }
696346
final protected function URLToString(array $components = array(
		'scheme',
		'user',
		'pass',
		'host',
		'port',
		'path',
		'query',
		'fragment'
	))
	{
		$url = '';
		$query = "{$this->query}";
		if (in_array('scheme', $components)) {
			if (is_string($this->_url_data['scheme'])) {
				$url .= rtrim($this->_url_data['scheme'], ':/') . '://';
			} else {
				$url .= 'http://';
			}
		}

		if (@is_string($this->_url_data['user']) and in_array('user', $components)) {
			$url .= urlencode($this->_url_data['user']);
			if (@is_string($this->_url_data['pass']) and in_array('pass', $components)) {
				$url .= ':' . urlencode($this->_url_data['pass']);
			}
			$url .= '@';
		}

		if (in_array('host', $components)) {
			if (@is_string($this->_url_data['host'])) {
				$url .= $this->_url_data['host'];
			} else {
				$url .= 'localhost';
			}
		}
		if (
			is_int($this->_url_data['port'])
			and ! $this->isDefaultPort($this->_url_data['scheme'], $this->_url_data['port'])
		) {
			$url .= ":{$this->_url_data['port']}";
		}
		if (in_array('path', $components)) {
			if (@is_string($this->_url_data['path'])) {
				$url .= '/' . ltrim($this->_url_data['path'], '/');
			} else {
				$url .= '/';
			}
		}

		if(
			strlen($query) !== 0 and in_array('query', $components)
		) {
			$url .= "?$query";
		}
		if (@is_string($this->_url_data['fragment']) and in_array('fragment', $components)) {
			$url .= '#' . ltrim($this->_url_data['fragment'], '#');
		}
		return $url;
	}
1249267
public function setUrl( $url )
    {
        if( $url==null )
        {
            return null;
        }

        $urlParts = parse_url( $url );

        $this->scheme = $urlParts['scheme'];
        $this->host = $urlParts['host'];
        $this->user = $urlParts['user'];
        $this->password = $urlParts['pass'];
        $this->path = $urlParts['path'];
        $this->query = $urlParts['query'];
        $this->fragment = $urlParts['fragment'];
        $this->port = $urlParts['port'];

        return $this;
    }
1149246
private function parseUrl( $url = '', Array $query_string_vars = [ ] ) {
        parse_str( parse_url( $url, PHP_URL_QUERY ), $this->query_string );
        $request_uri = trim( parse_url( $url, PHP_URL_PATH ), '/' );
        $this->request = trim( preg_replace( '#^/*index\.php#', '', $request_uri ), '/' );
        if ( ! empty( $query_string_vars ) ) {
            $this->query_string = array_merge( $this->query_string, $query_string_vars );
        }
    }
62254
public static function parseRoute($url)
    {
        $result = null;

        $parts = explode('/', trim($url, '/'));
        if (count($parts) === 1) {
            $parts[0] = $parts[0] === '' ? self::DEFAULT_CONTROLLER : $parts[0];
            $parts[1] = self::DEFAULT_ACTION;
        }

        $action                   = static::preparePart(array_pop($parts), true);
        $parts[count($parts) - 1] = static::preparePart($parts[count($parts) - 1]).'Controller';
        $controller               = '\\project\\controllers\\'.implode('\\',
                $parts);

        if ($action != '' && $controller != '') {
            $result = $controller.'::'.$action;
        }

        return $result;
    }
1132224
private function parseUrl(string $url): array
    {
        $parts = parse_url($url);

        if ($parts === false || !isset($parts['host'])) {
            throw new \InvalidArgumentException(sprintf('Invalid connection URL given: "%s"', $url));
        }

        $params = [
            'login' => $parts['user'] ?? '',
            'password' => $parts['pass'] ?? '',
            'host' => $parts['host'],
            'port' => (int) ($parts['port'] ?? 5672),
            'vhost' => empty($parts['path']) || $parts['path'] === '/' ? '/' : substr($parts['path'], 1),
        ];

        parse_str($parts['query'] ?? '', $queryParams);

        return $params + $queryParams;
    }
401904
public static function tryParseRelative(string $url, UrlInterface $baseUrl): ?UrlInterface
    {
        try {
            if (!self::myParse($baseUrl, $url, $scheme, $host, $port, $path, $queryString, $fragment)) {
                return null;
            }
        } catch (UrlPathLogicException $exception) {
            return null;
        }

        return new self($scheme, $host, $port, $path, $queryString, $fragment);
    }
748803
protected function parseUrlParams($url, &$var = [])
    {
        if ($url) {
            if ($this->getConfig('url_param_type')) {
                $var += explode('|', $url);
            } else {
                preg_replace_callback('/(\w+)\|([^\|]+)/', function ($match) use (&$var) {
                    $var[$match[1]] = strip_tags($match[2]);
                }, $url);
            }
        }
    }
76639
public function url($url = null)
    {
        if ($url) {
            $command = $this->getDriver()->factoryCommand('url', WebDriver_Command::METHOD_POST, ['url' => $url]);
            //protect slowest pages and lost selenium connection
            try {
                $this->getDriver()->curl($command);
            } catch (WebDriver_NoSeleniumException $mainException) {
                if (!$this->config()->get(WebDriver_Config::IMPROVED_URL_OPEN)) {
                    throw $mainException;
                }
                try {
                    $currentUrl = $this->url();
                    $partCheck = [PHP_URL_PATH, PHP_URL_QUERY, PHP_URL_HOST];
                    $isEqual = true;
                    foreach ($partCheck as $urlPart) {
                        if (parse_url($url, $urlPart) != parse_url($currentUrl, $urlPart)) {
                            var_dump(parse_url($url, $urlPart));
                            $isEqual = false;
                        }
                    }
                    if (!$isEqual) {
                        throw $mainException;
                    }
                } catch (WebDriver_NoSeleniumException $e) {
                    throw $mainException;
                }
            }
        } else {
            $result = $this->getDriver()->curl(
                $this->getDriver()->factoryCommand('url', WebDriver_Command::METHOD_GET)
            );
            return $result['value'];
        }
    }
811971
public function parse(Url $url) :? array
	{
		// Get path without possible file
		$path = $url->path();

		// Build route pattern
		$pattern = $this->buildRoutePattern();

		if (preg_match($pattern, $path, $matches) === 1) {

			$variables = [];
			$length = sizeof($matches);

			for ($i = 1; $i < $length; $i++) {
				$variables[$this->parameter[$i - 1]] = $matches[$i];
			}

			return $variables;
		}

		return null;
	}
142174
private function parseUrl($url)
	{
		$newUrl = preg_replace($this->patterns, $this->replacements, $url);
		$newUrl = trim($newUrl, '\/?');
		$newUrl = trim($newUrl, '\/');

		return $newUrl;
	}
783931
protected function parseUrl($url)
    {
        if ($parsed = parse_url($url)) {
            return $this->addPassword($parsed);
        }

        // A second try for not file:// schemes which does support absolute
        // paths (like sqlite:///)

        // Cut the scheme by hand
        $parts = explode(':', $url, 2);

        if (count($parts) != 2 || strlen($parts[0]) > 24) {
            throw new InvalidArgumentException("Unparseable url $url");
        }

        // Now cheat parse_url by giving it a file url
        if (!$parsed = parse_url('file:'.$parts[1])) {
            throw new InvalidArgumentException("Unparseable url $url");
        }

        $parsed['scheme'] = $parts[0];

        return $this->addPassword($parsed);
    }
756301
public function setUrl(string $url) : Request
    {
        $components = parse_url($url);

        if ($components === false) {
            throw new \InvalidArgumentException('The URL provided is not valid.');
        }

        if (! isset($components['scheme'])) {
            throw new \InvalidArgumentException('The URL must have a scheme.');
        }

        $scheme = strtolower($components['scheme']);

        if ($scheme !== 'http' && $scheme !== 'https') {
            throw new \InvalidArgumentException(sprintf('The URL scheme "%s" is not acceptable.', $scheme));
        }

        $isSecure = ($scheme === 'https');

        if (! isset($components['host'])) {
            throw new \InvalidArgumentException('The URL must have a host name.');
        }

        $host = $components['host'];

        if (isset($components['port'])) {
            $port = $components['port'];
            $hostHeader = $host . ':' . $port;
        } else {
            $port = ($isSecure ? 443 : 80);
            $hostHeader = $host;
        }

        $this->path = isset($components['path']) ? $components['path'] : '/';
        $requestUri = $this->path;

        if (isset($components['query'])) {
            $this->queryString = $components['query'];
            parse_str($this->queryString, $this->query);
            $requestUri .= '?' . $this->queryString;
        } else {
            $this->queryString = '';
            $this->query = [];
        }

        $this->setHeader('Host', $hostHeader);

        $this->host = $host;
        $this->port = $port;
        $this->isSecure = $isSecure;
        $this->requestUri = $requestUri;

        return $this;
    }
743308
public function url($component = -1) {
        $active_url = URL::here();

        if ($component > -1) {
            return parse_url($active_url, $component);
        }
        return $active_url;
    }
1036074
public function parse($url)
    {
        $this->_fixUrlForParsing($url);

        if (empty($url->path) && !isset($url->query['option'])) {
            $url->path = (get_viewer()->guest()) ? 'pages' : 'dashboard';
        }

        $segments = explode('/', trim($url->path, '/'));
        $segments = array_filter($segments);

        if (!empty($segments)) {
            $component = array_shift($segments);
            $url->query = array_merge(array('option' => 'com_'.$component), $url->query);
            $component = str_replace('com_', '', $url->query['option']);
            $query = $this->getComponentRouter($component)->parse($segments);
            $url->query = array_merge($url->query, array('option' => 'com_'.$component), $query);
        }

        return $url;
    }