. */ ! defined('ABSPATH') || ! function_exists('add_options_page') || ! function_exists('add_action') || ! function_exists('wp_die') && die('death by askapache firing squad'); ! defined('COOKIEPATH') && define('COOKIEPATH', preg_replace('|https?://[^/]+|i', '', get_option('home') . '/')); ! defined('SITECOOKIEPATH') && define('SITECOOKIEPATH', preg_replace('|https?://[^/]+|i', '', get_option('siteurl') . '/')); ! defined('ADMIN_COOKIE_PATH') && define('ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin'); ! defined('PLUGINS_COOKIE_PATH') && define('PLUGINS_COOKIE_PATH', preg_replace('|https?://[^/]+|i', '', WP_PLUGIN_URL)); ! defined('WP_CONTENT_DIR') && define('WP_CONTENT_DIR', ABSPATH . 'wp-content'); ! defined('WP_PLUGIN_DIR') && define('WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins'); ! defined('WP_CONTENT_URL') && define('WP_CONTENT_URL', get_option('siteurl') . '/wp-content'); ! defined('WP_PLUGIN_URL') && define('WP_PLUGIN_URL', WP_CONTENT_URL . '/plugins'); class AskApacheGoogle404 { var $options = false; var $plugin = false; var $errors = false; var $messages = false; var $code = 404; var $message; var $reason; var $ASC = array( 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', 226 => 'IM Used', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => 'Reserved', 307 => 'Temporary Redirect', 400 => array('Bad Request', "Your browser sent a request that this server could not understand."), 401 => array('Unauthorized', "This server could not verify that you are authorized to access the document requested."), 402 => array('Payment Required', "%I_ERR%"), 403 => array('Forbidden', "You don't have permission to access %R_URI% on this server."), 404 => array('Not Found', "We couldn't find that uri on our server, though it's most certainly not your fault."), 405 => array('Method Not Allowed', "The requested method %R_METH% is not allowed for the URL %R_URI%."), 406 => array('Not Acceptable', "An appropriate representation of the requested resource %R_URI% could not be found on this server."), 407 => array('Proxy Authentication Required', "An appropriate representation of the requested resource %R_URI% could not be found on this server."), 408 => array('Request Timeout', "Server timeout waiting for the HTTP request from the client."), 409 => array('Conflict', "%I_ERR%"), 410 => array('Gone', "The requested resource%R_URI%is no longer available on this server and there is no forwarding address. Please remove all references to this resource."), 411 => array('Length Required', "A request of the requested method GET requires a valid Content-length."), 412 => array('Precondition Failed', "The precondition on the request for the URL %R_URI% evaluated to false."), 413 => array('Request Entity Too Large', "The requested resource %R_URI% does not allow request data with GET requests, or the amount of data provided in the request exceeds the capacity limit."), 414 => array('Request-URI Too Long', "The requested URL's length exceeds the capacity limit for this server."), 415 => array('Unsupported Media Type', "The supplied request data is not in a format acceptable for processing by this resource."), 416 => array('Requested Range Not Satisfiable', ""), 417 => array('Expectation Failed', "The expectation given in the Expect request-header field could not be met by this server. The client sent Expect:"), 422 => array('Unprocessable Entity', "The server understands the media type of the request entity, but was unable to process the contained instructions."), 423 => array('Locked', "The requested resource is currently locked. The lock must be released or proper identification given before the method can be applied."), 424 => array('Failed Dependency', "The method could not be performed on the resource because the requested action depended on another action and that other action failed."), 425 => array('No Code', "%I_ERR%"), 426 => array('Upgrade Required', "The requested resource can only be retrieved using SSL. Either upgrade your client, or try requesting the page using https://"), 500 => array('Internal Server Error', "%I_ERR%"), 501 => array('Not Implemented', " %R_METH% to %R_URI% not supported."), 502 => array('Bad Gateway', "The proxy server received an invalid response from an upstream server."), 503 => array('Service Unavailable', "The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later."), 504 => array('Gateway Timeout', "The proxy server did not receive a timely response from the upstream server."), 505 => array('HTTP Version Not Supported', "%I_ERR%"), 506 => array('Variant Also Negotiates', "A variant for the requested resource %R_URI% is itself a negotiable resource. This indicates a configuration error."), 507 => array('Insufficient Storage', "The method could not be performed. There is insufficient free space left in your storage allocation."), 510 => array('Not Extended', "A mandatory extension policy in the request is not accepted by the server for this resource.") ); /** * AskApacheGoogle404::AskApacheGoogle404() */ function AskApacheGoogle404() { global $wpdb; $this->LoadOptions(); add_action('wp_head', array(&$this, 'wp_header')); add_filter('wp_title', array(&$this, 'title_fix')); add_action('template_redirect', array(&$this, 'template_redirect'), 1); if (is_admin()) { $_GET['TB_iframe']=null; add_filter('plugin_action_links_' . $this->plugin['pb'], array(&$this, 'plugin_action_links')); add_action('activate_' . $this->plugin['pb'], array(&$this, 'activate')); add_action('deactivate_' . $this->plugin['pb'], array(&$this, 'deactivate')); add_action('admin_menu', array(&$this, 'admin_menu')); add_action('admin_notices', array(&$this, 'admin_notices')); add_action('load-' . $this->plugin['hook'], array(&$this, 'load')); } else return; } /* * +-------------------------------------------------------+ * | | * | Activation / Deactivation * | | * +-------------------------------------------------------+ */ /** * AskApacheGoogle404::activate() */ function activate() { $this->InitOptions(); } /** * AskApacheGoogle404::deactivate() */ function deactivate() { $options = get_option('askapache_google_404_options'); update_option('aa_google_404_api_key', $options['api_key']); delete_option('askapache_google_404_options'); //delete_option('askapache_google_404_plugin'); } /* * +-------------------------------------------------------+ * | | * | Hooks, Filters, Actions * | | * +-------------------------------------------------------+ */ /** * AskApacheGoogle404::admin_menu() */ function admin_menu() { //$page_title, $menu_title, $access_level, $file, $function add_options_page($this->plugin['Plugin Name'], $this->plugin['Short Name'], 8, $this->plugin['page'], array(&$this, 'options_page')); } /** * AskApacheGoogle404::admin_notices() */ function admin_notices() { if ($this->options['api_key'] != '') return; printf(__('

%s needs attention: please enter an API key or disable the plugin.

'), $this->plugin['action'], $this->plugin['Plugin Name']); } /** * AskApacheGoogle404::plugin_action_links() */ function plugin_action_links($links) { return array_merge(array('Settings'), $links); } /** * AskApacheGoogle404::template_redirect() */ function template_redirect() { if (is_404()) $this->askapache_404_handler(); else return false; } /** * AskApacheGoogle404::load() */ function load() { add_thickbox(); wp_enqueue_script('theme-preview'); if ($_SERVER['REQUEST_METHOD'] == 'POST') $this->handle_post(); } /* * +-------------------------------------------------------+ * | | * | Plugin Options * | | * +-------------------------------------------------------+ */ /** * AskApacheGoogle404::LoadOptions() */ function LoadOptions() { $options = get_option('askapache_google_404_options'); $plugin = get_option('askapache_google_404_plugin'); if (is_array($options) && sizeof($options) > 1 && is_array($plugin) && sizeof($plugin) > 1) { foreach ($options as $k => $v) $this->options[$k] = $v; foreach ($plugin as $k => $v) $this->plugin[$k] = $v; } else $this->InitOptions(); } /** * AskApacheGoogle404::InitOptions() */ function InitOptions() { $this->plugin = $this->get_plugin_data(); $this->options = array('old_api_key' => '', 'old_code_html' => '', 'old_code_css' => '', 'old_code_js' => '', 'db_version' => '', 'version' => '', 'api_key' => '', 'related_posts_title'=>'

More Related Pages to the Request

', 'related_posts_number'=> '10', 'related_posts_length'=> '240', 'recent_posts_title'=>'

Most Recent Posts

', 'recent_posts_number'=> '6', 'show_related'=> '1', 'show_recent'=> '1', 'show_google_404'=>'1', 'code_html' => '

%title%


', 'code_css' => '', 'code_js' => ''); $upgrade = get_option('aa_google_404_api_key'); if ($upgrade) { $search_replace = array('aalabel' => 'aa_LABEL', 'aamysite' => 'aa_MYSITE', 'aaexecute' => 'aa_XX'); foreach (array('api_key', 'code_html', 'code_css', 'code_js') as $k) { $v = false; $v = get_option('aa_google_404_' . $k); if ($v && ! empty($v)) { $v = str_replace(array_keys($search_replace), array_values($search_replace), $v); $this->options['old_' . $k] = $v; if ($k == 'api_key') $this->options[$k] = $v; } delete_option('aa_google_404_' . $k); } } $this->SaveOptions(); } /** * AskApacheGoogle404::SaveOptions() */ function SaveOptions() { $pluginoldvalue = get_option("askapache_google_404_plugin"); update_option("askapache_google_404_options", $this->options); if ($pluginoldvalue != $this->plugin) update_option("askapache_google_404_plugin", $this->plugin); return true; } /* * +-------------------------------------------------------+ * | | * | User Input * | | * +-------------------------------------------------------+ */ /** * AskApacheGoogle404::handle_post() */ function handle_post() { if (current_user_can('manage_options') && current_user_can('edit_themes')) { if (! wp_verify_nonce($_POST['_wpnonce'], 'aa404_google_ajax_search_form')) die('ERROR: Incorrect Form Submission, please try again.'); foreach ( array('api_key', 'related_posts_title', 'related_posts_number', 'related_posts_length', 'recent_posts_title', 'recent_posts_number') as $k) { $v = 'aa404_' . $k; $this->options[$k] = ( isset($_POST[$v]) && $_POST[$v] != $this->options[$k] ) ? $_POST[$v] : $this->options[$k]; } foreach ( array('show_google_404', 'show_related', 'show_recent') as $k) { $v = 'aa404_' . $k; $this->options[$k] = ( !isset($_POST[$v]) ) ? '0' : '1'; } foreach (array('code_css', 'code_html', 'code_js') as $k) { $v = 'aa404_' . $k; if (isset($_POST[$v])) $this->options[$k] = stripslashes($_POST[$v]); } $this->SaveOptions(); } } /** * AskApacheGoogle404::options_page() */ function options_page() { echo '
'; if ($this->options['api_key'] == '') { echo "

"; echo ""; echo "Click Here to Get a Google API Key!

"; } echo '

If your active theme has a 404.php file it is used, otherwise the plugin handles it. If you use a 404.php file, add this the following code where you want the plugin output to be displayed..

'; echo '
<?php if(function_exists("aa_google_404"))aa_google_404();?>
'; echo '

If your server allows .htaccess files and this plugin isnt working, then add this to your .htaccess (everyone should if they have htaccess capability). Look for another update in a few, enjoy!

ErrorDocument 404 /index.php?error=404'."\n".'Redirect 404 /index.php?error=404
'; $this->google_ajax_search_form(); // ?>

More Info from Google


options[$id] . "\n", "\n") - 2); $rows= ($rows > 25)? 25 : $rows; ?>

Test Your 404


form_field(1,'Show Google 404 Helper', 'show_google_404', 'Displays Google New 404 Helper');?> form_field(1,'Show Related Posts', 'show_related', 'Displays List of Posts similar to the query');?> form_field(1,'Show Recent Posts', 'show_recent', 'Displays List of Recent Posts');?>


form_field(2,'Related Posts Title', 'related_posts_title', 'Displayed above the related posts..');?> form_field(2,'Number of Related Posts to Show', 'related_posts_number', 'How many related posts to show..');?> form_field(2,'Related Posts Excerpt Length', 'related_posts_length', 'How many related posts to show..');?> form_field(2,'Recent Posts Title', 'recent_posts_title', 'Displayed above the recent posts..');?> form_field(2,'Number of Recent Posts to Show', 'recent_posts_number', 'How many recent posts to show..');?> options['api_key']=='')echo 'Get an API Key!'; ?> form_field(2,'API Key', 'api_key', 'This identifies your blog to Google.');?>

form_field(3,'HTML Code', 'code_html', 'The html that controls the google ajax search results.. (%title% is replaced with the status code and error phrase - 404 Not Found)');?> form_field(3,'CSS Code', 'code_css', 'The css that controls the google ajax search results.. (and anything else on the page)');?> form_field(3,'JavaScript Code', 'code_js', 'The javscript that runs the google ajax search.. (and anything else on the page)');?>

'The server encountered an internal error or misconfiguration and was unable to complete your request.', '%R_URI%' => attribute_escape(stripslashes($_SERVER['REQUEST_URI'])), '%R_METH%' => $_SERVER['REQUEST_METHOD'] ); $this->code = (int)$current_code; $this->message = (isset($this->ASC[$this->code][1])) ? str_replace(array_keys($search_and_replace), array_values($search_and_replace), $this->ASC[$this->code][1]) : ''; $this->reason = $this->ASC[$this->code][0]; ob_start(); @header("HTTP/1.1 {$this->code} {$this->reason}", 1); @header("Status: {$this->code} {$this->reason}", 1); if ($this->code == 400 || $this->code == 403 || $this->code == 405 || (string )$this->code[0] == '5') $this->handle_non_404(); elseif ( file_exists( TEMPLATEPATH . '/404.php' ) ) load_template(TEMPLATEPATH . '/404.php'); else load_template(dirname(__FILE__) . '/404.php'); } /** * AskApacheGoogle404::title_fix() */ function title_fix($title) { if (! is_404()) return $title; return $this->code . ' ' . $this->reason; } /** * AskApacheGoogle404::handle_non_404() */ function handle_non_404() { if ($this->code == 405) @header('Allow: GET,HEAD,POST,OPTIONS,TRACE'); @header("Connection: close", 1); echo "\n\n{$this->code} {$this->reason}\n"; echo "

{$this->reason}

\n

{$this->message}
\n

\n"; ob_flush(); flush(); exit; exit(); } /** * AskApacheGoogle404::wp_header() */ function wp_header() { if (! is_404()) return; $aa_label = get_option('blogname'); $aa_execute = aa_get_keywords('|', 6); $aa_best_guess_keywords = aa_get_keywords(' ', 2); $aa_best_guess = 'OR allinurl:' . $aa_best_guess_keywords; $aa_mysite = str_replace('www.', '', $_SERVER['HTTP_HOST']); echo "\n\n" . '' . "\n"; echo ''; echo "\n" . '' . "\n"; echo $this->options['code_js']; echo $this->options['code_css']; echo "\n" . '' . "\n\n"; } /** * AskApacheGoogle404::get_plugin_data() */ function get_plugin_data($find = array('Description', 'Author', 'Version', 'DB Version', 'Requires at least', 'Tested up to', 'WordPress', 'Plugin', 'Plugin Name', 'Short Name', 'Domain Path', 'Text Domain', '(?:[a-z]{2,25})? URI')) { $fp = fopen(__FILE__, 'r'); if(!is_resource($fp))return false; $data = fread($fp, 1000); fclose($fp); $mtx = $plugin = array(); preg_match_all('/(' . join('|', $find) . ')\:[\s\t]*(.+)/i', $data, $mtx, PREG_SET_ORDER); foreach ($mtx as $m) $plugin[trim($m[1])] = str_replace(array("\r","\n","\t"), '', trim($m[2])); $plugin['pb'] = preg_replace('|^' . preg_quote(WP_PLUGIN_DIR, '|') . '/|', '', __FILE__); $plugin['Title'] = '' . $plugin['Plugin Name'] . ''; $plugin['Author'] = '' . $plugin['Author'] . ''; $plugin['page'] = basename(__FILE__); $plugin['hook'] = 'settings_page_' . rtrim($plugin['page'], '.php'); $plugin['action'] = 'options-general.php?page=' . $plugin['page']; return $plugin; } } /** * askapache_g404_loader_init() */ function askapache_g404_loader_init() { global $AskApacheGoogle404; $AskApacheGoogle404 = new AskApacheGoogle404(); } add_action('plugins_loaded', 'askapache_g404_loader_init'); /** * aa_get_keywords() */ function aa_get_keywords($sep, $num=6) { $comp_words = $found_words = array(); preg_match_all("/[\w]{3,15}/", strtolower(html_entity_decode(strip_tags($_SERVER['REQUEST_URI'],' '.$_SERVER['QUERY_STRING']))), $found_words); foreach (array_unique((array)$found_words[0]) as $key => $aa_word) $comp_words[] = $aa_word; if (sizeof((array)$comp_words) > 0) { shuffle($comp_words); if (sizeof($comp_words) > $num) array_splice($comp_words, $num + 1); } return ((sizeof($comp_words) >0) ? trim(implode($sep, $comp_words)) : $_SERVER['HTTP_HOST']); } /** * aa_related_posts_404() */ function aa_related_posts_404($limit=15, $len=120) { global $wpdb; $terms = aa_get_keywords(' '); if(strlen($terms)<3) return; $now = gmdate("Y-m-d H:i:s", (time() + (get_settings('gmt_offset') * 3600))); $results = $wpdb->get_results("SELECT ID, post_title, post_content, "."MATCH (post_name, post_content) AGAINST ('$terms') AS score FROM $wpdb->posts ". "WHERE MATCH (post_name, post_content) AGAINST ('$terms') "."AND post_date <= '$now' ". "AND (post_status IN ( 'publish', 'static' )) AND post_password ='' ORDER BY score DESC LIMIT $limit"); if ($results){ $output=''; foreach ($results as $result) $output.= sprintf( '
  • %2$s

    %3$s...

  • %4$s', get_permalink($result->ID), attribute_escape(stripslashes(apply_filters('the_title', $result->post_title))), substr(wp_trim_excerpt(stripslashes(strip_tags($result->post_content))), 0, $len),"\n"); echo "\n