<?php
/*
Plugin Name: Rank Tracker
Plugin URI: http://ranktrackerplugin.com
Description: Shows you what keywords and position your pages are ranking for in Google
Author: Peter Coughlin
Version: 1.6
Author URI: http://petercoughlin.com

Changelog
---------
1.6		Added countries
1.5		Sorted export by Rank
		Removed commas in exported keywords and URLs
1.4		Added CSV export
1.3		Added previous rank
		Added keyword export
1.2		Added urlencoding for google query
1.1		Added email option
1.0		Initial version
*/

class rank_tracker_tool {
	function rank_tracker_tool() {
		$this->name = 'Rank Tracker';
		$this->version = '1.6';
		$plugin = plugin_basename(__FILE__);
		add_filter("plugin_action_links_$plugin", array(&$this, 'settings_link'));
		if ( !defined('WP_PLUGIN_URL') ) {
			if ( !defined('WP_CONTENT_DIR') ) define('WP_CONTENT_DIR', ABSPATH.'wp-content');
			if ( !defined('WP_CONTENT_URL') ) define('WP_CONTENT_URL', get_option('siteurl').'/wp-content');
			if ( !defined('WP_PLUGIN_DIR') ) define('WP_PLUGIN_DIR', WP_CONTENT_DIR.'/plugins');
			define('WP_PLUGIN_URL', WP_CONTENT_URL.'/plugins');
		}// end if
		register_deactivation_hook(__FILE__, array(&$this, 'deactivate'));
		add_action('template_redirect', array(&$this, 'action'));
	}// end function

	function deactivate() {
		delete_option('rank_tracker_tool');
	}// end function
	
	function settings_link($links) {
		$settings_link = '<a href="options-general.php?page=rank-tracker-tool/admin.php">Settings</a>';
		array_unshift($links,$settings_link);
		return $links;
	}// end function
	
	function action() {
		if ( $_SERVER['HTTP_REFERER'] ) {
			$referer = $_SERVER['HTTP_REFERER'];
			$options = $this->get_options();
			if ( 'localhost' == $_SERVER['HTTP_HOST'] )
				$country = 'http://localhost';
			else
				$country = $options['country'];
			if ( '' == $country )
				$country = 'http://www.google.com';
			if ( stripos($referer, $country) !== false ) {
				$querystring = substr(strstr($referer, '?'), 1);
				if ( strlen($querystring) ) {
					parse_str($querystring, $querystring);
					if ( is_array($querystring) && count($querystring) ) {
						$keyword = $querystring['q'];
						$rank = $querystring['cd'];
						$url = $querystring['url'];
						if ( strlen($keyword) && strlen($rank) && strlen($url) ) {
							$previousrank = $options['rankings'][$keyword]['rank'];
							if ( $rank != $previousrank ) {
								if ( intval($previousrank) == 0 ) $previousrank = '-';
								$options['rankings'][$keyword]['previousrank'] = $previousrank;
								if ( $options['sendemail'] )
									$this->sendemail($keyword, $previousrank, $rank, $url);
							}
							$options['rankings'][$keyword]['rank'] = $rank;
							$options['rankings'][$keyword]['url'] = str_replace(get_bloginfo('url'), '', $url);
							$options['rankings'][$keyword]['pr'] = $this->getpagerank($url);
							$options['rankings'][$keyword]['lastchecked'] = time();
							update_option('rank_tracker_tool', $options);
						}// end if
					}// end if
				}// end if
			}// end if
		}// end if
	}// end function

	function sendemail($keyword, $previousrank, $rank, $url) {
		$options = $this->get_options();
		$to_email = $options['to_email'];
		$from_email = $options['from_email'];
		$subject = $options['subject'];
		if ( '' == $to_email )
			$to_email = get_bloginfo('admin_email');
		if ( '' == $from_email )
			$from_email = 'wordpress@'.str_replace('www.', '', strtolower($_SERVER['SERVER_NAME']));
		if ( '' == $subject )
			$subject = 'Keyword rank update on '.get_bloginfo('name');
		$headers =  "MIME-Version: 1.0\r\n";
		$headers .= "From: $from_email\r\n";
		$headers .= "Content-Type: text/html; charset=\"".get_option('blog_charset')."\"\r\n";
		$message = '<html><head><style>p{font:normal 12px "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;}.small{margin-top:3.0em;font-size:10px;color:#999;}.small span{padding-top:3px;border-top:1px solid #ccc;}</style></head><body>';
		$message .= '<p>There has been a change in your Google rankings!</p>';
		$message .= '<p><b>'.$url.'</b> is now ranking at number <b><u>'.$rank.'</u></b> in Google for the keyword phrase: <b>'.stripslashes($keyword).'</b></p>';
		if ( $previousrank != '-' )
			$message .= '<p>It was previously ranking at number '.$previousrank.'.</p>';
		$message .= '<p class="small"><span>'.$this->name.' v'.$this->version.'. You can turn these messages off from the plugin settings page on your wordpress site.</span></p>';
		$message .= '</body></html>';
		mail($to_email, $subject, $message, $headers);
	}// end func

	function strtonum($str, $check, $magic) {
		$int32unit = 4294967296;
		$length = strlen($str);
		for ($i = 0; $i < $length; $i++) {
			$check *= $magic;
			if ( $check >= $int32unit ) {
				$check = ($check - $int32unit * (int) ($check / $int32unit));
				$check = ($check < -2147483648) ? ($check + $int32unit) : $check;
			}// end if
			$check += ord($str{$i});
		}// end for
		return $check;
	}// end func

	function hashurl($String) {
		$Check1 = $this->strtonum($String, 0x1505, 0x21);
		$Check2 = $this->strtonum($String, 0, 0x1003F);
		$Check1 >>= 2;
		$Check1 = (($Check1 >> 4) & 0x3FFFFC0 ) | ($Check1 & 0x3F);
		$Check1 = (($Check1 >> 4) & 0x3FFC00 ) | ($Check1 & 0x3FF);
		$Check1 = (($Check1 >> 4) & 0x3C000 ) | ($Check1 & 0x3FFF);
		$T1 = (((($Check1 & 0x3C0) << 4) | ($Check1 & 0x3C)) <<2 ) | ($Check2 & 0xF0F );
		$T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0x3C00)) << 0xA) | ($Check2 & 0xF0F0000 );
		return ($T1 | $T2);
	}// end func

	function checkhash($Hashnum) {
		$CheckByte = 0;
		$Flag = 0;
		$HashStr = sprintf('%u', $Hashnum);
		$length = strlen($HashStr);
		for ($i = $length - 1;$i >= 0;$i--) {
			$Re = $HashStr{$i};
			if ( 1 === ($Flag % 2) ) {
				$Re += $Re;
				$Re = (int)($Re / 10) + ($Re % 10);
			}// end if
			$CheckByte += $Re;
			$Flag++;
		}// end for
		
		$CheckByte %= 10;
		if ( 0 !== $CheckByte ) {
			$CheckByte = 10 - $CheckByte;
			if ( 1 === ($Flag % 2) ) {
				if ( 1 === ($CheckByte % 2) ) {
					$CheckByte += 9;
				}// end if
				$CheckByte >>= 1;
			}// end if
		}// end if
		return '7'.$CheckByte.$HashStr;
	}// end func

	function getpagerank($url) {
		$query = 'http://toolbarqueries.google.com/search?client=navclient-auto&ch='.$this->checkhash($this->hashurl($url)).'&features=Rank&q=info:'.urlencode($url).'&num=100&filter=0';
		$data = wp_remote_fopen($query);
		$pos = strpos($data, 'Rank_');
		if ( $pos === false ) {
			$pagerank = '-';
		} else {
			$pagerank = trim(substr($data, $pos + 9));
		}// end if
		return $pagerank;
	}// end func
	
	function get_options() {
		$options = get_option('rank_tracker_tool');
		if ( !is_array($options) )
			$options = $this->set_defaults();
		return $options;
	}// end function
	
	function set_defaults() {
		$options = array(
			'to_email' => get_bloginfo('admin_email'),
			'from_email' => 'wordpress@'.str_replace('www.', '', strtolower($_SERVER['SERVER_NAME'])),
			'subject' => 'Keyword rank update on '.get_bloginfo('name'),
			'sendemail' => true,
			'country' => 'http://www.google.com',
			'rankings' => array()
		);
		update_option('rank_tracker_tool', $options);
		return $options;
	}// end function

}// end class
$rank_tracker_tool = new rank_tracker_tool;

if ( is_admin() )
	include_once dirname(__FILE__).'/admin.php';
