<?
/*
// Erik J. Barzeski's 404 Search Code
// http://nslog.com/2007/01/04/revised_404_search_for_wordpress/
// 
// You are free to copy and use this code anywhere you see fit
// so long as the above text remains in the file as it is here.
*/


// Get the actual name of the file referenced in the URL
$search_term substr$_SERVER["REQUEST_URI"], );
$pieces explode'/'$search_term );

// If the URL ends with /, get the "piece" before it.
if('/' == substr($search_term, -11))
{
    
$search_term $pieces[count($pieces) - 2];
}
else 
// Otherwise, get the last piece.
{
    
$search_term $pieces[count($pieces) - 1];
}

// Get rid of requests that think I'm running IIS
if( strstr($search_term'.dll') ||
    
strstr($search_term'.asp') ||
    
strstr($search_term'.exe')
    ) exit;
    
// Discard file extension, save extension in case it's an image
$pieces explode'.'$search_term );
$search_term $pieces[0];
$extension $pieces[1];
    
// No translated URL, so do a search for this term instead
$search_url 'http://nslog.com/?s=';

// If searching for images, put the extension back and don't take out '_'
if ($extension == "jpg" || $extension == "gif" || $extension == "png")
    
$search_term .= ".$extension";
else 
// Otherwise, remove "_" and replace with a space (%20)
    
$search_term str_replace('_''%20'$search_term);

// Create full search URL and perform search
$full_search_url $search_url $search_term;
$full_page implode""file$full_search_url ));


/*
// Email myself to monitor 404 searches
// I un-comment this when I make a change that results in more 404s than normal
$body_of_email = "Search URL: $full_search_url
Queried URL: " . $_SERVER["REQUEST_URI"] . "
Search Term(s): $search_term_fixed";
$clickable_search = str_replace('%20', ' ', $search_term);
@mail("me@mydomain.com", "Search Query: $clickable_search", $body_of_email);
*/


// Look for search results based on a unique regular expression string
// NOTE! This is likely the only thing you'll have to change to get this to work for you.
$search_string '/<a href="([^"]*)".*bookmark/';
$count preg_match_all($search_string$full_page$matches );

// If there's only one search match, go straight to the match
if( $count == ) {
    
header"Location: {$matches[1][0]}" );
}
// Otherwise, print the results
else {
    echo 
$full_page;
}

?>