<?php
require '../../../wp-blog-header.php';
require_once 'TwitterAPIExchange.php';

ini_set('display_errors', 1);

set_time_limit(200);
function return_300($seconds) {
	// change the default feed cache recreation period to 2 hours
	return 300;
}

add_filter('wp_feed_cache_transient_lifetime', 'return_300');

$campaign = smSelectCampaign();
if (empty($campaign)) {
	echo "no campaign selected <br/>\n";
	exit;
}

switch (rand(1, 100) % 2) {
case 0:
	$post = smChooseWPPost($campaign);
	if (empty($post)) {
		echo "nothing to post <br/>\n";
		exit;
	}
	$res = doPostToTwitter($campaign, $post);
	echo "Cron Finished <br/>\n";
	break;
case 1:
	doCustomToTwitter($campaign);
	echo "Custom To Twitter <br/>\n";
	break;
}

function doPostToTwitter($campaignId, $wpPostId) {
	$permalink = get_permalink(intval($wpPostId));
	$post = get_post(intval($wpPostId));

	if (empty($post)) {
		echo "No Post found with given ID<br/>\n";
		return;
	}

	if (sm_check_in_master_log('WP Post to Twitter', $campaignId, $wpPostId) == 0) {
		$imgURL = get_the_post_thumbnail_url($post->ID, 'full');
		$b64image = base64_encode(file_get_contents($imgURL));
		$mediaID = smUploadTwitterImage($b64image, $campaignId);
		smPostToTwitter($permalink, $post->post_title, $mediaID, $campaignId, $wpPostId);

		return true;
	} else {
		echo "Post already posted to twitter<br/>\n";
		return false;
	}
}

function doCustomToTwitter($campaignId) {
	$custom = smGetCustom($campaignId);

	if (empty($custom)) {
		echo "No custom Post found<br/>\n";
		return;
	}

	if (sm_check_in_master_log('Custom to Twitter', $campaignId, $custom->id) == 0) {
		$imgURL = get_the_post_thumbnail_url($custom->id, 'full');
		$b64image = base64_encode(file_get_contents($custom->image));
		$mediaID = smUploadTwitterImage($b64image, $campaignId);
		smPostToTwitter($custom->url, $custom->headline, $mediaID, $campaignId, $custom->id, $custom->message, 'Custom to Twitter');

		return true;
	} else {
		echo "Custom {$custom->id} already posted to twitter<br/>\n";
		return false;
	}
}

function smUploadTwitterImage($b64image, $campaignId) {
	$token = get_post_meta(111111113, $campaignId . 'smTwAccessToken', TRUE);
	$tokensecret = get_post_meta(111111113, $campaignId . 'smTwTokenSecret', TRUE);
	$key = get_post_meta(111111113, $campaignId . 'smTwConsumerKey', TRUE);
	$secret = get_post_meta(111111113, $campaignId . 'smTwConsumerSecret', TRUE);
	$userid = get_post_meta(111111113, $campaignId . 'smTwOwnerId', TRUE);

	$settings = array(
		'oauth_access_token' => $token,
		'oauth_access_token_secret' => $tokensecret,
		'consumer_key' => $key,
		'consumer_secret' => $secret,
	);

	$url = 'https://upload.twitter.com/1.1/media/upload.json';
	$requestMethod = 'POST';

	$postfields = array(
		'media_data' => $b64image
	);

	$twitter = new TwitterAPIExchange($settings);
	$response = $twitter->buildOauth($url, $requestMethod)
		->setPostfields($postfields)
		->performRequest();

	$response = json_decode($response);

	$id = $response->media_id;
	return $id;
}

function smPostToTwitter($link, $title, $mediaID, $campaign, $wpPostId, $message = '', $logAction = 'WP Post to Twitter') {
	$title = html_entity_decode($title);

	if (empty($message)) {
		$tweet = html_entity_decode($title);
	} else {
		$tweet = html_entity_decode($message);
	}

	$token = get_post_meta(111111113, $campaign . 'smTwAccessToken', TRUE);
	$tokensecret = get_post_meta(111111113, $campaign . 'smTwTokenSecret', TRUE);
	$key = get_post_meta(111111113, $campaign . 'smTwConsumerKey', TRUE);
	$secret = get_post_meta(111111113, $campaign . 'smTwConsumerSecret', TRUE);

	$settings = array(
		'oauth_access_token' => $token,
		'oauth_access_token_secret' => $tokensecret,
		'consumer_key' => $key,
		'consumer_secret' => $secret,
	);

	$url = 'https://api.twitter.com/1.1/statuses/update.json';
	$requestMethod = 'POST';

	if (strlen($tweet) > 113) {
		$tweet = substr($tweet, 0, 113);
		$tweet = $tweet . "...";
	}

	$postfields = array(
		'status' => $tweet . " " . $link,
		'media_ids' => $mediaID,
	);

	$twitter = new TwitterAPIExchange($settings);
	$tweets = $twitter->buildOauth($url, $requestMethod)
		->setPostfields($postfields)
		->performRequest();

	$tweets = json_decode($tweets);

	if (isset($tweets->id)) {
		echo "Successfully Posted to Twitter<br/>";

		sm_add_to_master_log($logAction, $campaign, $wpPostId, "https://twitter.com/statuses/{$tweets->id}");

		return true;
	} else {
		echo "Error while trying to post to twitter <br/>\n";

		var_dump($tweets);
		echo $tweets->error->message;

		echo "<br/>\n";
		return false;
	}
}
