If the current Joomla URI is on https or PHP is on a secure connection always return 443 instead of 80

{@inheritdoc}
335719
public function getPort()
    {
        $port = parent::getPort();

        if (JUri::getInstance()->isSsl() || ($this->isSecure() && in_array($port, ['80', '8080']))) {
            $port = '443';
        }

        return $port;
    }
1361801
protected function getCurrentURI()
	{
		$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
		$current_uri = $protocol.$_SERVER['HTTP_HOST'].$this->getRequestURI();
		$parts = parse_url($current_uri);

		$query = '';
		if(!empty($parts['query']))
		{
			$params = array();
			parse_str($parts['query'], $params);
			$params = array_filter($params);
			if(!empty($params))
			{
				$query = '?'.http_build_query($params, '', '&');
			}
		}

		// Use port if non default.
		$port = isset($parts['port']) &&
			(($protocol === 'http://' && $parts['port'] !== 80) || ($protocol === 'https://' && $parts['port'] !== 443)) ? ':'.$parts['port']
				: '';

		// Rebuild.
		return $protocol.$parts['host'].$port.$parts['path'].$query;
	}
1035454
public function connect($connection_timeout = 0, $response_timeout = 30)
    {
        // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like
        // "regular" socket.
        // TODO: disabled for now because OpenSSL must be *compiled* in (not just
        //       loaded), and until PHP5 stream_get_wrappers is not available.
        //	  	if ($this->scheme == 'https') {
        //		  	if (version_compare(phpversion(), '4.3.0') >= 0) {
        //		  		if (extension_loaded('openssl')) {
        //		  			$this->scheme = 'ssl';
        //		  			$this->debug('Using SSL over OpenSSL');
        //		  		}
        //		  	}
        //		}
        $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port");
        if ($this->io_method() == 'socket') {
            if (!is_array($this->proxy)) {
                $host = $this->host;
                $port = $this->port;
            } else {
                $host = $this->proxy['host'];
                $port = $this->proxy['port'];
            }

            // use persistent connection
            if ($this->persistentConnection && isset($this->fp) && is_resource($this->fp)) {
                if (!feof($this->fp)) {
                    $this->debug('Re-use persistent connection');
                    return true;
                }
                fclose($this->fp);
                $this->debug('Closed persistent connection at EOF');
            }

            // munge host if using OpenSSL
            if ($this->scheme == 'ssl') {
                $host = 'ssl://' . $host;
            }
            $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout);

            // open socket
            if ($connection_timeout > 0) {
                $this->fp = @fsockopen($host, $this->port, $this->errno, $this->error_str, $connection_timeout);
            } else {
                $this->fp = @fsockopen($host, $this->port, $this->errno, $this->error_str);
            }

            // test pointer
            if (!$this->fp) {
                $msg = 'Couldn\'t open socket connection to server ' . $this->url;
                if ($this->errno) {
                    $msg .= ', Error (' . $this->errno . '): ' . $this->error_str;
                } else {
                    $msg .= ' prior to connect().  This is often a problem looking up the host name.';
                }
                $this->debug($msg);
                $this->setError($msg);
                return false;
            }

            // set response timeout
            $this->debug('set response timeout to ' . $response_timeout);
            socket_set_timeout($this->fp, $response_timeout);

            $this->debug('socket connected');
            return true;
        } elseif ($this->io_method() == 'curl') {
            if (!extension_loaded('curl')) {
                //			$this->setError('cURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS');
                $this->setError('The PHP cURL Extension is required for HTTPS or NLTM.  You will need to re-build or update your PHP to include cURL or change php.ini to load the PHP cURL extension.');
                return false;
            }
            // Avoid warnings when PHP does not have these options
            if (defined('CURLOPT_CONNECTIONTIMEOUT')) {
                $CURLOPT_CONNECTIONTIMEOUT = CURLOPT_CONNECTIONTIMEOUT;
            } else {
                $CURLOPT_CONNECTIONTIMEOUT = 78;
            }
            if (defined('CURLOPT_HTTPAUTH')) {
                $CURLOPT_HTTPAUTH = CURLOPT_HTTPAUTH;
            } else {
                $CURLOPT_HTTPAUTH = 107;
            }
            if (defined('CURLOPT_PROXYAUTH')) {
                $CURLOPT_PROXYAUTH = CURLOPT_PROXYAUTH;
            } else {
                $CURLOPT_PROXYAUTH = 111;
            }
            if (defined('CURLAUTH_BASIC')) {
                $CURLAUTH_BASIC = CURLAUTH_BASIC;
            } else {
                $CURLAUTH_BASIC = 1;
            }
            if (defined('CURLAUTH_DIGEST')) {
                $CURLAUTH_DIGEST = CURLAUTH_DIGEST;
            } else {
                $CURLAUTH_DIGEST = 2;
            }
            if (defined('CURLAUTH_NTLM')) {
                $CURLAUTH_NTLM = CURLAUTH_NTLM;
            } else {
                $CURLAUTH_NTLM = 8;
            }

            $this->debug('connect using cURL');
            // init CURL
            $this->ch = curl_init();
            // set url
            $hostURL = ($this->port != '') ? "$this->scheme://$this->host:$this->port" : "$this->scheme://$this->host";
            // add path
            $hostURL .= $this->path;
            $this->setCurlOption(CURLOPT_URL, $hostURL);
            // follow location headers (re-directs)
            if (ini_get('safe_mode') || ini_get('open_basedir')) {
                $this->debug('safe_mode or open_basedir set, so do not set CURLOPT_FOLLOWLOCATION');
                $this->debug('safe_mode = ');
                $this->appendDebug($this->varDump(ini_get('safe_mode')));
                $this->debug('open_basedir = ');
                $this->appendDebug($this->varDump(ini_get('open_basedir')));
            } else {
                $this->setCurlOption(CURLOPT_FOLLOWLOCATION, 1);
            }
            // ask for headers in the response output
            $this->setCurlOption(CURLOPT_HEADER, 1);
            // ask for the response output as the return value
            $this->setCurlOption(CURLOPT_RETURNTRANSFER, 1);
            // encode
            // We manage this ourselves through headers and encoding
            //		if(function_exists('gzuncompress')){
            //			$this->setCurlOption(CURLOPT_ENCODING, 'deflate');
            //		}
            // persistent connection
            if ($this->persistentConnection) {
                // I believe the following comment is now bogus, having applied to
                // the code when it used CURLOPT_CUSTOMREQUEST to send the request.
                // The way we send data, we cannot use persistent connections, since
                // there will be some "junk" at the end of our request.
                //$this->setCurlOption(CURL_HTTP_VERSION_1_1, true);
                $this->persistentConnection = false;
                $this->setHeader('Connection', 'close');
            }
            // set timeouts
            if ($connection_timeout != 0) {
                $this->setCurlOption($CURLOPT_CONNECTIONTIMEOUT, $connection_timeout);
            }
            if ($response_timeout != 0) {
                $this->setCurlOption(CURLOPT_TIMEOUT, $response_timeout);
            }

            if ($this->scheme == 'https') {
                $this->debug('set cURL SSL verify options');
                // recent versions of cURL turn on peer/host checking by default,
                // while PHP binaries are not compiled with a default location for the
                // CA cert bundle, so disable peer/host checking.
                //$this->setCurlOption(CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt');
                $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0);
                $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0);

                // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo)
                if ($this->authtype == 'certificate') {
                    $this->debug('set cURL certificate options');
                    if (isset($this->certRequest['cainfofile'])) {
                        $this->setCurlOption(CURLOPT_CAINFO, $this->certRequest['cainfofile']);
                    }
                    if (isset($this->certRequest['verifypeer'])) {
                        $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']);
                    } else {
                        $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 1);
                    }
                    if (isset($this->certRequest['verifyhost'])) {
                        $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']);
                    } else {
                        $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 1);
                    }
                    if (isset($this->certRequest['sslcertfile'])) {
                        $this->setCurlOption(CURLOPT_SSLCERT, $this->certRequest['sslcertfile']);
                    }
                    if (isset($this->certRequest['sslkeyfile'])) {
                        $this->setCurlOption(CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']);
                    }
                    if (isset($this->certRequest['passphrase'])) {
                        $this->setCurlOption(CURLOPT_SSLKEYPASSWD, $this->certRequest['passphrase']);
                    }
                    if (isset($this->certRequest['certpassword'])) {
                        $this->setCurlOption(CURLOPT_SSLCERTPASSWD, $this->certRequest['certpassword']);
                    }
                }
            }
            if ($this->authtype && ($this->authtype != 'certificate')) {
                if ($this->username) {
                    $this->debug('set cURL username/password');
                    $this->setCurlOption(CURLOPT_USERPWD, "$this->username:$this->password");
                }
                if ($this->authtype == 'basic') {
                    $this->debug('set cURL for Basic authentication');
                    $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_BASIC);
                }
                if ($this->authtype == 'digest') {
                    $this->debug('set cURL for digest authentication');
                    $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_DIGEST);
                }
                if ($this->authtype == 'ntlm') {
                    $this->debug('set cURL for NTLM authentication');
                    $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_NTLM);
                }
            }
            if (is_array($this->proxy)) {
                $this->debug('set cURL proxy options');
                if ($this->proxy['port'] != '') {
                    $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host'] . ':' . $this->proxy['port']);
                } else {
                    $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host']);
                }
                if ($this->proxy['username'] || $this->proxy['password']) {
                    $this->debug('set cURL proxy authentication options');
                    $this->setCurlOption(CURLOPT_PROXYUSERPWD, $this->proxy['username'] . ':' . $this->proxy['password']);
                    if ($this->proxy['authtype'] == 'basic') {
                        $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_BASIC);
                    }
                    if ($this->proxy['authtype'] == 'ntlm') {
                        $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_NTLM);
                    }
                }
            }
            $this->debug('cURL connection set up');
            return true;
        } else {
            $this->setError('Unknown scheme ' . $this->scheme);
            $this->debug('Unknown scheme ' . $this->scheme);
            return false;
        }
    }
566584
public function serve404()
	{
		$response = new Response();
		$response->setStatusCode(Response::HTTP_NOT_FOUND);

		return $this->render('Errors/404', [], $response);
	}
353382
public function get_normalized_http_url() {

        $parts = parse_url($this->http_url);

        $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http';
        $port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80');
        $host = (isset($parts['host'])) ? strtolower($parts['host']) : '';
        $path = (isset($parts['path'])) ? $parts['path'] : '';

        if (($scheme == 'https' && $port != '443')
            || ($scheme == 'http' && $port != '80')) {
            $host = "$host:$port";
        }

        return "$scheme://$host$path";

    }
834077
private function _rfc1123()
    {
        $date = new \DateTime(null, new \DateTimeZone("GMT"));
        return str_replace("+0000", "GMT", $date->format(\DateTime::RFC1123));
    }
399068
public function isSecure()
    {
        $https = $this->server('HTTPS');
        return !empty($https) && 'off' !== strtolower($https) || (int)$this->server('SERVER_PORT') === 443 || $this->server('HTTP_X_FORWARDED_PROTO') === 'https';
    }
213805
public function getDefaultPort()
    {
        if (!$this->hasDefaultPort()) throw new UrlException(sprintf(
            "No default port for URL '%s'",
            $this->_inputString
        ));

        $scheme = $this->getScheme();
        if ($scheme == 'http') return 80;
        elseif ($scheme == 'https') return 443;
        else throw new UrlException("No default port for scheme '$scheme'");
    }
875482
public static function isBehindSsl() : bool
  {
      // Check for proxy first
      if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
          return self::protocolWithActiveSsl($_SERVER['HTTP_X_FORWARDED_PROTO']);
      }

      if (isset($_SERVER['HTTPS'])) {
          return self::protocolWithActiveSsl($_SERVER['HTTPS']);
      }

      return $_SERVER['SERVER_PORT'] == 443;
  }
953949
public function setSocket()
    {
        if (empty($this->uri['scheme'])) {
            throw new OutOfBoundsException('Unknown URL scheme');
        }

        if ($this->uri['scheme'] === 'http') {
            $port = 80;
            $protocol = 'tcp';
        } else if ($this->uri['scheme'] === 'https') {
            $port = 443;
            $protocol = 'ssl';
        } else {
            throw new UnexpectedValueException("Unsupported URL scheme: {$this->uri['scheme']}");
        }

        if (isset($this->uri['port'])) {
            $port = $this->uri['port'];
        }

        $this->socket = "$protocol://{$this->uri['host']}:$port";

        if (!isset($this->headers['Host'])) {
            $this->headers['Host'] = "{$this->uri['host']}:$port";
        }

        return $this;
    }
200645
public static function isHTTPS($server = array())
    {

        $response = false;

        if (empty($server) && isset($_SERVER)) {
            $server = $_SERVER;
            if (!isset($server['SERVER_PORT'])) {
                $server['SERVER_PORT'] = 80;
            }
        } else {
            $server['HTTPS'] = getenv('HTTPS');
            $server['SERVER_PORT'] = getenv('SERVER_PORT');
        }

        if (isset($server['HTTPS']) && $server['HTTPS'] !== 'off'
            || $server['SERVER_PORT'] == 443
        ) {
            $response = true;
        }

        return $response;
    }
183544
public static function protocolHostPort()
    {
        if (RequestHelper::isCli()) {
            return null;
        }

        $isHttps = RequestHelper::isHttps();
        $protocol = 'http' . ($isHttps ? 's' : '');
        $serverName = $_SERVER['SERVER_NAME'];
        $serverPort = (int)$_SERVER['SERVER_PORT'];

        $protocolHostPort = $protocol . '://';

        if ((!$isHttps && $serverPort !== 80) || ($isHttps && $serverPort !== 443)) {
            $protocolHostPort .= $serverName . ':' . $serverPort;
        } else {
            $protocolHostPort .= $serverName;
        }

        return $protocolHostPort;
    }
1197553
private function abridgeUri($uri)
    {
        $i = 30;
        $j = 12;

        if (mb_strlen($uri) <= $i) {
            return $uri;
        }

        $host = rtrim(parse_url($uri, PHP_URL_HOST), '/');
        $path = '/'.ltrim(parse_url($uri, PHP_URL_PATH), '/');

        if ($host === getenv('HTTP_HOST')) {
            $i = 50;
            $j = 22;

            $host = '';
        } else {
            if (mb_strlen($host) > $i && mb_strlen($path) > $i) {
                return $this->abridgeStr($uri, 50, 22);
            }

            $host = $this->abridgeStr($host, 20, 7);
        }

        $path = $this->abridgeStr($path, $i, $j);

        return $host.$path;
    }
1137398
static function FilePost($url, $data = "", $verify_cert = false, $timeout = 30)
	{
		$qs = HttpRequest::ArrayToQueryString($data);
		$url = $url . ($qs ? "?" . $qs : "");

		$show_headers = false;
		$url = parse_url($url);

		if (!isset($url['port'])) {
			if ($url['scheme'] == 'http') { $url['port']=80; }
			elseif ($url['scheme'] == 'https') { $url['port']=443; }
		}
		$url['query']=isset($url['query'])?$url['query']:'';

		$url['protocol']=$url['scheme'].'://';
		$eol="\r\n";

		$headers =  "POST ".$url['protocol'].$url['host'].$url['path']." HTTP/1.0".$eol.
			"Host: ".$url['host'].$eol.
			"Referer: ".$url['protocol'].$url['host'].$url['path'].$eol.
			"Content-Type: application/x-www-form-urlencoded".$eol.
			"Content-Length: ".strlen($url['query']).$eol.
			$eol.$url['query'];
		$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
		if($fp)
		{
			fputs($fp, $headers);
			$result = '';
			while(!feof($fp)) { $result .= fgets($fp, 128); }
			fclose($fp);
			if (!$show_headers)
			{
				//removes headers
				$match = preg_split("/\r\n\r\n/s",$result,2);
				$result = $match[1];
			}

			return $result;
		}
	}
106877
public static function is_https(HTTPRequest $request = null)
    {
        // Check override from alternate_base_url
        if ($baseURL = self::config()->uninherited('alternate_base_url')) {
            $baseURL = Injector::inst()->convertServiceProperty($baseURL);
            $protocol = parse_url($baseURL, PHP_URL_SCHEME);
            if ($protocol) {
                return $protocol === 'https';
            }
        }

        // Check the current request
        $request = static::currentRequest($request);
        if ($request && ($scheme = $request->getScheme())) {
            return $scheme === 'https';
        }

        // Check default_base_url
        if ($baseURL = self::config()->uninherited('default_base_url')) {
            $baseURL = Injector::inst()->convertServiceProperty($baseURL);
            $protocol = parse_url($baseURL, PHP_URL_SCHEME);
            if ($protocol) {
                return $protocol === 'https';
            }
        }

        return false;
    }
481765
private int getPort(URI endpoint) {
        if (endpoint.getPort() != -1) {
            return endpoint.getPort();
        } else if ("https".equals(endpoint.getScheme())) {
            return 443;
        } else {
            return 80;
        }
    }
865821
protected function determineUri()
    {
        $params = $this->getServerParams();
        
        $parts = $this->mapUriPartsFromServerParams($params);
        
        if (
            isset($params['SERVER_PROTOCOL']) &&
            \Jasny\str_starts_with(strtoupper($params['SERVER_PROTOCOL']), 'HTTP/')
        ) {
            $parts['scheme'] = !empty($params['HTTPS']) && $params['HTTPS'] !== 'off' ? 'https' : 'http';
        }
        
        if (isset($parts['host'])) {
            list($parts['host']) = explode(':', $parts['host'], 2); // May include the port
        }
        
        if (isset($parts['path'])) {
            $parts['path'] = parse_url($parts['path'], PHP_URL_PATH); // Includes the query string
        }

        return new UriObject($parts);
    }