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

set_time_limit(200);
function return_300($seconds) {
	return 300;
}

add_filter('wp_feed_cache_transient_lifetime', 'return_300');

$campaign = smSelectCampaign();

if (empty($campaign)) {
	echo "no campaign found";
	exit;
}

smDoStart($campaign);
echo "completed";
exit;

function smSelectSource($campaignId) {
	global $wpdb;
	$wpdb->show_errors();

	$table_name = $wpdb->prefix . "smfeeds";

	$query = "SELECT * FROM $table_name WHERE campaign = $campaignId ORDER BY RAND() LIMIT 1";
	$querydata = $wpdb->get_results($query);

	if (count($querydata) > 0) {
		return $querydata[0];
	}

	return false;
}

function smDoStart($campaign) {
	$smFirstAsFeatured = get_post_meta(111111113, $campaign . 'sm-first-as-featured', true);
	$smStripFirstImage = get_post_meta(111111113, $campaign . 'sm-strip-first-image', true);
	$smStripLinks = get_post_meta(111111113, $campaign . 'sm-strip-links', true);

	global $wpdb;
	$wpdb->show_errors();

	for ($i = 0; $i < 5; $i++) {
		$source = smSelectSource($campaign);

		if (!$source) {
			echo "no source found. skipping... <br/>\n";
			continue;
		}

		if ($source->contentType === 'rss-feed') {
			if (smPostFeed($campaign, $source)) {
				echo "posted. exiting... <br/>\n";
				break;
			} else {
				echo "post failed. exiting... <br/>\n";
				continue;
			}
		} else if ($source->contentType === 'youtube-channel') {
			if (smPostYoutubeChannel($campaign, $source)) {
				echo "youtube channel video posted. exiting... <br/>\n";
				break;
			} else {
				echo "youtube channel video post failed. exiting... <br/>\n";
				continue;
			}
		} else if ($source->contentType === 'youtube-playlist') {
			if (smPostYoutubePlaylist($campaign, $source)) {
				echo "youtube playlist video posted. exiting... <br/>\n";
				break;
			} else {
				echo "youtube playlist video post failed. exiting... <br/>\n";
				continue;
			}
		/* } else if ($source->contentType === 'facebook-fan-page') {
			if (smPostFacebookFanPage($campaign, $source)) {
				echo "post from facebook fanpage posted. exiting... <br/>\n";
				break;
			} else {
				echo "post from facebook fanpage failed. exiting... <br/>\n";
				continue;
			} */
		} else if ($source->contentType === 'twitter-account') {
			if (smPostTwitter($campaign, $source)) {
				echo "post from twitter posted. exiting... <br/>\n";
				break;
			} else {
				echo "post from twitter failed. exiting... <br/>\n";
				continue;
			}
		} else if ($source->contentType === 'instagram-account') {
			if (smPostInstagram($campaign, $source)) {
				echo "post from instagram posted. exiting... <br/>\n";
				break;
			} else {
				echo "post from instagram failed. exiting... <br/>\n";
				continue;
			}
		} else if ($source->contentType === 'pinterest-board') {
			if (smPostPinterest($campaign, $source)) {
				echo "post from pinterest posted. exiting... <br/>\n";
				break;
			} else {
				echo "post from pinterest failed. exiting... <br/>\n";
				continue;
			}
		} else if ($source->contentType === 'reddit-subreddit') {
			if (smPostReddit($campaign, $source)) {
				echo "post from reddit posted. exiting... <br/>\n";
				break;
			} else {
				echo "post from reddit failed. exiting... <br/>\n";
				continue;
			}
		}
	}
}

function sm_getTitlesArray($id) {
	global $wpdb;
	$wpdb->show_errors();
	$table_name = $wpdb->prefix . "smtitlesets";

	$query = "SELECT * FROM $table_name where id={$id} ORDER BY setname ASC";
	$result = $wpdb->get_row($query);

	if (empty($result)) {
		return false;
	}

	return explode('|:|', $result->title);
}

function smPostFeed($campaign, $source) {
	$url = $source->url;

	if (empty($url)) {
		return false;
	}

	if ($source->titlesetId != '0') {
		$titles = sm_getTitlesArray($source->titlesetId);
	}

	$rss = fetch_feed($url);

	if (!is_wp_error($rss)) {
		$maxitems = $rss->get_item_quantity(0);
		$rss_items = $rss->get_items(0, $maxitems);

		foreach ($rss_items as $item) {
			$link = $item->get_permalink();
			$content = $item->get_content();
			$titleFromFeed = $item->get_title();

			if ($source->titlesetId === '0' || $titles === false) {
				$title = $titleFromFeed;
			} else {
				$title = $titles[array_rand($titles, 1)];

				if (empty($title)) {
					$title = $titleFromFeed;
				}

				$spintax = new smSpintax();
				$title = $spintax->process($title);
			}

			$imgURL = smGetImgSrc($content);
			$inhistory = sm_check_in_master_log('Feed To WP Post', $campaign, $link);

			if ($inhistory == 0) {
				$postid = smPostToBlog($imgURL, $content, $title, $link, $campaign, $source->ioId);
				sm_add_to_master_log('Feed To WP Post', $campaign, $link, get_permalink($postid), $link, $postid);
				return true;
			}
		}
	}
}

function smPostYoutubeChannel($campaign, $source) {
	require_once 'smYoutubeAPI.php';

	$googleApiKey = get_post_meta(111111113, 'smGoogle', true);
	$url = $source->url;

	if (empty($url)) {
		return false;
	}

	if ($source->titlesetId != '0') {
		$titles = sm_getTitlesArray($source->titlesetId);
	}

	$youtubeClient = new smYoutubeAPI(array('key' => $googleApiKey));

	try {
		$channel = $youtubeClient->getChannelFromURL($url);
		$videos = $youtubeClient->searchChannelVideos('', $channel->id, date('c'));

		foreach ($videos as $video) {
			$thumbnail = $video->snippet->thumbnails->default->url;
			$titleFromYoutube = $video->snippet->title;
			$description = $video->snippet->description;
			$id = $video->id->videoId;
			$link = 'http://youtu.be/' . $id;
			$embedcode = '<iframe width="640" height="360" src="//www.youtube.com/embed/' . $id . '" frameborder="0" allowfullscreen></iframe>';

			if ($source->titlesetId === '0' || $titles === false) {
				$title = $titleFromYoutube;
			} else {
				$title = $titles[array_rand($titles, 1)];
				if (empty($title)) {
					$title = $titleFromYoutube;
				}

				$spintax = new smSpintax();
				$title = $spintax->process($title);
			}

			$inhistory = sm_check_in_master_log('Youtube Channel To WP Post', $campaign, $id);
			if ($inhistory == 0) {
				$postid = smPostToBlog($thumbnail, $embedcode . $description, $title, $link, $campaign, $source->ioId);
				sm_add_to_master_log('Youtube Channel To WP Post', $campaign, $id, get_permalink($postid), $link, $postid);
				return true;
			}
		}
	} catch (Exception $ex) {
		return false;
	}

	return false;
}

function smPostYoutubePlaylist($campaign, $source) {
	require_once 'smYoutubeAPI.php';

	$googleApiKey = get_post_meta(111111113, 'smGoogle', true);
	$url = $source->url;

	if (empty($url)) {
		return false;
	}

	if ($source->titlesetId != '0') {
		$titles = sm_getTitlesArray($source->titlesetId);
	}

	$youtubeClient = new smYoutubeAPI(array('key' => $googleApiKey));

	try {
		$playlist = $youtubeClient->getPlaylistFromURL($url);
		$videos = $youtubeClient->getPlaylistItemsByPlaylistId($playlist);

		foreach ($videos as $video) {
			$thumbnail = $video->snippet->thumbnails->default->url;
			$titleFromYoutube = $video->snippet->title;
			$description = $video->snippet->description;
			$id = $video->contentDetails->videoId;
			$link = 'http://youtu.be/' . $id;
			$embedcode = '<iframe width="640" height="360" src="//www.youtube.com/embed/' . $id . '" frameborder="0" allowfullscreen></iframe>';

			if ($source->titlesetId === '0' || $titles === false) {
				$title = $titleFromYoutube;
			} else {
				$title = $titles[array_rand($titles, 1)];
				if (empty($title)) {
					$title = $titleFromYoutube;
				}

				$spintax = new smSpintax();
				$title = $spintax->process($title);
			}

			$inhistory = sm_check_in_master_log('Youtube Playlist To WP Post', $campaign, $id);
			if ($inhistory == 0) {
				$postid = smPostToBlog($thumbnail, $embedcode . $description, $title, $link, $campaign, $source->ioId);
				sm_add_to_master_log('Youtube Playlist To WP Post', $campaign, $id, get_permalink($postid), $link, $postid);
				return true;
			}
		}
	} catch (Exception $ex) {
		return false;
	}

	return false;
}

function smGetImgSrc($content) {
	$matches = array();
	$match = preg_match('/\bhttps?:\/\/\S+(?:png|jpg)\b/', $content, $matches);

	if ($match == 1) {
		return $matches[0];
	} else {
		return "";
	}
}

function smPostFacebookFanPage($campaign, $source) {
	$url = $source->url;

	if (empty($url)) {
		return false;
	}

	if ($source->titlesetId != '0') {
		$titles = sm_getTitlesArray($source->titlesetId);
	}

	try {
		$raw = smFacebookQuery("$url/feed", '', $campaign);
		$result_data = $raw["data"];

		foreach ($result_data as $dt) {
			$id = $dt['id'];
			$description = $dt['message'];
			$originalTitle = $dt['story'];
			$link = 'https://facebook.com/' . $id;

			if ($source->titlesetId === '0' || $titles === false) {
				$title = $originalTitle;
			} else {
				$title = $titles[array_rand($titles, 1)];
				if (empty($title)) {
					$title = $originalTitle;
				}

				$spintax = new smSpintax();
				$title = $spintax->process($title);
			}

			$inhistory = sm_check_in_master_log('Facebook Fan Page To WP Post', $campaign, $id);
			if ($inhistory == 0) {
				$postid = smPostToBlog($thumbnail, $embedcode . $description, $title, $link, $campaign, $source->ioId);
				sm_add_to_master_log('Facebook Fan Page To WP Post', $campaign, $id, get_permalink($postid), $link, $postid);
				return true;
			}
		}
	} catch (Exception $ex) {
		return false;
	}

	return false;
}

function smPostInstagram($campaign, $source) {
	$url = $source->url;

	if (empty($url)) {
		return false;
	}

	require __DIR__ . '/composer/vendor/autoload.php';

	$smIGUser = get_post_meta(111111113, $campaign . 'smIGUser', true);
	$smIGPassword = get_post_meta(111111113, $campaign . 'smIGPassword', true);

	if (empty($smIGUser) || empty($smIGPassword)) {
		return false;
	}

	$instagram = new \Instagram\Instagram();

	if ($source->titlesetId != '0') {
		$titles = sm_getTitlesArray($source->titlesetId);
	}

	try {
		$instagram->login($smIGUser, $smIGPassword);
		$user = $instagram->getUserByUsername($url);
		$feeds = $instagram->getUserFeed($user->getPk());

		foreach ($feeds->getItems() as $item) {
			$images = $item->getImageVersions2()->getCandidates();
			$image = '';
			$video = '';
			$title = '';

			if (sizeof($images) > 0) {
				$image = $images[0]->getUrl();
			}
			$embedcode = "<img src='$image' alt='from instagram' />";

			// if (!$item->isVideo()) {
			// 	continue;
			// }

			if ($item->isVideo()) {
				$videos = $item->getVideoVersions();

				if (sizeof($videos) > 0) {
					$video = $videos[0]->getUrl();
					$embedcode = "<video controls><source src='{$video}' type='video/mp4'></video>";
				}
			}

			$id = $item->getId();
			$link = sm_instagram_id_to_url($id);

			if ($source->titlesetId === '0' || $titles === false) {
				$title = '';
			} else {
				$title = $titles[array_rand($titles, 1)];

				if (empty($title)) {
					$title = '';
				}
				$spintax = new smSpintax();
				$title = $spintax->process($title);
			}

			$inhistory = sm_check_in_master_log('Instagram Account To WP Post', $campaign, $id);

			if ($inhistory == 0) {
				$postid = smPostToBlog($image, $embedcode, $title, $link, $campaign, $source->ioId);
				sm_add_to_master_log('Instagram Account To WP Post', $campaign, $id, get_permalink($postid), $link, $postid);
				return true;
			}
		}
	} catch (Exception $ex) {
		var_dump($ex);
		return false;
	}

	return false;
}

function smPostTwitter($campaign, $source) {
	require_once 'TwitterAPIExchange.php';
	$user = $source->url;

	if (empty($user)) {
		return false;
	}

	if ($source->titlesetId != '0') {
		$titles = sm_getTitlesArray($source->titlesetId);
	}

	$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/user_timeline.json';
	$requestMethod = 'GET';

	$twitter = new TwitterAPIExchange($settings);
	$tweets = $twitter->setGetfield('?screen_name=' . $user . '&include_entities=1')
		->buildOauth($url, $requestMethod)
		->performRequest();

	$tweets = json_decode($tweets, true);
	if (isset($tweets['errors'])) {
		echo "error...";
		return false;
	}

	foreach ($tweets as $tweet) {
		$id = $tweet['id_str'];
		$content = $tweet['text'];
		$titleFromFeed = $tweet['text'];

		$link = "https://twitter.com/statuses/$id";

		$img = '';
		$video = '';

		if (!empty($tweet['extended_entities']) && !empty($tweet['extended_entities']['media'])) {
			foreach ($tweet['extended_entities']['media'] as $media) {
				if ($media['type'] === 'video') {
					$img = $media['media_url_https'];

					if (!empty($media['video_info']) && !empty($media['video_info']['variants'])) {
						foreach ($media['video_info']['variants'] as $varient) {
							if ($variant['content_type'] === 'video/mp4') {
								$video = $variant['content'];
								break;
							}
						}
					}
				} else if ($media['type'] === 'photo') {
					$img = $media['media_url_https'];
				}
			}
		}

		if ($source->titlesetId === '0' || $titles === false) {
			$title = $titleFromFeed;
		} else {
			$title = $titles[array_rand($titles, 1)];
			if (empty($title)) {
				$title = $titleFromFeed;
			}

			$spintax = new smSpintax();
			$title = $spintax->process($title);
		}

		if (empty($img) && empty($video)) {
			continue;
		}

		if (!empty($video)) {
			$content .= "<video controls><source src='{$video}' type='video/mp4'></video>";
		}
		if (!empty($img)) {
			$content .= "<img src='$image' alt='from Twitter' />";
		}

		$inhistory = sm_check_in_master_log('Twitter Account To WP Post', $campaign, $id);

		if ($inhistory == 0) {
			$postid = smPostToBlog($img, $content, $title, $link, $campaign, $source->ioId);
			sm_add_to_master_log('Twitter Account To WP Post', $campaign, $id, get_permalink($postid), $link, $postid);
			return true;
		}
	}
}

class smSpintax {
	public function process($text) {
		return preg_replace_callback(
			'/\{(((?>[^\{\}]+)|(?R))*)\}/x',
			array($this, 'replace'),
			$text
		);
	}

	public function replace($text) {
		$text = $this->process($text[1]);
		$parts = explode('|', $text);
		return $parts[array_rand($parts)];
	}
}

function smFacebookQuery($query, $params, $campaign) {
	$post_url = 'https://graph.facebook.com/' . $query;
	$accesstoken = get_post_meta(111111113, $campaign . 'smaccesstoken', true);
	$post_url = $post_url . '?access_token=' . $accesstoken . $params;

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $post_url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	$result = curl_exec($ch);
	curl_close($ch);

	$result = json_decode($result, true);
	return $result;
}

function sm_instagram_id_to_url($instagram_id) {
	$url_prefix = "https://www.instagram.com/p/";

	if (!empty(strpos($instagram_id, '_'))) {
		$parts = explode('_', $instagram_id);
		$instagram_id = $parts[0];
		$userid = $parts[1];
	}

	$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';

	while ($instagram_id > 0) {
		$remainder = $instagram_id % 64;
		$instagram_id = ($instagram_id - $remainder) / 64;
		$url_suffix = $alphabet{$remainder} . $url_suffix;
	}
	;

	return $url_prefix . $url_suffix;
}

function smPostPinterest($campaign, $source) {
	$url = $source->url;

	if (empty($url)) {
		return false;
	}

	if ($source->titlesetId != '0') {
		$titles = sm_getTitlesArray($source->titlesetId);
	}

	$rss = fetch_feed(trim($url, '/') . '.rss');

	if (!is_wp_error($rss)) {
		$maxitems = $rss->get_item_quantity(0);
		$rss_items = $rss->get_items(0, $maxitems);

		foreach ($rss_items as $item) {
			$link = $item->get_permalink();
			$content = smFixPinRelativeURL($item->get_content());
			$titleFromFeed = $item->get_title();

			if ($source->titlesetId === '0' || $titles === false) {
				$title = $titleFromFeed;
			} else {
				$title = $titles[array_rand($titles, 1)];

				if (empty($title)) {
					$title = $titleFromFeed;
				}

				$spintax = new smSpintax();
				$title = $spintax->process($title);
			}

			$imgURL = smGetImgSrc($content);
			$inhistory = sm_check_in_master_log('Pinterest Board To WP Post', $campaign, $link);

			if ($inhistory == 0) {
				$postid = smPostToBlog($imgURL, $content, $title, $link, $campaign, $source->ioId);
				sm_add_to_master_log('Pinterest Board to WP Post', $campaign, $link, get_permalink($postid), $link, $postid);
				return true;
			}
		}
	}
}

function smFixPinRelativeURL($content) {
	return str_replace("<a href=\"/pin/", "<a href=\"https://www.pinterest.com/pin/", $content);
}

function smPostReddit($campaign, $source) {
	$url = $source->url;

	if (empty($url)) {
		return false;
	}

	if ($source->titlesetId != '0') {
		$titles = sm_getTitlesArray($source->titlesetId);
	}

	$rss = fetch_feed(trim($url, '/') . '.rss');

	if (!is_wp_error($rss)) {
		$maxitems = $rss->get_item_quantity(0);
		$rss_items = $rss->get_items(0, $maxitems);

		foreach ($rss_items as $item) {
			$link = $item->get_permalink();
			$content = $item->get_content();
			$titleFromFeed = $item->get_title();

			if ($source->titlesetId === '0' || $titles === false) {
				$title = $titleFromFeed;
			} else {
				$title = $titles[array_rand($titles, 1)];

				if (empty($title)) {
					$title = $titleFromFeed;
				}

				$spintax = new smSpintax();
				$title = $spintax->process($title);
			}

			$imgURL = smGetImgSrc($content);
			$inhistory = sm_check_in_master_log('Reddit Subreddit To WP Post', $campaign, $link);

			if ($inhistory == 0) {
				$postid = smPostToBlog($imgURL, $content, $title, $link, $campaign, $source->ioId);
				sm_add_to_master_log('Reddit Subreddit to WP Post', $campaign, $link, get_permalink($postid), $link, $postid);
				return true;
			}
		}
	}
}