<?php
/*
Plugin Name: SocialTrafficBot Pro
Plugin URI: http://social-traffic-bot.com
Description: Build REAL Fanpage followers on autopilot.
Version: 1.0.0
Author: Dan Green
 */

ini_set('display_errors', 0);
 error_reporting(E_ALL ^ E_NOTICE ^ E_STRICT);

require_once 'sminstall.php';
register_activation_hook(__FILE__, 'smpro_install');

if (!function_exists('register_sm_dashboard_widget')) {

	session_start();
	require_once ABSPATH . 'wp-includes/pluggable.php';
	require_once __DIR__ . '/facebook/graph-sdk/src/Facebook/autoload.php';

	require_once 'smsettings.php';
	require_once 'smcampaigns.php';
	require_once 'class.smcampaigns.php';

	require_once 'smfeeds.php';
	require_once 'class.smfeeds.php';

	require_once 'smtitlesets.php';
	require_once 'class.smtitlesets.php';

	 require_once 'sm_intros_outros.php';
	 require_once 'class.sm_intros_outros.php';

	require_once 'smpages.php';
	require_once 'class.smpages.php';

	require_once 'smYoutubeAPI.php';
	require_once 'smlog.php';
	require_once 'class.smlog.php';

	require_once 'smcustom.php';
	require_once 'class.smcustom.php';

	require_once 'smviralspiral.php';
	require_once 'class.smviralspiral.php';

	require_once 'smautoblogging.php';

	require_once __DIR__ . "/pinterest/nxs-api/nxs-api.php";
	require_once __DIR__ . "/pinterest/nxs-api/nxs-http.php";
	require_once __DIR__ . "/pinterest/inc/nxs-functions.php";

	$image = plugin_dir_url(__FILE__) . 'logo.png';
	$favicon = plugin_dir_url(__FILE__) . 'favicon.png';

	define("SOCIALTRAFFICBOT", "<img src ='" . $image . "' />");

	add_action('admin_menu', 'sm_menu');
	add_action('admin_enqueue_scripts', 'sm_admin_scripts');

	require 'plugin_update_check.php';
	$MyUpdateChecker = new PluginUpdateChecker_2_0(
		'https://kernl.us/api/v1/updates/12345/',
		__FILE__,
		'socialtrafficbot',
		1
	);

	add_action('wp_dashboard_setup', 'register_sm_dashboard_widget');
	function register_sm_dashboard_widget() {
		wp_add_dashboard_widget(
			'sm_dashboard_widget',
			'Recommended Software For You',
			'sm_promotion_widget_display'
		);
		global $wp_meta_boxes;
		$normal_dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
		$sm_dashboard_widget = array(
			'sm_dashboard_widget' => $normal_dashboard['sm_dashboard_widget'],
		);
		unset($normal_dashboard['sm_dashboard_widget']);
		$sorted_dashboard = array_merge($sm_dashboard_widget, $normal_dashboard);
		$wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;
	}

	function sm_promotion_widget_display() {
		echo file_get_contents('http://fanmarketer.net/app-promotions.php');
	}

	function sm_menu() {
		$hook = add_menu_page('SocialTrafficBot', __('SocialTrafficBot', 'sm'), 'manage_options', 'sm', 'sm_admin', plugin_dir_url(__FILE__) . 'favicon.png');
		$settings = add_submenu_page('sm', 'Settings', 'Settings', 'manage_options', 'sm', 'sm_settings');
		$campaigns = add_submenu_page('sm', 'Campaigns', 'Campaigns', 'manage_options', 'sm_campaigns', 'sm_campaigns');
		$support = add_submenu_page('sm', 'Support', 'Support', 'manage_options', 'sm_support', 'sm_support');
	}

	function sm_support() {
		echo '<div class = "wrap">
		<div class = "fbvahead">
		' . SOCIALTRAFFICBOT . ' </div>
		<h1> Support</h1>
		<hr />
		<iframe src="https://socialtrafficbot.co/support/smsupport.html" width = "100%" height = "4500px" scrolling = "no"></iframe> ';
	}

	function sm_admin() {

	}

	function sm_admin_scripts() {
		wp_enqueue_style('fb-admin-css', plugins_url('admin-style.css', __FILE__), false);
		wp_enqueue_style('togglescss', plugins_url('css/tinytools.toggleswitch.min.css', __FILE__), false);
		wp_enqueue_script('jquery');
		wp_enqueue_script('toggles', plugins_url('tinytools.toggleswitch.min.js', __FILE__), false);
		wp_enqueue_script('chart', plugins_url('chart.js', __FILE__), false);
		wp_enqueue_script('editinline', plugins_url('editinline.js', __FILE__), false);
	}

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

		$params = "&limit=5000";
		$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_add_to_master_log($source, $campaign_id, $uid, $url, $description = '', $wpPostId = null, $error = '') {
		global $wpdb;

		$wpdb->show_errors();
		$table_name = $wpdb->prefix . "smmasterlog";

		$result = $wpdb->insert($table_name, array(
			'source' => $source,
			'campaign_id' => $campaign_id,
			'uid' => $uid,
			'description' => $description,
			'url' => $url,
			'error' => $error,
			'created_at' => time(),
			'post_id' => $wpPostId,
		));
	}

	function sm_check_in_master_log($source, $campaign_id, $uid) {
		global $wpdb;
		$wpdb->show_errors();

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

		$result = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT * FROM $table_name WHERE source=%s and campaign_id=%s and uid=%s",
				$source, $campaign_id, $uid
			)
		);

		if ($result == null) {
			return 0;
		} else {
			return 1;
		}
	}

	function smSelectCampaign() {
		global $wpdb;
		$wpdb->show_errors();

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

		$query = "SELECT id FROM $table_name WHERE name!='' AND status='ON' ORDER BY RAND() limit 1";
		$campaign = $wpdb->get_var($query);
		return $campaign;
	}

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

		$table_name = $wpdb->prefix . "smmasterlog";
		$query = "SELECT post_id FROM $table_name WHERE source in ('Facebook Fan Page To WP Post', 'Instagram Account To WP Post', 'Twitter Account To WP Post', 'Feed To WP Post', 'Youtube Channel To WP Post', 'Youtube Playlist To WP Post') AND campaign_id='$campaignId' ORDER BY RAND()";

		// $post = $wpdb->get_var($query);
		// return $post;

		$posts = $wpdb->get_results($query, "ARRAY_A");
		foreach ($posts as $post) {
			if (get_post_status($post['post_id']) == 'publish') {
				return $post['post_id'];
			}
		}
		return null;
	}

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

		$table_name = $wpdb->prefix . "smcustom";
		$query = "SELECT * FROM $table_name WHERE campaign='$campaignId' ORDER BY RAND() limit 1";
		$post = $wpdb->get_row($query);

		return $post;
	}

	function wpsmMySubreddits($campaign) {
		if (!class_exists('OAuth2/Client')) {
			require_once __DIR__ . '/oauth2/Client.php';
			require_once __DIR__ . "/oauth2/GrantType/IGrantType.php";
			require_once __DIR__ . "/oauth2/GrantType/AuthorizationCode.php";
			require_once __DIR__ . "/oauth2/GrantType/RefreshToken.php";
		}

		$clientId = get_post_meta(111111113, $campaign . 'smRdID', TRUE);
		$clientSecret = get_post_meta(111111113, $campaign . 'smRdSecret', TRUE);
		$refreshtoken = get_post_meta(111111113, $campaign . 'smRdRefreshToken', TRUE);

		$userAgent = 'SocialTrafficBot by DanGreen';
		$client = new OAuth2\Client($clientId, $clientSecret, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC);
		$client->setCurlOption(CURLOPT_USERAGENT, $userAgent);

		$response = $client->getAccessToken('https://ssl.reddit.com/api/v1/access_token', "refresh_token", array("refresh_token" => $refreshtoken));
		update_post_meta(111111113, $campaign . 'smRdAccessToken', $response["result"]["access_token"]);

		$accesstoken = $response["result"]["access_token"];

		$client->setAccessToken($accesstoken);
		$client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER);

		$response = $client->fetch("https://oauth.reddit.com/subreddits/mine/subscriber");

		return $response["result"]["data"]["children"];
	}

	function wpsmGetPinterestBoard($email, $password) {
		$nxs_gCookiesArr = smGetSavedPinterestLogin();

		$nt = new nxsAPI_PN();
		$nt->ck = $nxs_gCookiesArr;
		$loginError = $nt->connect($email, $password);

		if (!$loginError) {
			smSavePinterestLogin($nt->ck);
			$boards = smParseBoards($nt->getBoards());
			return $boards;
		} else {
			return $loginError;
		}
	}

	function smGetSavedPinterestLogin() {
		$pnTempLogin = get_post_meta(111111113, 'smPnTempLogin', true);
		if (empty($pnTempLogin)) {
			return null;
		}

		return unserialize($pnTempLogin);
	}

	function smSavePinterestLogin($obj) {
		update_post_meta(111111113, 'smPnTempLogin', serialize($obj));
	}

	function smParseBoards($str) {
		$matches = array();
		preg_match_all("/<option[^>]*value=\"(\d+)\">([^<]*)<\/option>/", $str, $matches);

		$out = array();

		if (!empty($matches)) {
			foreach ($matches[1] as $key => $val) {
				$out[$val] = $matches[2][$key];
			}
		}

		return $out;
	}

	function smReversePrintR($in) {
		$lines = explode("\n", trim($in));
		if (trim($lines[0]) != 'Array') {
			// bottomed out to something that isn't an array
			return $in;
		} else {
			// this is an array, lets parse it
			if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
				// this is a tested array/recursive call to this function
				// take a set of spaces off the beginning
				$spaces = $match[1];
				$spaces_length = strlen($spaces);
				$lines_total = count($lines);
				for ($i = 0; $i < $lines_total; $i++) {
					if (substr($lines[$i], 0, $spaces_length) == $spaces) {
						$lines[$i] = substr($lines[$i], $spaces_length);
					}
				}
			}
			array_shift($lines); // Array
			array_shift($lines); // (
			array_pop($lines); // )
			$in = implode("\n", $lines);
			// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
			preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
			$pos = array();
			$previous_key = '';
			$in_length = strlen($in);
			// store the following in $pos:
			// array with key = key of the parsed array's item
			// value = array(start position in $in, $end position in $in)
			foreach ($matches as $match) {
				$key = $match[1][0];
				$start = $match[0][1] + strlen($match[0][0]);
				$pos[$key] = array($start, $in_length);
				if ($previous_key != '') {
					$pos[$previous_key][1] = $match[0][1] - 1;
				}

				$previous_key = $key;
			}
			$ret = array();
			foreach ($pos as $key => $where) {
				// recursively see if the parsed out value is an array too
				$ret[$key] = smReversePrintR(substr($in, $where[0], $where[1] - $where[0]));
			}
			return $ret;
		}
	}
}
