<?php
/*
 * Plugin Name: Permalinks redirect
 * Version: 0.3
 * Plugin URI: http://scott.yang.id.au/2005/05/permalink-redirect/
 * Description: This plugin ensures that we are viewing the permalink.
 * Author: Scott Yang
 * Author URI: http://scott.yang.id.au/
 */
function ysy_permalink_redirect () {
    global $posts;
    global $wp_query;

    $uri = $_SERVER['REQUEST_URI'];

    // 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 = get_query_var('m');
    if ($m) {
	$m = preg_replace('/[^0-9]/', '', $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;
	}
    } elseif (is_single() && (sizeof($posts) > 0)) {
	$post = $posts[0];
	$link = get_permalink($post->ID);
    } elseif (is_page() && (sizeof($posts) > 0)) {
	$post = $posts[0];
	$link = get_page_link($post->ID);
    } elseif (is_author()) {
	// 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()) {
	$link = get_category_link(get_query_var('cat'));
    } elseif (is_day()) {
	$link = get_day_link(get_query_var('year'),
			     get_query_var('monthnum'),
			     get_query_var('day'));
    } elseif (is_month()) {
	$link = get_month_link(get_query_var('year'),
			       get_query_var('monthnum'));
    } elseif (is_year()) {
	$link = get_year_link(get_query_var('year'));
    } else {
	return;
    }

    $parsed = parse_url($link);
    $pos = strpos($uri, $parsed['path']);
    if ($pos === false || $pos != 0) {
	header("HTTP/1.1 301 Moved Permanently");
	header("Location: $link");
	exit(0);
    }
}

add_action('template_redirect', 'ysy_permalink_redirect');
?>
