<?php
/*
Plugin Name: Indexing Tool
Plugin URI: http://indexingtool.com/
Description: Helps get your links indexed...
Author: Peter Coughlin
Version: 1.6.5
Author URI: http://indexingtool.com/

Changelog
---------
1.6.5	Added option to open links in new window.
1.6.4	Updated checking code for new google interface
1.6.3	Added check for is_feed and is_404 before debug output.
1.6.2	Updated to also display unchecked links.
1.6.1	Fixed bug in checking unindexed urls first.
1.6		Added debug mode.
		Added status for ip banned by google.
1.5		Added automatic feed refresh.
		Added widget.
1.4		Added check for no URLs.
1.3		Added option for delay between google checks.
1.2		Added option to not show links on posts.
		Added option to show links on pages.
1.1		Separated indexed URLs.
1.0		Initial version.
*/

class indexing_tool {

	function indexing_tool() {

		$this->name = 'Indexing Tool';
		$this->version = '1.6.5';

		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_filter('the_content', array(&$this, 'filter'));		
		add_action('template_redirect', array(&$this, 'action'));
		$plugin = plugin_basename(__FILE__);
		add_filter("plugin_action_links_$plugin", array(&$this, 'settings_link'));

	}// end func
	
	function deactivate() {
		$options = $this->get_options();
		if ( $options['remove_settings'] )
			delete_option('indexing_tool');
	}// end func
	
	function settings_link($links) {
		$settings_link = '<a href="options-general.php?page=indexing-tool/admin.php">Settings</a>';
		array_unshift($links,$settings_link);
		return $links;
	}// end func
	
	function filter($content) {
		if ( !is_singular() || is_feed() )
			return $content;
		$options = $this->get_options();
		if ( !count($options['urls']) )
			return $content;
		if ( is_single() && $options['show_on_posts'] == false )
			return $content;
		if ( $options['new_window'] )
			$target = ' target="_blank"';
		global $post;
		if ( is_single() || (is_page() && in_array($post->ID, $options['linkspages'])) ) {
			$count = $options['max_links'];
			$links = array();
			if ( $count ) {
				$i = 0;
				foreach ( $options['urls'] as $url => $stats ) {
					if ( $stats['status'] != 'indexed' ) {
						$links[$url] = $stats['title'];
						$i++;
					}// end if
					if ( $i == $count )
						break;
				}// end foreach			
			}// end if
		}// end if
		if ( count($links) ) {
			$output = '';
			if ( '' != $options['title'] )
				$output .= stripslashes($options['title']);
			$output .= '<ul class="idxt">';
			foreach ( $links as $url => $title )
				$output .= '<li><a href="'.stripslashes($url).'" title="'.stripslashes($title).'"'.$target.'>'.stripslashes($title).'</a></li>';
			$output .= '</ul>';
		}// end if
		return $content.$output;
	}// end func
	
	function action() {
		$options = $this->get_options();
		if ( $options['debug'] ) $this->debug('plugin action called');
		if ( $options['debug'] ) $this->debug('current time = '.current_time('timestamp').', last check = '.$options['lastcheck'].', delay = '.$options['delay']);
		if ( current_time('timestamp') > (intval($options['delay']) + $options['lastcheck']) ) {
			$checkunindexed = true;
			if ( is_array($options['urls']) && count($options['urls']) ) {
				if ( $options['debug'] ) $this->debug('urls found in options');
				// initial check of each url
				foreach ( $options['urls'] as $url => $stats ) {
					// work through all unchecked urls first
					if ( $stats['status'] == 'unchecked' ) {
						if ( $options['debug'] ) $this->debug('checking '.$url);
						$status = $this->get_status($url);
						if ( $options['debug'] ) $this->debug('result = '.$status);
						if ( $status == 'indexed' ) {
							$options['indexed_urls'][$url]['status'] = 'indexed';
							$options['indexed_urls'][$url]['title'] = $options['urls'][$url]['title'];
							unset($options['urls'][$url]);
						} else {
							$options['urls'][$url]['status'] = $status;
						}// end if
						// we don't want to check the unindexed urls just yet..
						$checkunindexed = false;
						if ( count($options['urls']) )
							break;
					}// end if
				}// end foreach
				// random check of unindexed urls
				if ( $checkunindexed ) {
					if ( $options['debug'] ) $this->debug('checking un-indexed urls');
					$url = array_rand($options['urls']);
					if ( $options['debug'] ) $this->debug('checking '.$url);
					$status = $this->get_status($url);
					if ( $options['debug'] ) $this->debug('result = '.$status);
					if ( $status == 'indexed' ) {
						$options['indexed_urls'][$url]['status'] = 'indexed';
						$options['indexed_urls'][$url]['title'] = $options['urls'][$url]['title'];
						unset($options['urls'][$url]);
					} else {
						$options['urls'][$url]['status'] = $status;
						$options['urls'][$url]['lastchecked'] = current_time('timestamp');
					}// end if
				} else {
					if ( $options['debug'] ) $this->debug('not checking un-indexed urls yet');
				}// end if
			} else {
				if ( $options['debug'] ) $this->debug('no urls found in options');
			}// end if
			$options['lastcheck'] = current_time('timestamp');
			if ( $options['debug'] ) $this->debug('lastcheck updated to '.$options['lastcheck']);
			update_option('indexing_tool', $options);
		}// end if			
		// feed refresh
		if ( '' != $options['feedurl'] && ( current_time('timestamp') > (3600 + $options['lastrefresh']) ) ) {
			if ( $options['debug'] ) $this->debug('refreshing feed');
			$latest = array();
			$rss = fetch_feed($options['feedurl']);
			if ( !is_wp_error($rss) ) {
				if ( $rss->get_item_quantity() ) {		
					foreach ( $rss->get_items() as $item ) {
						$url = str_replace('&amp;', '&', $item->get_link());
						$title = str_replace('&amp;', '&', $item->get_title());
						$latest[$url]['title'] = $title;
						$latest[$url]['status'] = 'unchecked';
					}// end foreach
				}// end if
			}// end if
			unset($rss);
			if ( count($latest) ) {
				// we only want URLs not already in the indexed list..
				if ( is_array($options['indexed_urls']) && count($options['indexed_urls']) ) {
					$unindexed = array_diff_assoc($latest, $options['indexed_urls']);
				}
				// if we have anything, update the un-indexed list..
				if ( is_array($unindexed) && count($unindexed) ) {
					$options['urls'] = $unindexed;
				}
			}// end if
			$options['lastrefresh'] = current_time('timestamp');
			if ( $options['debug'] ) $this->debug('lastrefresh updated to '.$options['lastrefresh']);
			update_option('indexing_tool', $options);
		}// end if
	}// end function

	function get_status($url) {
		$result = 'unchecked';
		$query = 'http://www.google.com/search?q=inurl%3A'.urlencode($url).'&gl=US';
		$data = wp_remote_fopen($query);
		if ( stripos($data, 'did not match any documents') !== false )
			$result = 'unindexed';
		if ( stripos($data, 'resultStats') !== false )
			$result = 'indexed';
		if ( stripos($data, 'your computer or network may be sending automated queries') !== false )
			$result = 'banned';
		return $result;
	}// end func

	function debug($text) {
		if ( !is_feed() && !is_404() ) {
			$options = $this->get_options();
			if ( $options['debug'] )
				echo '<!-- '.current_time('mysql').' - '.$text." -->\n";
		}// end if
	}// end func
	
	function get_options() {
		$options = get_option('indexing_tool');
		if ( !is_array($options) )
			$options = $this->set_defaults();
		return $options;
	}// end function
	
	function set_defaults() {
		$options = array(
			'feedurl' => '',
			'title' => '<p>Other articles you might like;</p>',
			'max_links' => '5',
			'show_on_posts' => true,
			'linkspages' => array(),
			'new_window' => false,
			'urls' => array(),
			'indexed_urls' => array(),
			'lastcheck' => current_time('timestamp')-600,
			'lastrefresh' => current_time('timestamp'),
			'delay' => '600',
			'remove_settings' => false,
			'debug' => false
		);
		update_option('indexing_tool', $options);
		return $options;
	}// end function

}// end class
$indexing_tool = new indexing_tool;

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

class UnindexedLinks extends WP_Widget {

	function UnindexedLinks() {
		$widget_ops = array('description' => __('Displays unindexed links') );
		$this->WP_Widget('idxt', __('Indexing Tool'), $widget_ops);
	}

	function widget( $args, $instance ) {
		extract($args, EXTR_SKIP);
		$title = apply_filters('widget_title', $instance['title']);
		if ( !$maxlinks = intval($instance['maxlinks']) )
			$maxlinks = 5;

		global $indexing_tool;
		$options = $indexing_tool->get_options();

		if ( is_array($options['urls']) && count($options['urls']) ) {
			
			$links = array_slice($options['urls'], 0, $maxlinks, true);
			
			if ( count($links) ) {
				
				echo $before_widget;
				
				if ( !empty($title) )
					echo $before_title.$title.$after_title;

				echo '<ul>';
				foreach ( $links as $url => $info )
					echo '<li><a href="'.stripslashes($url).'" title="'.stripslashes($info['title']).'">'.stripslashes($info['title']).'</a></li>';
				echo '</ul>';
				
				echo $after_widget;

			}// end if

		}// end if
		
	}// end func

	function update($new_instance, $old_instance) {
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['maxlinks'] = intval($new_instance['maxlinks']);
		return $instance;
	}

	function form($instance) {
		$title = isset($instance['title']) ? esc_attr($instance['title']) : '';
		if ( !isset($instance['maxlinks']) || !$maxlinks = intval($instance['maxlinks']) )
			$maxlinks = 5;
	?>
	<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
	<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>
	
	<p><label for="<?php echo $this->get_field_id('maxlinks'); ?>"><?php _e('Number of links to show:'); ?></label>
	<input id="<?php echo $this->get_field_id('maxlinks'); ?>" name="<?php echo $this->get_field_name('maxlinks'); ?>" type="text" value="<?php echo $maxlinks; ?>" size="3" /></p>
	<?php
	}
}

add_action('widgets_init', create_function('', 'return register_widget("UnindexedLinks");'));
