<?php
/*
 * drop this in mu-plugins. by dd32
 */

add_filter('pre_update_option_siteurl', '_siteurl_pre_change', 5, 2);
function _siteurl_pre_change( $new, $old ) {
	$valid = _siteurl_is_valid( $new, $old );
	if ( ! is_wp_error( $valid ) )
		return $new;
		
	$message = sprintf(__( 'WordPress has detected that changing the WordPress Address of your Site to <code>%s</code> will result in WordPress not being accessable for the following reason(s)') , esc_html( $new ) );
	$message .= '<ul><li>' . $valid->get_error_message();
	$data = $valid->get_error_data();
	if ( is_wp_error( $data ) )
		$message .= ' <ul><li>' . $data->get_error_message() . '</li></ul>';
	$message .= '</li></ul>';
	$message .= '</p><p>' . '<input type="submit" value="' . esc_attr(__('Continue?')) . '" />';
	wp_die( $message );
	exit;
}

function _siteurl_is_valid($new, $old) {
	$_url = add_query_arg( 'testing-redirects', '1', $new );
	$res = wp_remote_head($_url);
	if ( is_wp_error($res) )
		return new WP_Error('unknown', __('WordPress cannot verify the suggested site URL'), $res );

	if ( isset($res['headers']['wordpress-redirection']) && 'ok' == $res['headers']['wordpress-redirection'] )
		wp_die( 'True: <pre>' . print_r(array($_url,$res), true) );
	
	if ( isset($res['headers']['wordpress-redirection']) && 'not-front-page' == $res['headers']['wordpress-redirection'] )
		return new WP_Error('not_wordpress_front', __('The Provided URL does not resolve to the front page of WordPress.') );
	
	if ( '200' == $res['response']['code'] ) // Something exists, but is not the WordPress we expected.
		return new WP_Error('not_wordpress', __('This WordPress Installation was not accessable at that URL.') );

	if ( in_array( $res['response']['code'], array(300, 301, 302) ) ) // Redirection elsewhere.
		return new WP_Error('unknown', sprintf(__('Redirection to %s'), $res['headers']['location']) );

	wp_die( 'Fallthrough:<pre>' . print_r(array($_url,$res), true) );
//	return true;
}

add_action('template_redirect', '_tr', 100);
function _tr() {
	if ( isset($_GET['testing-redirects']) ) {
		if ( is_front_page() )
			header('WordPress-Redirection: ok');
		else
			header('WordPress-Redirection: not-front-page');
		die();
	}
}