<?php

    include_once( PLOG_CLASS_PATH."class/plugin/pluginbase.class.php" );
include_once( PLOG_CLASS_PATH."class/plugin/pluginmanager.class.php" );
include_once( PLOG_CLASS_PATH."class/net/url.class.php" );

/**
    * Implementation to highlight the search terms if the user is coming from google.
    *
    * Based on google_hilite from Textism, http://www.textism.com/tools/google_hilite/
    */
    class PluginGoogle extends PluginBase {

    	var $colors = Array( "yellow",
                             "lightpink",
                             "aquamarine",
                             "darkgoldenrod",
                             "darkseagreen",
                             "lightgreen",
                             "rosybrown",
                             "seagreen",
                             "chocolate",
                             "violet" );

    	function PluginGoogle()
        {
	    $this->PluginBase();
	    $this->id = "google";
            $this->desc = <<<EOD
This plugin will highlight the search terms entered by a Google user when arriving to
your blog.<br/><br/>To enable the plugin, you must include \{\$google->start()} somewhere in the
beginning of your page and \{\$google->end()} somewhere near the end. Anything else
outside the boundaries marked by the calls to the start() and end() methods will not
be highlighted by the plugin. A very effective solutions is to put \{\$google->start()}
in the very beginning of the header.template file and \{\$google->end()} and the very end
of the footer.template file, to ensure that all the content of your pages will be scanned.<br/>
<br/>
The plugin will automatically highlight the search terms and should you wish to display
a generated message containing information about the terms that have been highlighted, in the
same way Google does, then you can place the string <b>[googleplugin]</b> anywhere in your
templates and it will be automatically replaced by a message similar to:<br/><br/>
<b>Google user, I have highlighted the following terms for you:
<span style="background:yellow">term1</span>&nbsp;
<span style="background:lightpink">term2</span>&nbsp;
<span style="background:aquamarine">term3</span>&nbsp;</b>
<br/><br/>
If you wish to customize the way this message looks, it is possible to do so using
CSS. The message is included within a &lt;div class="googlepluginmessage"&gt;...&lt;/div&gt;
<br/><br/>
Please reports any bugs to the LifeType team! :)
EOD;

            $this->author = "The LifeType team";

            $this->totalReplacements = 0;
            $this->highlightedTerms  = "";
}

function start()
{
    ob_start();
}

function google_hilite($text) {

    //$ref = urldecode($_SERVER[HTTP_REFERER]);

    $url = new Url($_SERVER["HTTP_REFERER"]);

    # let's see if the referrer is google
    //if (preg_match('/^http:\/\/w?w?w?\.?google.*/i',$url->getHost())) {
	if (preg_match('/^w?w?w?\.?google.*/i',$url->getHost())) {

	    # chop the search terms into an array
            // and separate all the different parameters
            $reqParams = explode( "&", $url->getQuery());

            $query_array = Array();
            foreach( $reqParams as $param ) {
                // now, for every parameter, get rid of the '='
                $parts = explode( "=", $param );
                $var = $parts[0];
                $value = urldecode($parts[1]);
		if(strncmp($value, "site:", 5) && strncmp($value, "inurl:", 6)){
                    $query_array[$var] = $value;
 	        }
            }

	    if( $query_array["q"] == "" || empty($query_array["q"]))
		return false;

	    // otherwise, we can proceed to highlight the words!
            $searchTerms = explode( " ", $query_array["q"]);
	    // assign a color to each google search term
                $i=0;
	    $this->highlightedTerms = "<div class=\"googlepluginmessage\">Welcome Google user, I have highlighted the following terms for you: ";

	    for($i=0; $i<count($searchTerms); $i++ ) {
		$searchTerms[$i] = trim(str_replace( "+", "", $searchTerms[$i]));
		$searchTerms[$i] = str_replace( "\"", "", $searchTerms[$i]);
		$assignedColors[$searchTerms[$i]] = $this->colors[$i%count($this->colors)];

		$this->highlightedTerms .= "<span style=\"background:".$assignedColors[$searchTerms[$i]]."\">".$searchTerms[$i]."</span>&nbsp;";
	    }

	    //print($highlightedTerms);
	    $this->highlightedTerms .= "</div>";

	    # loop through the search terms
	    foreach($searchTerms as $b){

		if( $b != "" || !empty($b)) {
		    //$b = trim($b);
		    // if the string ends up having '+' sings, the regular expression
                        // parser will surely not like it!
                        $b = trim(str_replace( "+", "", $b ));
		    if (!preg_match('/<.+>/',$text)) {
			# If there are no tags in the text, we'll just do a simple search and replace
			$text = preg_replace('/(\b'.$b.'\b)/i','<span style="background:'.$assignedColors[$b].'">$1</span>',$text);
			$this->totalReplacements++;
		    }
		    else {
			# If there are tags, we need to stay outside them
			$text = preg_replace('/(?<=>)([^<]+)?(\b'.$b.'\b)/i','$1<span style="background:'.$assignedColors[$b].'">$2</span>',$text);
			$this->totalReplacements++;
		    }
		}
	    }
	}

	return $text;
    }

    function end()
    {
	$contents = ob_get_contents();

	ob_end_clean();

	$hilite = $this->google_hilite($contents);
	$hilite = str_replace( "[googleplugin]", $this->highlightedTerms, $hilite );

	print( $hilite );
    }
}

?>
