<?php
/*
 * Plugin Name: Web Traffic Genius
 */
/*
 * Plugin URI: http://www.webtrafficgenius.com
 * Description: This plugin will when a new post is published, create and submit a new rss feed to the pre-configured RSS Aggregator websites, and where applicable will also include the tags used in the post.
 * Version: 3.5.4
 */
/*
 * Author: The Marketing Assassins
 */
/*
 * Author URI: http://www.webtrafficgenius.com
 */

/*
* Web Traffic Genius Pro v3.5.4
* Copyright (c) 2008-2010
* Success on the Internet Pty Ltd
* PO Box 25
* Salisbury SA 5108
* Australia
* Phone: +61 422 512 549
* Fax: +61 8 8425 9657
* Web: http://www.webtrafficgenius.com
* Support: http://www.marketing-assassins.com
*
*/
require_once(dirname(__FILE__). '/config.php');
require_once(dirname(__FILE__). '/rss_log.php');
require_once(dirname(__FILE__). '/export_aggregators.php');
require_once(dirname(__FILE__). '/process_submit.php');
require_once(dirname(__FILE__). '/rss_database.php');
require_once(dirname(__FILE__). '/rss_cron_job.php');
require_once(dirname(__FILE__). '/feed_generator.php');
require_once(dirname(__FILE__). '/extrafeed_model.php');

//add_action('rss_power_plus/rss_submitter.php', 'wtg_activation');
register_activation_hook(__FILE__, 'wtg_activation');
//add_action('deactivate_rss_power_plus/rss_submitter.php', 'wtg_deactivation');
register_deactivation_hook(__FILE__, 'wtg_deactivation');

add_action('wp_print_scripts', 'wtg_my_init_method');

add_action('admin_menu', 'wtg_add_menu_page');
add_action('template_redirect', 'wtg_custom_feed');
add_action('plugins_loaded', 'wtg_export_xml');
add_action('draft_to_publish', 'wtg_publish_post');
add_action('future_to_publish', 'wtg_publish_post');
add_action('pending_to_publish', 'wtg_publish_post');
add_action('xmlrpc_publish_post','wtg_publish_post_xmlrpc');
//add_action('save_post', 'wtg_publish_post');
add_action('wtg_cron_post_feed_event', 'wtg_cron_post_feed');
add_action('new_to_publish', 'wtg_publish_post');
add_action('private_to_publish', 'wtg_publish_post');

function wtg_add_menu_page() {
	if (function_exists('add_menu_page') && function_exists('add_submenu_page')) {
		add_menu_page('Web Traffic Genius Pro', 'Web Traffic Genius Pro', USER_LEVEL, __FILE__, 'wtg_load_menu');
		add_submenu_page(__FILE__, 'Web Traffic Genius Pro Options', 'Options', USER_LEVEL, __FILE__, 'wtg_load_menu');
		add_submenu_page(__FILE__, 'Manage Aggregators', 'Manage Aggregators', USER_LEVEL, 'manage_aggregators', 'wtg_load_menu');
		add_submenu_page(__FILE__, 'Manage Extrafeeds', 'Manage Extrafeeds', USER_LEVEL, 'manage_extrafeeds', 'wtg_load_menu');
		add_submenu_page(__FILE__, 'Captcha Services', 'Captcha Services', USER_LEVEL, 'manage_captcha', 'wtg_load_menu');
		add_submenu_page(__FILE__, 'RSS Feed List', 'RSS Feed', USER_LEVEL, 'rss_feed_list', 'wtg_load_menu');
		add_submenu_page(__FILE__, 'Import Configuration', 'Import', USER_LEVEL, 'import_aggregators', 'wtg_load_menu');
		add_submenu_page(__FILE__, 'Export Configuration', 'Export', USER_LEVEL, 'export_aggregators', 'wtg_load_menu');
		add_submenu_page(__FILE__, 'Web Traffic Genius Log', 'Log', USER_LEVEL, 'aggregator_log', 'wtg_load_menu');
		add_submenu_page(__FILE__, 'Web Traffic Genius Schedule Job List', 'Schedule Job', USER_LEVEL, 'schedule_job', 'wtg_load_menu');
		add_submenu_page(__FILE__, 'Register Web Traffic Genius Plugin', 'Register', USER_LEVEL, 'register', 'wtg_load_menu');
		add_submenu_page(__FILE__, 'Auto Upgrade', 'Auto Upgrade', USER_LEVEL, 'autoupgrade', 'wtg_load_menu');
		add_submenu_page(__FILE__, 'About', 'About', USER_LEVEL, 'rss_about', 'wtg_load_menu');
	}
	
	
	// Check for capability
	checkDomainRegistered();
}

function wtg_load_menu() {
	switch ($_GET["page"]) {
		case 'manage_aggregators' :
			include_once (dirname(__FILE__). '/manage_aggregators.php');
			wtg_manage_aggregators();
			break;
		case 'add_aggregator' :
			include_once (dirname(__FILE__). '/add_aggregator.php'); //add aggregator functions
			wtg_add_aggregator();
			break;
		case 'export_aggregators' :
			include_once (dirname(__FILE__). '/export_aggregators.php'); //export aggregator functions
			wtg_export_aggregators();
			break;
		case 'import_aggregators' :
			include_once (dirname(__FILE__). '/import_aggregators.php'); //import aggregator functions
			wtg_import_aggregators();
			break;
		case 'aggregator_log' :
			include_once (dirname(__FILE__). '/aggregator_log.php'); //
			wtg_log();
			break;
		case 'schedule_job' :
			include_once (dirname(__FILE__). '/schedule_job.php'); // tgb
			wtg_schedule_job_list();
			break;
		case plugin_basename(__FILE__) :
			include_once (dirname(__FILE__). '/rss_submitter_options.php');
			wtg_options();
			break;
		case 'rss_about' :
			include_once (dirname(__FILE__). '/rss_about.php');
			wtg_about();
			break;
		case 'manage_extrafeeds':
			include_once (dirname(__FILE__). '/manage_extrafeeds.php');
			wtg_manage_extrafeeds();
			break;
		case 'rss_feed_list':
			include_once (dirname(__FILE__). '/rss_feed_list.php');
			wtg_display_rss_feed_list();
			break;
		case 'manage_captcha':
			include_once (dirname(__FILE__). '/manage_captcha.php');
			wtg_manage_captchas();
			break;
		case 'autoupgrade':
			include_once (dirname(__FILE__). '/auto_upgrade.php');
			wtg_auto_upgrade();
			break;
		case 'register':
			include_once (dirname(__FILE__). '/register.php');
			wtg_register_plugin();
			break;
		}
}

function wtg_publish_post_async($post) {
	$postID = $post->ID;

	global $logger, $indent;
	$GLOBALS['wtg']['postID'] = $postID;
	
	// works for published post only 
	if($post->post_status == 'publish') {
		$wtg_option = get_option('wtg_option');
		
		if ($wtg_option['pause_posting'] == 0)
		{
			//if(!empty($wtg_option['processing']) && $wtg_option['registration']) {
			if($wtg_option['registration']) {
				$logger = new WTG_Rss_Log();
				$logger->openlog();
				$logger->info("A post was just published(postId=$postID). About to Trigger feed submission session.");
			
				$GLOBALS['wtg']['feedName'] = wtg_dump_feed($postID);
				if (empty($GLOBALS['wtg']['feedName'])) {
					$logger->error("Dump feed FAIL exit");
					return;
				}
				$logger->info("Feed url will be " . wtg_callback_rss_feed_url(array('feed_name' => $GLOBALS['wtg']['feedName'])));
				//wtg_submit_rss();
				$file = 'async.php?id='.$postID.'&abspath='.ABSPATH;
				//$logger->info("File is:". $file);
				//proc_close(proc_open ($file." &", array(), $foo));
				//exec ("/usr/bin/php async.php?id=".$postID."&abspath=".ABSPATH." &");	
				$page_to_execute = $file ;
				$command = $page_to_execute;
				exec('/usr/local/bin/php async.php?id='.$postID.'&abspath='.ABSPATH.' -q');
				//$logger->info("output is: ". $out);
			}
		}
	}
}

function wtg_publish_post($post) {
	$postID = $post->ID;

	global $logger, $indent;
	$GLOBALS['wtg']['postID'] = $postID;
	
	// works for published post only 
	if($post->post_status == 'publish') {
		$wtg_option = get_option('wtg_option');
		
		if ($wtg_option['pause_posting'] == 0)
		{
			//if(!empty($wtg_option['processing']) && $wtg_option['registration']) {
			if($wtg_option['registration']) {
				$logger = new WTG_Rss_Log();
				$logger->openlog();
				$logger->info("A post was just published(postId=$postID). About to Trigger feed submission session.");
			
				$GLOBALS['wtg']['feedName'] = wtg_dump_feed($postID);
				if (empty($GLOBALS['wtg']['feedName'])) {
					$logger->error("Dump feed FAIL exit");
					return;
				}
				$logger->info("Feed url will be " . wtg_callback_rss_feed_url(array('feed_name' => $GLOBALS['wtg']['feedName'])));
				
				wtg_submit_rss();
			
				$logger->closelog();
				$result=wtg_get_version(WTG_UPGRADE_VERSION_URL);
				$version_message='';
				if(version_compare($result, WTG_CURRENT_VERSION, '>')) {
					$version_message="###################################\nA new version of Web Traffic Genius is available.\n###################################\n\n";
				}
				
				// send the log
				if (!empty($wtg_option['email']) && !empty($wtg_option['latest'])) {
						wp_mail($wtg_option['email'], 'Latest RSS feed submission log', $version_message.$logger->get_latest_log_text());
				} 
				if (!empty($wtg_option['email']) && !empty($wtg_option['complete'])) {
					   wp_mail($wtg_option['email'], 'Complete RSS feed submission log', $version_message.$logger->get_complete_log_text());
				}
			}
		}
	}
}


/*******************************************************/
/* If this comment is removed the program will blow up */
/*******************************************************/

function wtg_cron_publish_post($post) {
	$postID = $post->ID;

	global $logger, $indent;
	$GLOBALS['wtg']['postID'] = $postID;
	
	// works for published post only 
	if($post->post_status == 'publish') {
		$wtg_option = get_option('wtg_option');
		
		if ($wtg_option['pause_posting'] == 0)
		{
			//if(!empty($wtg_option['processing']) && $wtg_option['registration']) {
			if($wtg_option['registration']) {
				$logger = new WTG_Rss_Log();
				$logger->openlog();
				$logger->info("A post was just published(postId=$postID). About to Trigger feed submission session.");
			
				$GLOBALS['wtg']['feedName'] = wtg_dump_feed($postID);
				if (empty($GLOBALS['wtg']['feedName'])) {
					$logger->error("Dump feed FAIL exit");
					return;
				}
				$logger->info("Feed url will be " . wtg_callback_rss_feed_url(array('feed_name' => $GLOBALS['wtg']['feedName'])));
				wtg_submit_rss();
				$logger->closelog();
			}
		}
	}
}
	
function wtg_cron_submit_existing() {
    $db = new WTG_DB();
    $scheduled_list = array();
    $scheduled_posts = $db->get_scheduled_posts();
    foreach ($scheduled_posts as $scheduled_post) {
        array_push($scheduled_list, $scheduled_post->post_id);
    }
    //$scheduled_posts = array($db->get_scheduled_posts());
	
	$wtg_option = get_option('wtg_option');
	if (isset($wtg_option['posts_per_cron_job']))
		$posts_per_cron_job = $wtg_option['posts_per_cron_job'];
	else $posts_per_cron_job = POSTS_PER_CRON_JOB_DEFAULT;
	
    $args = array(
        'post_status'   => 'publish',
        'post__not_in'  => $scheduled_list,
        'numberposts'   => $posts_per_cron_job,
        'orderby'       => 'post_date',
		'order'         => 'DESC');
    $posts = get_posts($args);
    foreach ($posts as $post) {
        wtg_cron_publish_post($post);
    }
}

function wtg_publish_post_xmlrpc($post) {
	$postID = $post;

	global $logger, $indent;
	$GLOBALS['wtg']['postID'] = $postID;
	
	// works for published post only 
	if($post->post_status == 'publish') {
		$wtg_option = get_option('wtg_option');
		
		if ($wtg_option['pause_posting'] == 0)
		{
			if(!empty($wtg_option['processing']) && $wtg_option['registration']) {
				$logger = new WTG_Rss_Log();
				$logger->openlog();
				$logger->info("A post was just published(postId=$postID). About to Trigger feed submission session.");
			
				$GLOBALS['wtg']['feedName'] = wtg_dump_feed($postID);
				if (empty($GLOBALS['wtg']['feedName'])) {
					$logger->error("Dump feed FAIL exit");
					return;
				}
				$logger->info("Feed url will be " . wtg_callback_rss_feed_url(array('feed_name' => $GLOBALS['wtg']['feedName'])));
			
				wtg_submit_rss();
			
				$logger->closelog();
				$version_message='';
				if(version_compare($result, WTG_CURRENT_VERSION, '>')) {
					$version_message="###################################\nA Web Traffic Genius version of WTG is available.\n###################################\n\n";
				}
				
				// send the log
				if (!empty($wtg_option['email']) && !empty($wtg_option['latest'])) {
						wp_mail($wtg_option['email'], 'Latest RSS feed submission log', $version_message.$logger->get_latest_log_text());
				} 
				if (!empty($wtg_option['email']) && !empty($wtg_option['complete'])) {
					  wp_mail($wtg_option['email'], 'Complete RSS feed submission log', $version_message.$logger->get_complete_log_text());
				}
			}
		}
	}
}

function wtg_activation() {
	
	//if (!current_user_can('activate_plugins')) return;
    	wtg_check_activation();
    	
    	// Check domain registered
	$db = new WTG_DB();
	$db->activate();
	
	
}

function wtg_check_activation() {
	require_once(ABSPATH . 'wp-admin/includes/plugin.php');
	if (is_plugin_active("rss-power-plus-pro/rss_submitter.php")) {
		//delete_option("rs_option");
		//delete_option('rs_db_version');
		//deactivate_plugins("rss-power-plus-pro/rss_submitter.php");
		//update_option('active_plugins');
		deactivate_plugins(__FILE__); // Deactivate ourself
		wp_die("<p>Sorry, but you need to go back and deactivate the <b>RSS Power Plus Pro</b> before trying to activate <b>Web Traffic Genius Pro</b>.</p>");
	}
}

function wtg_deactivation() {
	// To keep the setting when deactivate the plugin, commented the following code 
	
	//delete_option('wtg_aggregators_xml');
	//delete_option('wtg_option');
	//delete_option('wtg_db_version');
	//$db = new WTG_DB();
	//$db->drop_tables();
}

function wtg_custom_feed() {
	if (empty($_GET['custom_feed'])) return; // not request feed of a post

	// Get feed type
	$feedType = trim($_GET['custom_feed']);

	// Dispatch the request
	if ($feedType == 'rss2') {
		include_once (dirname(__FILE__). '/custom_feed_rss2.php');
		wtg_custom_feed_rss2();
	} elseif ($feedType == 'atom') {
		include_once (dirname(__FILE__). '/custom_feed_atom.php');
		wtg_custom_feed_atom();
	} else {
		include_once (dirname(__FILE__). '/custom_feed_rss.php');
		wtg_custom_feed_rss(); // gambier
	}
}

function wtg_my_init_method($post) {
	if(isset($_GET['post']))
	{
		$postID = $_GET['post'];
		$post = get_post($postID);
		wp_enqueue_script('jquery');   
		wp_enqueue_script('submit_result', WP_PLUGIN_URL . '/'.plugin_basename(str_replace('//','/',dirname(__FILE__).'/')).'/js/submit_result.js', array('jquery'), '1.0' );	
		wp_localize_script('submit_result', 'PostInfo', array('pid' => $postID, 'status' => $post->post_status, 'path' => site_url(), 'plugin_dir' => plugin_basename(str_replace('//','/',dirname(__FILE__).'/'))));
	}
} 


function checkDomainRegistered() {
	$wtg_option = get_option('wtg_option');
	$wtg_option['domain']=convert_uudecode($wtg_option['domain']);
	if($wtg_option['domain'] != $_SERVER['SERVER_NAME']) {
		checkDomainDeactive($wtg_option['receipt_number']);
		$wtg_option['registration']=0;
		$wtg_option['receipt_number']='';
		$wtg_option['domain']='';
		$wtg_option['registration_date']=convert_uuencode(date("Y-m-d h:i:s"));
		$random_number=rand(3,7);
		$wtg_option['time_interval']=$random_number;
		update_option('wtg_option', $wtg_option);
	} else {
		if($wtg_option['registration'] && $wtg_option['receipt_number']) {
			// get number of days
			//$current_date=strtotime(date("Y-m-d h:i:s"));
			
			$current_date=date("Y-m-d h:i:s");
			$registration_date=convert_uudecode($wtg_option['registration_date']);
			$time_interval=$wtg_option['time_interval'];
			
			$time="10:34:05";
			$days='+'.$time_interval.' days';
			$execute_date=date('Y-m-d', strtotime($days)).' '.$time;
			
			//$no_of_days=count_days($registration_date,$current_date);
			if($execute_date==$current_date)
			{
				// decode the encoded receipt number
				$receipt_number=convert_uudecode($wtg_option['receipt_number']);
				$url='http://webtrafficgenius.com/upgrade/wtg-activations-stats.php';
				
				$message=wtg_post_data($url, array("action" => 'checkstatus', "receipt_num" => $receipt_number, "domain" => $_SERVER['SERVER_NAME'], "type" => 'wtg'));
				if($message == 'fail') {
					checkDomainDeactive($wtg_option['receipt_number']);
					$wtg_option['registration']=0;
					$wtg_option['receipt_number']='';
					$wtg_option['domain']='';
					$wtg_option['registration_date']=convert_uuencode(date("Y-m-d h:i:s"));
					$random_number=rand(3,7);
					$wtg_option['time_interval']=$random_number;
				} else {
					$random_number=rand(3,7);
					$wtg_option['time_interval']=$random_number;
					$wtg_option['registration_date']=convert_uuencode(date("Y-m-d h:i:s"));
				}
				update_option('wtg_option', $wtg_option);
			}
		}
	}
}

function checkDomainDeactive($receipt_number){
		// decode the encoded receipt number
		$receipt_number=convert_uudecode($receipt_number);
		$url='http://webtrafficgenius.com/upgrade/wtg-activations-stats.php';
		$message=wtg_post_data($url, array("action" => 'deactivate', "receipt_num" => $receipt_number, "type" => 'wtg'));
}
function count_days( $a, $b )
{
$gd_a = getdate( $a );
$gd_b = getdate( $b );

// Now recreate these timestamps, based upon noon on each day
// The specific time doesn't matter but it must be the same each day
$a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
$b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );

// Subtract these two numbers and divide by the number of seconds in a
// day. Round the result since crossing over a daylight savings time
// barrier will cause this time to be off by an hour or two.
return round( abs( $a_new - $b_new ) / 86400 );
}