<?php
/*
Plugin Name: Landing sites
Plugin URI: http://theundersigned.net/2006/06/landing-sites-11
Description: When visitors is referred to your site from a search engine, they are definitely looking for something specific - often they just roughly check the page they land on and then closes the window if what they are looking for isn't there. Why not help them by showing them related posts to their search on your blog? This plugin/guide lets you do that, works with a long list of search engines! Plugin is made with help from these scripts: http://www.w-a-s-a-b-i.com/archives/2006/02/02/wordpress-related-entries-20/ - http://textsnippets.com/posts/show/231 - http://www.lazaryn.com/entry-28.html
Version: 1.3
Author: The undersigned
*/

function ls_get_delim($ref) {
    
// Search engine match array
    // Used for fast delimiter lookup for single host search engines.
    // Non .com Google/MSN/Yahoo referrals are checked for after this array is checked

    
$search_engines = array('google.com' => 'q',
            
'go.google.com' => 'q',
            
'maps.google.com' => 'q',
            
'local.google.com' => 'q',
            
'search.yahoo.com' => 'p',
            
'search.msn.com' => 'q',
            
'msxml.excite.com' => 'qkw',
            
'search.lycos.com' => 'query',
            
'alltheweb.com' => 'q',
            
'search.aol.com' => 'query',
            
'search.iwon.com' => 'searchfor',
            
'ask.com' => 'q',
            
'ask.co.uk' => 'ask',
            
'search.cometsystems.com' => 'qry',
            
'hotbot.com' => 'query',
            
'overture.com' => 'Keywords',
            
'metacrawler.com' => 'qkw',
            
'search.netscape.com' => 'query',
            
'looksmart.com' => 'key',
            
'dpxml.webcrawler.com' => 'qkw',
            
'search.earthlink.net' => 'q',
            
'search.viewpoint.com' => 'k',
            
'mamma.com' => 'query',
      
'pesquisa.sapo.pt' => 'q',
      
'search.live.com' => 'q',
      
'altavista.com' => 'q');

    
$delim false;

    
// Check to see if we have a host match in our lookup array
    
if (isset($search_engines[$ref])) {
        
$delim $search_engines[$ref];
    } else {
        
// Lets check for referrals for international TLDs and sites with strange formats

        // Optimizations
        
$sub13 substr($ref013);

        
// Search string for engine
        
if(substr($ref07) == 'google.')
            
$delim "q";
        elseif(
$sub13 == 'search.atomz.')
            
$delim "sp-q";
        elseif(
substr($ref011) == 'search.msn.')
            
$delim "q";
        elseif(
$sub13 == 'search.yahoo.')
            
$delim "p";
        elseif(
preg_match('/home\.bellsouth\.net\/s\/s\.dll/i'$ref))
            
$delim "bellsouth";
        elseif(
$sub13 == 'busca.uol.com')
            
$delim "q";
        elseif(
$sub13 == 'buscador.terr')
            
$delim "query";
        elseif(
$sub13 == 'farejador-1.i')
            
$delim "palavraChave";
        elseif(
$sub13 == 'farejador-2.i')
            
$delim "palavraChave";
        elseif(
$sub13 == 'farejador-3.i')
            
$delim "palavraChave";
    }
    return 
$delim;
}

function 
ls_get_terms($d) {
    
$terms       null;
    
$query_array = array();
    
$query_terms null;

    
// Get raw query
    
$query explode($d.'='$_SERVER['HTTP_REFERER']);
    
$query explode('&'$query[1]);
    
$query urldecode($query[0]);

    
// Remove quotes, split into words, and format for HTML display
    
$query str_replace("'"''$query);
    
$query str_replace('"'''$query);
    
$query_array preg_split('/[\s,\+\.]+/',$query);
    
$query_terms implode(' '$query_array);
    
$terms htmlspecialchars(urldecode($query_terms));

    return 
$terms;
}

function 
ls_get_refer() {
    
// Break out quickly so we don't waste CPU cycles on non referrals
    
if (!isset($_SERVER['HTTP_REFERER']) || ($_SERVER['HTTP_REFERER'] == '')) return false;

    
$referer_info parse_url($_SERVER['HTTP_REFERER']);
    
$referer $referer_info['host'];

    
// Remove www. is it exists
    
if(substr($referer04) == 'www.')
        
$referer substr($referer4);

    return 
$referer;
}

function 
ls_related($limit=5$len=10$before_title ''$after_title ''$before_post ''$after_post ''$show_pass_post false$show_excerpt false) {
   
    global 
$wpdb$id;

    
// Did we come from a search engine? 
    
$referer ls_get_refer();
    if (!
$referer) return false;

    
$delimiter ls_get_delim($referer);

    if(
$delimiter
    { 
        
$terms ls_get_terms($delimiter);

        
$time_difference get_settings('gmt_offset');
        
$now gmdate("Y-m-d H:i:s",(time()+($time_difference*3600)));

        
// Primary SQL query
    
        
$sql "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' )) ";
        if (
$show_pass_post=='false') { $sql .= "AND post_password ='' "; }
        
$sql .= "ORDER BY score DESC LIMIT $limit";
        
$results $wpdb->get_results($sql);
        
$output '';
        if (
$results) {
            foreach (
$results as $result) {
                
$title stripslashes(apply_filters('the_title'$result->post_title));
                
$permalink get_permalink($result->ID);
                
$post_content strip_tags($result->post_content);
                
$post_content stripslashes($post_content);
                
$output .= $before_title .'<a href="'$permalink .'" rel="bookmark" title="Permanent Link: ' $title '">' $title '</a>' $after_title;
                if (
$show_excerpt=='true') {
                    
$words=split(" ",$post_content); 
                    
$post_strip join(" "array_slice($words,0,$len));
                    
$output .= $before_post $post_strip $after_post;
                }
            }
            echo 
$output;
        } else {
            echo 
$before_title.'No related posts'.$after_title;
        }
    }
}

// Return true if the referer is a search engine
function ls_getinfo($what) {

    
// Did we come from a search engine? 
    
$referer ls_get_refer();
    if (!
$referer) return false;
    
$delimiter ls_get_delim($referer);

    if(
$delimiter
    { 
        
$terms ls_get_terms($delimiter);

        if(
$what == 'isref') { return true; }
        if(
$what == 'referrer') {
            
$parsed parse_url($_SERVER['HTTP_REFERER']);
            echo 
'<a href="http://'.$parsed['host'].'">'.$parsed['host'].'</a>';
        }
        if(
$what == 'terms') { echo $terms; }
        
    } 



function 
ls_install() {
    global 
$wpdb;
    global 
$table_prefix;
    
    
$sql 'ALTER TABLE `'.$table_prefix.'posts` ADD FULLTEXT `post_related` ( `post_name` ,'
    
' `post_content` )';
    
    
$wpdb->hide_errors();
    
$sql_result $wpdb->query($sql);
    
$wpdb->show_errors();
}

register_activation_hook(__FILE__'ls_install');


function 
ls_set_header() {
    if (
ls_getinfo('isref')) header('Vary: Referer'FALSE);
}

add_action('init''ls_set_header');
?>