<?php
// Based on "Permalink Redirect" from Scott Yang and "Enforce www. Preference" by Mark Jaquith

function redirect_permalinks() {
	global $withcomments;

	$requested = @parse_url( $_SERVER['REQUEST_URI'] );
	if ( false === $requested )
		return;

	$requested = $requested['path'];
	$requested_scheme = ( isset($_SERVER['HTTPS'] ) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';

	if ( is_feed() || is_trackback() || is_search() || is_comments_popup() )
		return;

	$link = redirect_guess_permalink();
	if ( !$link )
		return;
	$permalink = @parse_url( $link );

	// WP2.1: If a static page has been set as the front-page, we'll get 
	// empty string here.
	if ( !$permalink['path'] )
		$permalink['path'] = '/';

	if ( $requested != $permalink['path'] ) {
		$redirect = $link;
	} else {
		$user_home = parse_url(get_option('home'));

		$user_home['scheme'] . '://' . $user_home['host'];

		if ( $user_home['host'] != $_SERVER['HTTP_HOST'] )
			$redirect = $requested_scheme . $user_home['host'] . $_SERVER['REQUEST_URI'];
	}

	if ( $redirect ) {
		wp_redirect($redirect, 301);
		exit();
	}
}

function redirect_guess_permalink() {
	global $posts;

	// For partial links
	if ( is_404() ) {
		global $wp_query, $wpdb;
		if ( !get_query_var( 'name' ) )
			return;

		$where = "post_name LIKE '" . $wpdb->escape( get_query_var( 'name' ) ) . "%'";

		// if any of year, monthnum, or day are set, use them to refine the query
		if ( get_query_var('year') )
			$where .= " AND YEAR(post_date) = '" . $wpdb->escape(get_query_var('year')) . "'";
		if ( get_query_var('monthnum') )
			$where .= " AND MONTH(post_date) = '" . $wpdb->escape(get_query_var('monthnum')) . "'";
		if ( get_query_var('day') )
			$where .= " AND DAYOFMONTH(post_date) = '" . $wpdb->escape(get_query_var('day')) . "'";

		$post_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'" );
		if ( !$post_id )
			return false;
		return get_permalink( $post_id );
	}

	$haspost = count( $posts ) > 0;
	if ( get_query_var('m') ) {
		// Handling special case with '?m=yyyymmddHHMMSS'
		// Since there is no code for producing the archive links for
		// is_time, we will give up and not trying any redirection.
		$m = preg_replace( '/[^0-9]/', '', get_query_var('m') );
		switch ( strlen($m) ) {
			case 4: // Yearly
				$link = get_year_link($m);
				break;
			case 6: // Monthly
				$link = get_month_link( substr($m, 0, 4), substr($m, 4, 2) );
				break;
			case 8: // Daily
				$link = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2));
				break;
			default:
				return false;
		}
	} elseif ( ( is_single() || is_page() ) && ( sizeof( $posts ) > 0 ) ) {
		$post = $posts[0];
		$link = get_permalink($post->ID);
		$page = get_query_var('page');
		if ( $page && $page > 1 )
			$link = trailingslashit( $link ) . user_trailingslashit($page);
	} elseif ( is_author() && $haspost ) {
		global $wp_version;
		if ( $wp_version >= '2' ) {
			$author = get_userdata(get_query_var('author'));
			if ( false === $author )
				return false;
			$link = get_author_link( false, $author->ID, $author->user_nicename );
		} else {
			// XXX: get_author_link() bug in WP 1.5.1.2
			//      s/author_nicename/user_nicename/
			global $cache_userdata;
			$userid = get_query_var('author');
			$link = get_author_link(false, $userid,
				$cache_userdata[$userid]->user_nicename);
		}
	} elseif ( is_category() && $haspost ) {
		$link = get_category_link(get_query_var('cat'));
	} elseif ( is_day() && $haspost ) {
		$link = get_day_link(get_query_var('year'),
							 get_query_var('monthnum'),
							 get_query_var('day'));
	} elseif (is_month() && $haspost) {
		$link = get_month_link(get_query_var('year'),
							   get_query_var('monthnum'));
	} elseif (is_year() && $haspost) {
		$link = get_year_link(get_query_var('year'));
	} elseif ( is_home() ) {
		// WP2.1. Handling "Posts page" option. 
		if ((get_option('show_on_front') == 'page') &&
			($reqpage = get_option('page_for_posts'))) 
		{
			$link = get_permalink($reqpage);
		} else {
			$link = trailingslashit(get_settings('home'));
		}
	} else {
		return false;
	}

	if ( is_paged() ) {
		$paged = get_query_var('paged');
		if ($paged)
			$link = trailingslashit($link) . user_trailingslashit("page/$paged");
	}

	return $link;
}

add_action('template_redirect', 'redirect_permalinks');

?>
