<?php
/*
Plugin Name: Network Publisher
Plugin URI: http://www.linksalpha.com/
Description: Automatically posts your Articles to Social Networks - Facebook, Twitter, and LinkedIn
Version: 1.0.4
Author: Vivek Puri
Author URI: http://vivekpuri.com
*/

define('WIDGET_NAME', 'Network Publisher');
define('WIDGET_NAME_INTERNAL', 'networkpub');
define('WIDGET_PREFIX', 'networkpub');
define('NETWORKPUB', 'Automatically post your Articles to Social Networks - Facebook and Twitter');
define('ERROR_INTERNAL', 'internal error');
define('ERROR_INVALID_URL', 'invalid url');
define('ERROR_INVALID_KEY', 'invalid key');
if ( ! defined( 'WP_CONTENT_URL' ) )
      define( 'WP_CONTENT_URL', get_option( 'siteurl' ) . '/wp-content' );
if ( ! defined( 'WP_CONTENT_DIR' ) )
      define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' );
define('WP_PLUGIN_URL', WP_CONTENT_URL. '/plugins' );

$networkpub_settings['api_key'] = array('label'=>'API Key:', 'type'=>'text', 'default'=>'');
$networkpub_settings['id'] = array('label'=>'id', 'type'=>'text', 'default'=>'');
$options = get_option(WIDGET_NAME_INTERNAL);

function networkpub_init() {
	wp_enqueue_script('jquery');
	wp_register_script('networkpubjs', WP_PLUGIN_URL .'/network-publisher/networkpub.js');
	wp_enqueue_script('networkpubjs');
	wp_register_style('networkpubcss', WP_PLUGIN_URL . '/network-publisher/networkpub.css');
	wp_enqueue_style('networkpubcss');
	add_action('admin_menu', 'networkpub_pages');	
	add_action('{$new_status}_{$post->post_type}', 'networkping');
	add_action('publish_post', 'networkping');
}

add_action('init', 'networkpub_init');
add_action('init', 'networkpub_remove');

function networkping($id) {
	if(!$id) {
		return FALSE;
	}
	$options = get_option(WIDGET_NAME_INTERNAL);
	$link = 'http://www.linksalpha.com/a/ping?id='.$options['id'];
	require_once(ABSPATH.WPINC.'/class-snoopy.php');
	$snoop = new Snoopy;
	$snoop->agent = WIDGET_NAME.' - '.get_option('siteurl');
	$response = '';
	if($snoop->fetchtext($link)){
		if (strpos($snoop->response_code, '200')) {
			return TRUE;
		} 
	}
	return FALSE;
}

function networkpub_pages() {
	if ( function_exists('add_submenu_page') ) {
		$page = add_submenu_page('plugins.php', WIDGET_NAME, WIDGET_NAME, 'manage_options', 'networkpub', 'networkpub_conf');
	}
}

function networkpub_conf() {
	global $networkpub_settings;
	
	if ( isset($_POST['submit']) ) {
		if ( function_exists('current_user_can') && !current_user_can('manage_options') ) {
			die(__('Cheatin&#8217; uh?'));
		}
		$field_name = sprintf('%s_%s', WIDGET_PREFIX, 'api_key');
		$value = strip_tags(stripslashes($_POST[$field_name]));
		if($value) {
			$networkadd = networkpub_add($value);	
		}
	}
	$options = get_option(WIDGET_NAME_INTERNAL);
	$html  = '<div class="rts_header"><big><strong>'.WIDGET_NAME.'</strong></big></div>';
	$html .= '<table style="width:800px;"><tr><td style="padding-bottom:40px;">';
	$html .= '<div style="padding:0px 0px 10px 0px;">Network Publisher makes it easy and painless to Publish your Blog Posts to Social Networks. All you need to do is connect to your Social Networks at <a target="_blank" href="http://www.linksalpha.com/user/networks">LinksAlpha.com</a>, grab API Key for each enabled Network and enter it below. Once setup, your Blog posts content appears on the social networks as soon as you hit the Publish button.</div>';
	$html .= '<div style="padding:0px 0px 20px 0px;"><a href="http://www.linksalpha.com/user/networks" style="font-weight:bold;" target="_blank">Click Here</a> to get API Keys for your Social Networks. You can <a href="http://help.linksalpha.com/wordpress-plugin-network-publisher" target="_blank">read more about this process at LinksAlpha.com.</a></div>';
	$html .= '<div class="rts_header2"><big><strong>Setup</strong></big></div><div style="padding-left:10px;">';
	$html .= '<div style="text-align:left;">';
	$html .= '<form action="" method="post" id="networkpubadd" name="networkpubadd" style="width:90%;">';
	$html .= '<fieldset class="rts_fieldset">';
	$html .= '<legend>Additional API Key</legend>';
	
	$curr_field = 'api_key';
	$field_name = sprintf('%s_%s', WIDGET_PREFIX, $curr_field);
	$html .= '<div><label for="'.$field_name.'">'.$networkpub_settings[$curr_field]['label'].'&nbsp;</label></div>';
	$html .= '<div style="padding-bottom:10px"><input style="width:400px;" class="widefat" id="'.$field_name.'" name="'.$field_name.'" type="text" /></div>';
	
	$html .= '</fieldset>';
	$html .= '<div style="padding-top:20px;"><input type="submit" name="submit" value="Add API Key" /></div>';
	$html .= '<input type="hidden" value="'.WP_PLUGIN_URL.'" id="networkpub_plugin_url" /></form></div></td></tr><tr><td style="padding:0px 0px 0px 0px;vertical-align:top;">';
	$html .= '<div class="rts_header2"><big><strong>Currently Publishing</strong></big></div>';
	$html .= '<div style="padding-left:10px;">'.networkpub_load().'</div>';
	$html .= '</div></td></tr></table>';
	echo $html;
}

function networkpub_add($api_key) {
	if (!$api_key) {
		return FALSE;
	}
	$url = get_option('siteurl');
	$desc = get_bloginfo('description');
	if (!$url) {
		return FALSE;
	}
	$link = 'http://www.linksalpha.com/a/networkpubadd?url='.urlencode($url).'&key='.$api_key.'&desc='.urlencode($desc);
	require_once(ABSPATH.WPINC.'/class-snoopy.php');
	$snoop = new Snoopy;
	$snoop->agent = WIDGET_NAME.' - '.get_option('siteurl');
	$response = '';
	if($snoop->fetchtext($link)){
		if (strpos($snoop->response_code, '200')) {
			$response_json = $snoop->results;
			$response = networkpub_json_decode($response_json);
		}
	}
	if (!$response) {
		return FALSE;
	}
	if ($response->errorCode > 0) {
		return FALSE;
	}
	$options = get_option(WIDGET_NAME_INTERNAL);
	if(empty($options['api_key'])) {
		$options['api_key'] = $api_key;	
	} else {
		$options_array = explode(',', $options['api_key']);
		if(!in_array($api_key, $options_array)) {
			$options['api_key'] = $options['api_key'].','.$api_key;	
		}
	}
	$options['id'] = $response->results->id; 
	update_option(WIDGET_NAME_INTERNAL, $options);
	return TRUE;	
}

function networkpub_load() {
	$options = get_option(WIDGET_NAME_INTERNAL);
	if (empty($options['api_key'])) {
		$html = '<div>You have not added any API Key</div>';
		return $html;
	}
	$link = 'http://www.linksalpha.com/a/networkpubget?key='.$options['api_key'];
	require_once(ABSPATH.WPINC.'/class-snoopy.php');
	$snoop = new Snoopy;
	$snoop->agent = WIDGET_NAME.' - '.get_option('siteurl');
	$response = '';
	if($snoop->fetchtext($link)){
		if (strpos($snoop->response_code, '200')) {
			$response_json = $snoop->results;
			$response = networkpub_json_decode($response_json);
		}
	}
	if (!$response) {
		$html = '<div>Error occured while trying to load the API Keys. Please try again later.</div>';
		return $html;
	}
	if($response->errorCode > 0) {
		$html = '<div>Error occured while trying to load the API Keys. Please try again later.</div>';
		return $html;
	}
	$html = '<div style="padding-bottom:10px;">You are currently Publishing your Blog to '.count($response->results).' Social Networks</div>';
	$html .= '<table class="networkpub_added"><tr><th>API Key</th><th>Network</th><th>Option</th></tr>';
	foreach($response->results as $row) {
		$html .= '<tr id="r_key_'.$row->api_key.'">';
		switch($row->type) {
			case 'twitter':
				$html  .= '<td>'.$row->api_key.'</td><td>Twitter Account - <a target="_blank" href="http://twitter.com/'.$row->short_name.'">'.$row->name.'</a></td>';
				break;
			case 'fb_page':
				$html  .= '<td>'.$row->api_key.'</td><td>Facebook Page - <a target="_blank" href="'.$row->page_url.'">'.$row->name.'</a></td>';
				break;
			case 'fb_wall':
				$html  .= '<td>'.$row->api_key.'</td><td><a target="_blank" href="http://www.facebook.com/profile.php?id='.$row->id.'">'.$row->name.'</a></td>';
				break;	
			case 'myspace':
				$html  .= '<td>'.$row->api_key.'</td><td>MySpace Account - <a target="_blank" href="'.$row->page_url.'">'.$row->name.'</a></td>';
				break;	
			case 'linkedin':
				$html  .= '<td>'.$row->api_key.'</td><td>LinkedIn Account - <a target="_blank" href="'.$row->page_url.'">'.$row->name.'</a></td>';
				break;
			case 'yammer':
				$html  .= '<td>'.$row->api_key.'</td><td>Yammer Account - <a target="_blank" href="'.$row->page_url.'">'.$row->name.'</a></td>';
				break;	
		}
		$html .= '<td><a href="#" id="key_'.$row->api_key.'" class="networkpubre">Remove</a></td></tr>';
	}
	$html .= '</table>';
	return $html;
}

function networkpub_remove() {
	$options = get_option(WIDGET_NAME_INTERNAL);
	if (!empty($_POST['key'])) {
		$key_full = $_POST['key'];
		$key_only = substr($key_full, 4);
		$api_key = $options['api_key'];
		$api_key_array = explode(',', $api_key);
		$loc = array_search($key_only, $api_key_array);
		if($loc !== FALSE) {
			unset($api_key_array[$loc]);
		}
		$api_key = implode(",", $api_key_array);
		$options['api_key'] = $api_key;
		update_option(WIDGET_NAME_INTERNAL, $options);
		$link = 'http://www.linksalpha.com/a/networkpubremove?id='.$options['id'].'&key='.$key_only;
		require_once(ABSPATH.WPINC.'/class-snoopy.php');
		$snoop = new Snoopy;
		$snoop->agent = WIDGET_NAME.' - '.get_option('siteurl');
		$response = '';
		$snoop->fetchtext($link);	
		echo $key_full;
		return;
	}
}

function networkpub_json_decode($str) {
	if (function_exists("json_decode")) {
	    return json_decode($str);
	} else {
		if (!class_exists('Services_JSON')) {
			require_once("JSON.php");
		}
	    $json = new Services_JSON();
	    return $json->decode($str);
	}
}

?>