<?php
    date_default_timezone_set('America/New_York');
	require 'vendor/autoload.php';
	use GuzzleHttp\Client;
	use GuzzleHttp\Psr7\Response;
	use STS\Backoff;
	// *************************
	// Helpful Functions
	// *************************
	function url_add_var($url, $key, $value) {
		
		$url = preg_replace('/(.*)(?|&)'. $key .'=[^&]+?(&)(.*)/i', '$1$2$4', $url .'&');
		$url = substr($url, 0, -1);
		
		if (strpos($url, '?') === false) {
			return ($url .'?'. $key .'='. $value);
		} else {
			return ($url .'&'. $key .'='. $value);
		}
	}
	
	function getUserIP() {
		$client  = @$_SERVER['HTTP_CLIENT_IP'];
		$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
		$remote  = $_SERVER['REMOTE_ADDR'];

		if(filter_var($client, FILTER_VALIDATE_IP)) {
			$ip = $client;
		} elseif(filter_var($forward, FILTER_VALIDATE_IP)) {
			$ip = $forward;
		} else {
			$ip = $remote;
		} return $ip;
	}

	function woo_request($query_params, $uri) {
	    $woo_client = new GuzzleHttp\Client(['base_uri' => 'http://www.woopra.com']);
		$response = $woo_client->request('GET', $uri, ['query' => $query_params]);		
	}

	$ac_response = '';
    function ac_request($query_params, $api_action) {
		global $email, $adate, $ac_response;
        $ac_client = new GuzzleHttp\Client(['base_uri' => 'https://rif868.api-us1.com']);
        $uri = '/admin/api.php?api_key=222513def0a1b0a53f1b242f87504b9c14bbf6ab5968305bf070e40dfc2787a76f08768a&api_action='.$api_action.'&api_output=serialize';
        $response = $ac_client->request('POST', $uri, ['form_params' => $query_params]);
        $ac_response = $response->getBody();	
	    $f = fopen('./logs/ac_'.$api_action.'.csv', 'a');
	    fwrite($f,$adate.", ".$email. ", ".$ac_response.PHP_EOL); 
	    fclose($f);
    }


	// *************************
	// End Of Helpful Functions
	// *************************
	
	header('Access-Control-Allow-Origin:*');

	header('Access-Control-Allow-Methods:GET,POST,PUT');

	header("Access-Control-Allow-Headers:Requested-With");
    $name = 'Reader';
    $first_name = 'Reader';
    $last_name = '';
	$email = '';
	$listid = '2';
	$subid = '';
	$affid = '';
	$confirmation_page = 'https://wallstwatchdogs.com';
	$promoLink ='';
	$shareLead = '';
	$source = '';
	$term = '';
	$campaign = '';
	$content = '';
	$form_title = '';
	$rifUuid = '';
	$prefix = 'px1_';
    $rcn = 'rp1_';
    $dmn = 'px1.co';
    $gclid = '';
    $macobrand = 'false';
    $acecobrand = 'false';
    $sntcobrand = "false";       
    $client_id = $_COOKIE['_ga'] || '0';
    $timezone = '0';
    $cb_option = '';
    $adate = date("F j, Y, g:i a");
    $woo_tracker = $_COOKIE['wooTracker'] || '0';
	
    
	try{
		$confirmation_page = $_REQUEST["coregLink"]; 
		$confirmation_page = htmlspecialchars_decode($confirmation_page);
	} catch (Exception $e) {}

    try{
        $timezone = $_REQUEST['timezone'];
    } catch (Exception $e) {}
	
	try{
		$name = $_REQUEST["name"];
		    $tname = trim($name);
            $last_name = (strpos($tname, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $tname);
            setcookie('grName', $tname, time()+3600*24*730, '/', '.wallstreetwatchdogs.com', false);
            $first_name = trim( preg_replace('#'.$last_name.'#', '', $tname ) );
            $confirmation_page = url_add_var($confirmation_page, 'c1', $first_name);
	} catch (Exception $e) {}	


	try{
		$email = $_REQUEST["email"];
		setcookie('gr_email', $email, time()+3600*24*730, '/', '.wallstreetwatchdogs.com', false);
		$confirmation_page = url_add_var($confirmation_page, 'c2', $email);
	} catch (Exception $e) {}

	$md_email = md5(strtolower(trim($email)));

	try{
		$source = $_REQUEST["source"];
	} catch (Exception $e) {}	

	try{
		$term = $_REQUEST["term"];
	} catch (Exception $e) {}
	
	try{
		$campaign = $_REQUEST["campaign"];
	} catch (Exception $e) {}	
	
	try{
		$content = $_REQUEST["content"];
	} catch (Exception $e) {}	
	
	try{
		$listid = $_REQUEST["list_id"];
	} catch (Exception $e) {}
	
	try{
		$form_title = $_REQUEST["formTitle"];
	} catch (Exception $e) {}


    try{
    	$woo_tracker = $_REQUEST["woo-tracker"];
    	setcookie('wooTracker', $woo_tracker, time()+3600*24*730, '/', '.wallstreetwatchdogs.com', false);
    } catch (Exception $e) {}

   
	try{
		$gclid = $_REQUEST["gclid"];
	} catch (Exception $e) {}

    if($client_id == '0') {
        try{
            $client_id = $_REQUEST['gac'];
            setcookie('_ga', $client_id, time()+3600*24*730, '/', '.wallstreetwatchdogs.com', false);
        } catch (Exception $e) {}
    }
	$ipv4 = getUserIP();
/***************HONEY POT****************************/
    function honeypot_validade ($req) {
        if (!empty($req)) {
            $honeypot_fields = [
                "zipcode",
                "phonenumber"
            ];
            foreach ($honeypot_fields as $field) {
                if (isset($req[$field]) && !empty($req[$field])) {
                    return false;
                }
            }
        }
        return true;
    }
    if (honeypot_validade($_REQUEST)) {
        $is_spammer = false;
    } else {
        $is_spammer = true;
    }
/***************END HONEY POT********************/	
	
	
	
	$confirmation_page = url_add_var($confirmation_page, 'c4', $woo_tracker);
	$confirmation_page = url_add_var($confirmation_page, 'utm_source', $source);
	$confirmation_page = url_add_var($confirmation_page, 'utm_term', $term);
	$confirmation_page = url_add_var($confirmation_page, 'utm_campaign', $campaign);
	$confirmation_page = url_add_var($confirmation_page, 'utm_content', $content);
	if($gclid != 'undefined') {
	    if($gclid != '0') {
    	    $confirmation_page = url_add_var($confirmation_page, 'gclid', $gclid);
	    }
	}
	$confirmation_page = url_add_var($confirmation_page, 'fid', $form_title);
	$confirmation_page = url_add_var($confirmation_page, 'cid', $client_id);	
    $confirmation_page = url_add_var($confirmation_page, 'email', $email);

    	ignore_user_abort(true);
    	set_time_limit(0);
        ob_start();
    	$size = ob_get_length();
    	header("location: ".$confirmation_page);	
        header("Content-Encoding: none");
        header("Content-Length: {$size}");
        header("Connection: close");
		flush();
        ob_flush();
        fastcgi_finish_request(); 
        if(session_id()) session_write_close();  


/***************HONEY POT****************************/
    if($is_spammer === true) {
        $f = fopen('../bots.csv', 'a');
	    fwrite($f,$adate.", ".$email. ", ".$first_name.", ".$last_name.", ".getUserIP().", ".$_REQUEST['zipcode'].", ".$_REQUEST['phonenumber'].PHP_EOL); 
	    fclose($f);
	    $f = fopen('./logs/bots.csv', 'a');
	    fwrite($f,$adate.", ".$email. ", ".$first_name.", ".$last_name.", ".getUserIP().", ".$_REQUEST['zipcode'].", ".$_REQUEST['phonenumber'].PHP_EOL); 
	    fclose($f);
/***************End HONEY POT****************************/	    
    } else {
		if(strlen($email) > 5) {
    		$acct_code = 'AE4002';
    		$pwd = '2iFm4K';
    		$url = 'https://post.impressionwise.com/verifyme.aspx?CODE='.$acct_code.'&PWD='.$pwd.'&email='.urlencode($email);

    		$ch = curl_init($url);
    
    		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 35); 
    		curl_setopt($ch, CURLOPT_TIMEOUT,55); 
    		$response = curl_exec($ch);
    		curl_close($ch);
    		 
    		$json = json_decode($response, true);
    	    $f = fopen('./logs/imp_wise.csv', 'a');
    			fwrite($f,$adate.", ".$response.PHP_EOL); 
    			fclose($f); 
    			
			if($json["RESULT"] != "SUPPRESS") {
				$post = array(
					'email' =>  $email,
					'first_name' => $first_name,
					'last_name' => $last_name,
					'field[%RIFUUID%,0]' => $rifUuid,
					'field[%ACQSOURCE%,0]' => $source,
					'field[%ACQDATE%,0]' => $adate,
					'field[%ACQCAMPAIGN%,0]' => $campaign,
					'field[%ACQCONTENT%,0]' => $content,
					'field[%ACQTERM%,0]' => $term,
					'field[%FORMTITLE%,0]' => $form_title,
					'field[%GCLID%,0]' => $gclid,
					'field[%GA_CLIENT_ID%,0]' => $client_id,
					'field[%TIMEZONE%,0]' => $timezone,
					'field[%WOOTRACKER%,0]' => $woo_tracker,
					'ip4' => $ipv4,
					'p[2]' => 2,
					'instantresponders[2]' => 0,
					'status[2]' => 1
				);
				ac_request($post, 'contact_add');

		    	if (stripos($ac_response, "Contact Added") === false) {

					$matches = explode("\"",$ac_response);
					$ac_id = $matches[3];
					setType($ac_id, 'int');

					$post = array(
						'id' => $ac_id,
						'email' =>  $email,	 
						'overwrite' => 0,
						'p[2]' => 2,
						'status[2]' => 1,
						'field[%FORMTITLE%,0]' => $form_title,
						'field[%LAST_SUB_DATE%,0]' => $adate
					);

					ac_request($post, 'contact_edit');			        

					$post = array(
						'contact_id' => $ac_id,
						'contact_email' =>  $email,	 
						'automation' => '56'
					);			        
					ac_request($post, 'automation_contact_add');

				}
				
			    $api_key = '9ca58fbbedf04dd8b68ed84e557f54cd';
			    $url = 'https://api.zerobounce.net/v2/validate?api_key='.$api_key.'&email='.urlencode($email).'&ip_address='.urlencode($ipv4);
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_SSLVERSION, 6);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); 
                curl_setopt($ch, CURLOPT_TIMEOUT, 150); 
                $response = curl_exec($ch);
                curl_close($ch);
                $json = json_decode($response, true);
                
                if(($json['status'] == 'valid') || ($json['status'] == 'unknown')) {
                
				$wid = array(
					"project" => 'wallstreetwatchdogs.com',
					"cookie" => $woo_tracker,
					"cv_email" => $email
				); 
				woo_request($wid, 'track/identify');
				
        		$rand_a = rand(1,100);
        		$rand_b = rand(1,100);
        		$rand_c = rand(1,100);	
        		
				$wdata = array(
					"domain" => 'wallstreetwatchdogs.com',
					'event' => 'process_form',
					'ce_form_title' => $form_title,
					'cv_is_cobranded' => $macobrand,
					'cv_ga_client_id' => $client_id,
					"cv_email" => $email,
					"cv_name" => $name,
					"ce_acq_source" => $source,
					"ce_acq_campaign" => $campaign,
					"ce_acq_content" => $content,
					"ce_acq_term" => $term,
					"cv_acq_source" => $source,
					"cv_acq_campaign" => $campaign,
					"cv_acq_content" => $content,
					"cv_acq_term" => $term,
					"cv_form_title" => $form_title,
					"cv_gclid" => $gclid,
					"cv_ipv4" => $ipv4,
					'ip' => $ipv4,
					'cv_acq_date' => $adate,
					'cookie' => $woo_tracker,
					'cv_md5' => $md_email,
					'cs_gclid' => $gclid,
					'cv_rand_a' => $rand_a,
					'cv_rand_b' => $rand_b,
					'cv_rand_c' => $rand_c				
                );
            	woo_request($wdata, 'track/ce');
				

            }	
    	}
	}		
}
sleep(2);
exit;		
?>