User:Allen4names/Bug 14977

The following code was copied from DefaultSettings.php in MediaWiki 1.16.0.

/** URL of the server. It will be automatically built including https mode */
$wgServer = '';

if( isset( $_SERVER['SERVER_NAME'] ) ) {
	$wgServerName = $_SERVER['SERVER_NAME'];
} elseif( isset( $_SERVER['HOSTNAME'] ) ) {
	$wgServerName = $_SERVER['HOSTNAME'];
} elseif( isset( $_SERVER['HTTP_HOST'] ) ) {
	$wgServerName = $_SERVER['HTTP_HOST'];
} elseif( isset( $_SERVER['SERVER_ADDR'] ) ) {
	$wgServerName = $_SERVER['SERVER_ADDR'];
} else {
	$wgServerName = 'localhost';
}

# check if server use https:
$wgProto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';

$wgServer = $wgProto.'://' . $wgServerName;
# If the port is a non-standard one, add it to the URL
if(    isset( $_SERVER['SERVER_PORT'] )
	&& !strpos( $wgServerName, ':' )
    && (    ( $wgProto == 'http' && $_SERVER['SERVER_PORT'] != 80 )
	 || ( $wgProto == 'https' && $_SERVER['SERVER_PORT'] != 443 ) ) ) {

	$wgServer .= ":" . $_SERVER['SERVER_PORT'];
}

Here is the modified code.

/** URL of the server. It will be automatically built including https mode */
$wgServer = '';

if( isset( $_SERVER['SERVER_NAME'] ) ) {
	$wgServerName = $_SERVER['SERVER_NAME'];
} elseif( isset( $_SERVER['HOSTNAME'] ) ) {
	$wgServerName = $_SERVER['HOSTNAME'];
} elseif( isset( $_SERVER['HTTP_HOST'] ) ) {
	$wgServerName = $_SERVER['HTTP_HOST'];
} elseif( isset( $_SERVER['SERVER_ADDR'] ) ) {
	$wgServerName = $_SERVER['SERVER_ADDR'];
} else {
	$wgServerName = 'localhost';
}

# check if server use https:
$wgProto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';

if(	preg_match( '/^[0-9A-Fa-f]{0,4}:[0-9A-Fa-f]{0,4}:/', $wgServerName ) ) {
	$wgServer = $wgProto.'://[' . $wgServerName . ']';
} else {
	$wgServer = $wgProto.'://' . $wgServerName;
}

# If the port is a non-standard one, add it to the URL
if(    isset( $_SERVER['SERVER_PORT'] )
	&& substr_count( $wgServerName, ':' ) != 1
	&& !strpos( $wgServerName, ']:' )
    && (    ( $wgProto == 'http' && $_SERVER['SERVER_PORT'] != 80 )
	 || ( $wgProto == 'https' && $_SERVER['SERVER_PORT'] != 443 ) ) ) {
	$wgServer .= ":" . $_SERVER['SERVER_PORT'];
}
Notes
If $wgServerName matches '/^[0-9A-Fa-f]{0,4}:[0-9A-Fa-f]{0,4}:/' it is either an unbracketed IPv6 address or garbage.
If $wgServerName has just one colon in it or has ']:' as a substring don't add a port number.

This can be used to test for garbage.

<?php
echo '<html><head><title>Plain garbage</title></head><body><p><tt>';
echo 'SERVER_SOFTWARE: ' . $_SERVER['SERVER_SOFTWARE'];
echo '<br/>';
echo 'PHP version: ' . phpversion();
echo '<br/><br/>';
echo 'SERVER_NAME: ' . $_SERVER['SERVER_NAME'];
echo '<br/>';
echo 'HOSTNAME: ' . $_SERVER['HOSTNAME'];
echo '<br/>';
echo 'HTTP_HOST: ' . $_SERVER['HTTP_HOST'];
echo '<br/>';
echo 'SERVER_ADDR: ' . $_SERVER['SERVER_ADDR'];
echo '</tt></p></body></html>';
?>