@param string $url
@param bool   $allow_unsecured_connection

@throws \InvalidArgumentException

@return array
550703
private static function downloadContent($url, $allow_unsecured_connection)
    {
        // The URL must be a valid URL and scheme must be https
        Assertion::false(
            false === filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED),
            'Invalid URL.'
        );
        Assertion::false(
            false === $allow_unsecured_connection && 'https://' !==  mb_substr($url, 0, 8, '8bit'),
            'Unsecured connection.'
        );

        $params = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_URL            => $url,
        ];
        if (false === $allow_unsecured_connection) {
            $params[CURLOPT_SSL_VERIFYPEER] = true;
            $params[CURLOPT_SSL_VERIFYHOST] = 2;
        }

        $ch = curl_init();
        curl_setopt_array($ch, $params);
        $content = curl_exec($ch);
        $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        Assertion::eq(1, preg_match('/^application\/json([\s|;].*)?$/', $content_type), sprintf('Content type is not "application/json". It is "%s".', $content_type));
        curl_close($ch);

        Assertion::notEmpty($content, 'Unable to get content.');
        $content = json_decode($content, true);
        Assertion::isArray($content, 'Invalid content.');

        return $content;
    }
280451
public function urlWithQuerystring(string $url, string $allowedParameters = null) : string
    {
        if (!$allowedParameters) {
            return $url;
        }

        $allowedParameters = str_start($allowedParameters, '/');
        $allowedParameters = str_finish($allowedParameters, '/');

        $currentQuery = collect(request()->query())->filter(function ($value, $parameter) use ($allowedParameters) {
            return preg_match($allowedParameters, sprintf('%s=%s', $parameter, $value));
        });

        if (!$newQuery = http_build_query($currentQuery->all())) {
            return $url;
        };

        return sprintf('%s?%s', $url, $newQuery);
    }
247663
static protected function fetchData(string $url): array {
        $url  .= '.json?key=' . urlencode(RC::get('redmineApiKey'));
        $data = file_get_contents($url);
        if ($data) {
            $data = (array) json_decode($data);
            $data = array_pop($data);
            return (array) $data;
        }
        throw new RuntimeException('Fetching data failed');
    }
1096094
public function validateSocketUri($uri)
    {
        $uri = (string)$uri;
        if (!$uri) {
            throw new InvalidArgumentException('Invalid URI');
        }

        $scheme = parse_url($uri, PHP_URL_SCHEME);
        $scheme = $this->validateScheme($scheme);

        $host = parse_url($uri, PHP_URL_HOST);
        if (!$host) {
            throw new InvalidArgumentException("Invalid host");
        }

        $port = parse_url($uri, PHP_URL_PORT);
        if (!$port) {
            $port = $this->getPort($scheme);
        }

        return [$scheme, $host, $port];
    }
742301
private function getUrlOrigin($url)
    {
        return array(
            parse_url($url, PHP_URL_SCHEME),
            parse_url($url, PHP_URL_HOST),
            parse_url($url, PHP_URL_PORT),
        );
    }
912108
final public static function allowedParams (array $allowedParams=[], string $option) : array
	{
		$allowedArray 	= [];
		$option 		= static::checkGlobal($option);
		foreach ($allowedParams as $param) $allowedArray[$param] = $option[$param] ?? NULL;
		return $allowedArray;
	}
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);
    }
663868
static function parse_url_params($url)
    {
        try {
            $parse = parse_url($url);
            $query = '';
            if (isset($parse['query'])) {
                $query .= $parse['query'];
            }
            if (isset($parse['fragment'])) {
                if (empty($query)) {
                    $query = $parse['fragment'];
                } else {
                    $query .= '&' . $parse['fragment'];
                }
            }
            $queryParts = explode('&', $query);
            $params = array();
            foreach ($queryParts as $param) {
                $item = explode('=', $param);
                $params[$item[0]] = $item[1];
            }
            return $params;
        } catch (\Exception $e) {
            throw $e;
        }
    }
870857
protected function parseUrl($url)
    {
        $url = preg_replace('#^(sqlite3?):///#', '$1://null/', $url);

        $parsedUrl = parse_url($url);

        if ($parsedUrl === false) {
            throw new InvalidArgumentException('The database configuration URL is malformed.');
        }

        return $this->parseStringsToNativeTypes(
            array_map('rawurldecode', $parsedUrl)
        );
    }
1119767
public static function getPort(string $url)
    {
        $url = UrlHelper::validateUrl($url);

        $port = parse_url($url, PHP_URL_PORT);
        if ($port === false) {
            throw new InvalidArgumentException("Could not determine port, url seems to be invalid: $url");
        }

        return $port;
    }
971277
protected function extractUrlVariables($url){
        $variables = array();
        $pattern = "/(\\".static::$_URL_VAR_CHARACTER.".*?[^\\/]*)/";
        if (preg_match($pattern,$url,$matches)){
            array_shift($matches);
            foreach($matches as $match){
                $variables[] = $match[0];
            }
        }
        return $variables;
    }
36621
public function parseUrl($url) : array
    {
        $url = (string) $url;

        $parsedUrl = $this->doParseUrl($url);

        if ($parsedUrl === []) {
            throw new InvalidArgumentException(sprintf('Invalid url %s', $url));
        }

        $parsedUrl = array_merge(self::$defaultParts, $parsedUrl);

        if (isset($parsedUrl['host'])) {
            $parsedUrl['canonical'] = implode('.', array_reverse(explode('.', $parsedUrl['host']))) . ($parsedUrl['path'] ?? '') . (isset($parsedUrl['query']) ? '?' . $parsedUrl['query'] : '');

            $parsedUrl['resource'] = $parsedUrl['path'] ?? '';

            if (isset($parsedUrl['query'])) {
                $parsedUrl['resource'] .= '?' . $parsedUrl['query'];
            }
        }

        return $parsedUrl;
    }
542833
public function identify($url)
    {
        $result = $this->parseProjectId($url);
        if (empty($result['projectId']) && strpos($url, '.') !== false) {
            $result = $this->identifyFromHeaders($url);
        }
        if (empty($result['projectId'])) {
            throw new InvalidArgumentException('Failed to identify project ID from URL: <error>' . $url . '</error>');
        }

        return $result + ['environmentId' => null, 'host' => null, 'appId' => null];
    }
646509
protected function _getSkipActions(array $url): array
    {
        $controller = Utils::normalizeControllerName($url);
        $skipActions = (array)Configure::read('RolesCapabilities.accessCheck.skipActions.' . $controller);

        return $skipActions;
    }
1370446
private static function parseUrl(string $url, array $query = [], array $allowedSchemes = ['http' => 80, 'https' => 443]): array
    {
        if (false === $parts = parse_url($url)) {
            throw new InvalidArgumentException(sprintf('Malformed URL "%s".', $url));
        }

        if ($query) {
            $parts['query'] = self::mergeQueryString($parts['query'] ?? null, $query, true);
        }

        $port = $parts['port'] ?? 0;

        if (null !== $scheme = $parts['scheme'] ?? null) {
            if (!isset($allowedSchemes[$scheme = strtolower($scheme)])) {
                throw new InvalidArgumentException(sprintf('Unsupported scheme in "%s".', $url));
            }

            $port = $allowedSchemes[$scheme] === $port ? 0 : $port;
            $scheme .= ':';
        }

        if (null !== $host = $parts['host'] ?? null) {
            if (!\defined('INTL_IDNA_VARIANT_UTS46') && preg_match('/[\x80-\xFF]/', $host)) {
                throw new InvalidArgumentException(sprintf('Unsupported IDN "%s", try enabling the "intl" PHP extension or running "composer require symfony/polyfill-intl-idn".', $host));
            }

            if (false === $host = \defined('INTL_IDNA_VARIANT_UTS46') ? idn_to_ascii($host, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46) : strtolower($host)) {
                throw new InvalidArgumentException(sprintf('Unsupported host in "%s".', $url));
            }

            $host .= $port ? ':'.$port : '';
        }

        foreach (['user', 'pass', 'path', 'query', 'fragment'] as $part) {
            if (!isset($parts[$part])) {
                continue;
            }

            if (false !== strpos($parts[$part], '%')) {
                // https://tools.ietf.org/html/rfc3986#section-2.3
                $parts[$part] = preg_replace_callback('/%(?:2[DE]|3[0-9]|[46][1-9A-F]|5F|[57][0-9A]|7E)++/i', function ($m) { return rawurldecode($m[0]); }, $parts[$part]);
            }

            // https://tools.ietf.org/html/rfc3986#section-3.3
            $parts[$part] = preg_replace_callback("#[^-A-Za-z0-9._~!$&/'()*+,;=:@%]++#", function ($m) { return rawurlencode($m[0]); }, $parts[$part]);
        }

        return [
            'scheme' => $scheme,
            'authority' => null !== $host ? '//'.(isset($parts['user']) ? $parts['user'].(isset($parts['pass']) ? ':'.$parts['pass'] : '').'@' : '').$host : null,
            'path' => isset($parts['path'][0]) ? $parts['path'] : null,
            'query' => isset($parts['query']) ? '?'.$parts['query'] : null,
            'fragment' => isset($parts['fragment']) ? '#'.$parts['fragment'] : null,
        ];
    }
905129
public static function get(string $url, array $options = []) : array {
		$result = [
			'success' => false,
			'error' => [],
			'data' => null
		];
		if (strpos($url, '?') !== false) {
			$url.= '&';
		} else {
			$url.= '?';
		}
		$url.= http_build_query2($options['params']);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result['data'] = curl_exec($ch);
		if (!empty($options['json'])) {
			$result['data'] = json_decode($result['data'], true);
		}
		curl_close($ch);
		$result['success'] = true;
		return $result;
	}
554835
private function identifyFromHeaders($url)
    {
        if (!strpos($url, '.')) {
            throw new \InvalidArgumentException('Invalid URL: ' . $url);
        }
        if (strpos($url, '//') === false) {
            $url = 'https://' . $url;
        }
        $result = ['projectId' => null, 'environmentId' => null];
        $cluster = $this->getClusterHeader($url);
        if (!empty($cluster)) {
            $this->debug('Identified project cluster: ' . $cluster);
            list($result['projectId'], $result['environmentId']) = explode('-', $cluster, 2);
        }

        return $result;
    }