<?php

/*

These functions handle all tracking of user activity and redirect handling for this plugin

*/

//Click Filter - Return 1 if user is filtered
function opt_filter() {

	global $wpdb;
	
	$ip_address = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
	$user_agent = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
	
	$filter_check = $wpdb->query('SELECT * FROM '.DWPC_DB_PREFIX.'dwpc_click_filter WHERE (ip_address = "'.$ip_address.'" AND user_agent = "'.$user_agent.'" ) OR (ip_address = "'.$ip_address.'" AND user_agent = "" )  OR (ip_address = "" AND user_agent = "'.$user_agent.'" )');
		
	
	if($filter_check>0) { return "1"; } else { return "0"; }

	
}


//Logs everything about the current page_view
function opt_log_impression($url='') {
   
	/*global $wpdb;	
	
	if($url=='') {
	
		if($_SERVER['SERVER_PORT'] == '443') { $http = 'https://';} else {$http = 'http://';};	
		
		$url = $http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	
	}
	
	if(strpos($_SERVER['REQUEST_URI'],'/wp-admin/') === false && $_GET['opt_viewing']!=1) {
		
	if(strpos($_SERVER['REQUEST_URI'],'/admin_pages/ajax/remote.php')!==false) { $url = $_SERVER['HTTP_REFERER']; }	
	
	if(strpos($url,'opt_viewing')===false) {
		
	$wp_post_id = get_the_ID();	
	
	//Get incoming click id, first by cookie then by visitor id
	
	if($_COOKIE['inc_click_id']!='')
		{
			 $incoming_click_id = $_COOKIE['inc_click_id'];				
		}
	else
		{
			 $incoming_click_id = $GLOBALS['opt_visitor']['opt_incoming_link_id'];
		}
		
	if($_SERVER['SERVER_PORT'] == '443') { $http = 'https://';} else {$http = 'http://';};	
		
	$impression_text_id = opt_random_string(7,7);	
		
	//Gather information about the impression
	$data = array(
		'id' => NULL,
		'text_id' => $impression_text_id,
		'filtered' => opt_filter(),
		'time_created' => current_time('mysql'),
		'dwpc_visitor_id' => $dwpc->visitor['id'],
		'ip_address' => $_SERVER['REMOTE_ADDR'],
		'impression_url' => $url,
		'referal_url' => $_SERVER['HTTP_REFERER']
	);
	
	
	//Insert the impression data into the impression table
	//$wpdb->insert(OPT_DB_PREFIX."opt_impressions", $data );
	//$last_impression = $wpdb->insert_id;	

	$GLOBALS['opt_impression_text_id'] = $impression_text_id;*/

	opt_active_visitor($dwpc->visitor['id'],$dwpc->impression['id']);
		
	//}}

}


//Handles everything related to visitor level tracking.
/*function opt_visitor_cookie() {	
	
   if(strpos($_SERVER['REQUEST_URI'],'/wp-admin/admin-ajax.php')!==false) { return; }
   
   global $wpdb;   
   		
	if($_COOKIE['opt_visitor'])
		{
			//Get the visitor information from the database
			$GLOBALS['opt_visitor'] = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_visitors WHERE cookie = '".$_COOKIE['opt_visitor']."' AND user_agent = '".$_SERVER['HTTP_USER_AGENT']."'",ARRAY_A);	
						
		}
		
	//If visitor is null then create a new visitor	
	if(!$GLOBALS['opt_visitor'])
		{		
		
			//Bake a cookie and then check to see if it's been created yet.
			$cookie = opt_random_string(10,10);
		
		
			$cookie_check = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_visitors WHERE cookie = '".$cookie."'");	
		
			while($cookie_check != null)
				{
					$cookie = opt_random_string(10,10);		
					$cookie_check = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_visitors WHERE cookie = '".$cookie."'");	
				}
			
			//Make cookie safe domain out of this domain
			$cookie_domain = preg_replace('/^www\./','',$_SERVER['HTTP_HOST']);
			$cookie_domain = preg_replace('/:\d+$/','',$cookie_domain);	
			
			//Swap out cookie with global value just to be sure
			if($GLOBALS['opt_visitor']['cookie']!='') { $cookie = $GLOBALS['opt_visitor']['cookie']; };
			
			$directory = "/";
			$days = 31;     
				
			$cookie_time = ($days<=0) ? "" : time()+($days*24*60*60);
			setcookie('opt_visitor',$cookie,$cookie_time,$directory,$cookie_domain);
				
	
		
			$userAgent = new opt_user_agent(); 
		
			//Geocode IP
			if(WPMT_GEOCODING == 1) {
				$geo = opt_geocode_ip($_SERVER['REMOTE_ADDR']);				
			}
		
			//Gather information about the visitor
			$data = array(
				'id' => NULL,		
				'filtered' => opt_filter(),
				'time_created' => current_time('mysql'),
				'cookie' => $cookie,
				'ip_address' => $_SERVER['REMOTE_ADDR'],
				'user_agent' => $_SERVER['HTTP_USER_AGENT'],
				'browser' => ucwords($userAgent->getBrowserName()).' '.$userAgent->getBrowserVersion(),
				'operating_system' => ucwords($userAgent->getOperatingSystem()),
				'referal_url' => $_SERVER['HTTP_REFERER'],
				'country_code' => $geo->country_code,
				'country_name' => $geo->country_name,
				'region_code' => $geo->region_code,
				'region_name' => $geo->region_name,
				'zipcode' => $geo->zipcode,
				'latitude' => $geo->latitude,
				'longitude' => $geo->longitude
			);
			
			//Insert the visitor data into the database
			$wpdb->insert(OPT_DB_PREFIX."opt_visitors", $data );
			
			//Make the visitor information available to the rest of the application
			$GLOBALS['opt_visitor'] = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_visitors WHERE cookie = '".$cookie."'",ARRAY_A);	
	
		}
}*/
        
//---------------------------------------------
//CHECK IF 404 AND DO A PRETTY REDIRECT
function opt_pretty_redirector() {
        
    global $wp_query;
    global $wpdb;				
	global $dwpc;

						
		
    //if($wp_query->is_404){
		
		
		//check if it's an opt redirect
		
		//get the relevant link id
		
		//redirect to secured page
		
		
		
		
		//Check for incoming link		
		
		//Get the details of the link coming in
		/*$link = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_incoming_links WHERE pretty_url = '".mysql_real_escape_string($_SERVER['REQUEST_URI'])."'",ARRAY_A);		
		
		if($wpdb->num_rows > 0) {
			//Get the destination url
			if($link['opt_split_test_id']!='' && $link['opt_split_test_id']!=0) 
				{
					opt_split_test_tracker($link['opt_split_test_id'],$link);
				}
			//Only 1 redirect url is possible, so get the destination url.
			elseif($link['opt_offer_id']!='' && $link['opt_offer_id']!='0')
				{ //Link goes out to an offer
					opt_incoming_click($link['id'],'',$link['opt_offer_id'],1);
				}
			elseif($link['opt_landing_page_id']!='' && $link['opt_landing_page_id']!='0')
				{ //Link goes to a landing page url
					opt_incoming_click($link['id']);							
				}
		}*/
        
		
		/*//Check for Offer
		$link = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_offers WHERE pretty_url = '".mysql_real_escape_string($_SERVER['REQUEST_URI'])."'",ARRAY_A);			
		
		if($wpdb->num_rows > 0) { opt_outgoing_click($link['id']); }*/
		
		
		/*//Check for split test
		$link = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_split_tests WHERE pretty_url = '".mysql_real_escape_string($_SERVER['REQUEST_URI'])."'",ARRAY_A);		
		
		if($wpdb->num_rows > 0) { opt_split_test_tracker($link['id']); }*/
		
		//Welp! Actual 404
		
		
	//}	
}

//---------------------------------------------
//Track an outgoing click and do redirect
function opt_outgoing_click($offer_id,$incoming_click_id='',$split_test_link='',$dont_redirect='') {
	
		global $wpdb;						
		global $dwpc;
		
		$offer = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_offers WHERE id = ".$offer_id,ARRAY_A);
	
		//Get incoming click id, first by cookie then by visitor id		
		if(is_numeric($incoming_click_id)) { 
		
			$incoming_click = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_incoming_clicks WHERE id = ".$incoming_click_id,ARRAY_A);
			
		} elseif(is_numeric($_COOKIE['inc_click_id'])) { 
	
			$incoming_click = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_incoming_clicks WHERE id = ".$_COOKIE['inc_click_id'],ARRAY_A); 			
			
		} else { 
				
			$incoming_click = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_incoming_clicks WHERE dwpc_visitor_id = ".$dwpc->visitor['id']." ORDER BY id DESC",ARRAY_A);
		
		}
		
		
		//Save outgoing click information
		$data = array(
			'id' => NULL,
			'filtered' => opt_filter(),
			'time_created' => current_time('mysql'),
			'dwpc_visitor_id' => $dwpc->visitor['id'],
			'dwpc_impression_id' => $_COOKIE['opt_last_impression'],
			'opt_incoming_click_id' => $incoming_click['id'],
			'opt_landing_page_id' => $incoming_click['opt_landing_page_id'],
			'opt_ad_id' => $incoming_click['opt_ad_id'],
			'opt_offer_id' => $offer['id'],
			'opt_split_test_id' => $split_test_link['opt_split_test_id'],
			'opt_split_test_link_id' => $split_test_link['id'],
			'ip_address' => $_SERVER['REMOTE_ADDR'],
			't1' => $_REQUEST['t1'],
			't2' => $_REQUEST['t2'],
			't3' => $_REQUEST['t3'],
			't4' => $_REQUEST['t4'],
			't5' => $_REQUEST['t5'],
			'log_offer_name' => $offer['name']
		);
		
		//Create the click
		$dwpc->insert(OPT_DB_PREFIX."opt_outgoing_clicks", $data );
		$click_id = $wpdb->insert_id;
		
		setcookie('out_click_id',$click_id,time()+2592000);
		
		//Build the redirect url		
		$destination_url = opt_url_builder($offer['link_url'],'offer','',$click_id) ;		
		
		//Update the click id with the url that has been built		
		$data = array(
			'redirect_url' => $destination_url
		);
		
		$dwpc->update(OPT_DB_PREFIX."opt_outgoing_clicks", $data, array( 'id' => $click_id ));
		
		if($dont_redirect!=1) {	
		//Do the redirect			
		header('location: '.$destination_url);
		}
	
}


//---------------------------------------------
//Track an incoming click and do redirect
function opt_incoming_click($incoming_link_id,$split_test_link='',$offer_id='',$dont_redirect='') {

	global $wpdb;					
	global $dwpc;
	
	
	//Incoming link information
	if(is_numeric($incoming_link_id)) {	$incoming_link = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_incoming_links WHERE id = ".$incoming_link_id,ARRAY_A); }
	//If incoming link id isn't set check to see if there's a split test link
	elseif($split_test_link!='') { $incoming_link = $split_test_link; }
	
	//Get keyword
	if($_REQUEST['keyword']!='') { $keyword = $_REQUEST['keyword'];	}
	//Try to get the keyword in any other means possible	
	//ADD THIS LATER WHEN ITS CLEARER
	else {	}
				
	//Get clickcost	
	if(is_numeric($_REQUEST['cost'])) { $click_cost = $_REQUEST['cost']; }			
	//Get avg clickcost from incoming link
	else { $click_cost = $incoming_link['click_cost'];}
			
	//Get the raw request url		
	$request_url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];	
	
	//Build destination url	if this isn't an offer url, because we dont redirect offer url's in this function duh		
	if($incoming_link['opt_landing_page_id']!='') { $url = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_landing_pages WHERE id = ".$incoming_link['opt_landing_page_id'],ARRAY_A); $destination_url = opt_url_builder($url['url'],'landing page',$incoming_link['url_variables']);}

		//Save incoming click information
		$data = array(
			'id' => NULL,
			'filtered' => opt_filter(),
			'time_created' => current_time('mysql'),
			'opt_ad_id' => $incoming_link['opt_ad_id'],
			'dwpc_visitor_id' => $dwpc->visitor['id'],
			'opt_incoming_link_id' => $incoming_link_id,
			'opt_landing_page_id' => $incoming_link['opt_landing_page_id'],
			'opt_split_test_id' => $split_test_link['opt_split_test_id'],
			'opt_split_test_link_id' => $split_test_link['id'],
			'ip_address' => $_SERVER['REMOTE_ADDR'],
			'click_cost' => $click_cost,
			'keyword' => $keyword,
			't1' => $_REQUEST['t1'],
			't2' => $_REQUEST['t2'],
			't3' => $_REQUEST['t3'],
			't4' => $_REQUEST['t4'],
			't5' => $_REQUEST['t5'],
			'referal_url' => $_SERVER['HTTP_REFERER'],
			'destination_url' => $destination_url,
			'request_url' => $request_url
		);
		
		$dwpc->insert(OPT_DB_PREFIX."opt_incoming_clicks", $data );
		$click_id = $wpdb->insert_id;
				
		//Create a cookie based on your click id	
		if($incoming_link_id!='') { setcookie('inc_click_id',$click_id,time()+2592000); }					
			
			
		if($dont_redirect!=1 || ($incoming_link['opt_landing_page_id']!='' && $dont_redirect!=1)) {	
		//Do the redirect	
		//echo $destination_url;		
		header('location: '.$destination_url);
		}
		
		if(is_numeric($offer_id)) {
			opt_outgoing_click($offer_id,$click_id,$split_test_link);	
		}
}



//Do the randomization of a split test and then send the link out for tracking and redirection
function opt_split_test_tracker($split_test_id) {
	
	global $wpdb;				
	global $dwpc;
						
	
	$split_test = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_split_tests WHERE id = ".$split_test_id,ARRAY_A);	
	
	$split_test_links = $wpdb->get_results("SELECT * FROM ".OPT_DB_PREFIX."opt_split_test_items WHERE opt_split_test_id = ".$split_test_id." AND deleted != 1");
	
	if(is_array($split_test) && $wpdb->num_rows > 0){
		
		
		$i = 0;
		$link_array = array();
			
		//Build the probability array	
		foreach ( $split_test_links as $split_test_link) 
			{
				$j = 1;
				while($j <= $split_test_link->item_weight) 
				{ 
					$link_array[] = $split_test_link->id; 
					$i++; 
					$j++; 
				}		
			}
			
		$i--;
		
		//Choose the link id
		$split_test_link_id = $link_array[rand(0,$i)];
		
		return $split_test_link_id;
	}
	return '';
}

function opt_url_builder($url,$url_type,$url_vars='',$click_id='') {

	$variables = array_merge($_GET, $_POST);
	
	$taken_vars = array('t1','t2','t3','t4','t5','keyword','cost','inc','goto');
	
	$output = '';
	
	foreach($variables as $key => $value)
		{
		
			if(in_array($key,$taken_vars)===false)
				{
					$output .= '&'.$key.'='.$value;
				}
			
		}
		
	if(strpos($url,'?')===false && $output!='') { $output = $url.'?'.$output;}
	else { $output = $url.$output; }
		
	if($url_type=='offer') { $output = str_replace('[[SUBID]]',$click_id,$output); }	
	
	if($url_vars!='' && strpos($url,'?')===false ) { $output = $output.'?'.$url_vars; } 
	elseif($url_vars!='') { $output = $output.'&'.$url_vars; } 
	
	return $output;
	
}

function opt_redirector() {
	
	global $wpdb;					
	global $dwpc;
						
	
	/*----------------------------------------------------------------
	INCOMING LINKS
	Redirect an incoming link to the right place and log the click
	------------------------------------------------------------------*/
	if(strlen($_REQUEST['inc'])==6) {
	
		//Get the details of the link coming in
		$link = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_incoming_links WHERE link = '".$_REQUEST['inc']."'",ARRAY_A);		
		
		if(is_array($link)){
			//Get the destination url
			if($link['opt_split_test_id']!='' && $link['opt_split_test_id']!=0) 
				{
					opt_split_test_tracker($link['opt_split_test_id'],$link);
				}
			//Only 1 redirect url is possible, so get the destination url.
			elseif($link['opt_offer_id']!='' && $link['opt_offer_id']!='0')
				{ //Link goes out to an offer
					opt_incoming_click($link['id'],'',$link['opt_offer_id'],1);
				}
			elseif($link['opt_landing_page_id']!='' && $link['opt_landing_page_id']!='0')
				{ //Link goes to a landing page url
					opt_incoming_click($link['id']);							
				}
			else
				{
					return; //Nothing is set right	
				}	
		}
	}
	
	/*----------------------------------------------------------------
	OUTGOING LINKS
	Redirect an outgoing link to the right place and log the click
	------------------------------------------------------------------*/
	elseif(strlen($_REQUEST['goto'])==6) {
		
		$link = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_offers WHERE link = '".$_REQUEST['goto']."'",ARRAY_A);		
		
		if(is_array($link)){opt_outgoing_click($link['id']);}
		
	}
	
	/*----------------------------------------------------------------
	SPLIT TEST LINKS
	Do a split test properly
	------------------------------------------------------------------*/
	elseif(strlen($_REQUEST['inc'])==7) {
		
		//Get the details of split test
		$link = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_split_tests WHERE link = '".$_REQUEST['inc']."'",ARRAY_A);
	
			
		if(is_array($link)){opt_split_test_tracker($link['id']);}
			
	}
	
	
	/*----------------------------------------------------------------
	CONVERSION HANDLER
	Create a conversion based on an Outgoing Click ID and a somewhat secure pass key
	------------------------------------------------------------------*/
		
	$opt_local_verified = 0 ;
    if ($_REQUEST['opt_local_conversion'] == 1) { 
        $allowed_domains_result = $wpdb->get_results("SELECT * FROM " . OPT_DB_PREFIX . "opt_settings WHERE name LIKE 'opt_allowed_domain_%' AND value != ''",ARRAY_A);
		if(is_array($allowed_domains_result)){ 
			foreach ($allowed_domains_result as $allowed_domain) {
				$allowed_domains[] = $allowed_domain['value'];
			}
			//$domain = parse_url('http://www.pop-polls.com');
			$domain = parse_url($_SERVER['HTTP_REFERER']);
			$domain = preg_replace('/^www\./', '', $domain['host']);
			$domain = preg_replace('/:\d+$/', '', $domain);
			if (in_array($domain, $allowed_domains)) {
				$opt_local_verified = 1;
			}
		}
    }
	
	if($opt_local_verified == 1) {
		
			//Both cookies are set so we're good to go
			if(isset($_COOKIE['dwpc_visitor']) && isset($_COOKIE['out_click_id']))
			{
				$visitor = $wpdb->get_row($wpdb->prepare( 'SELECT * FROM '.DWPC_DB_PREFIX.'dwpc_visitors WHERE cookie="'.$_COOKIE['dwpc_visitor'].'"'),ARRAY_A);
				$click = $wpdb->get_row($wpdb->prepare( "SELECT * FROM ".OPT_DB_PREFIX."opt_outgoing_clicks WHERE id = '".$_COOKIE['out_click_id']."'"),ARRAY_A);
					
			//Try to get visitor and get last outlick
			} elseif(isset($_COOKIE['dwpc_visitor'])) {
				
				$visitor = $wpdb->get_row($wpdb->prepare( 'SELECT * FROM '.DWPC_DB_PREFIX.'dwpc_visitors WHERE cookie="'.$_COOKIE['dwpc_visitor'].'"'),ARRAY_A);
				$click = $wpdb->get_row($wpdb->prepare( "SELECT * FROM ".OPT_DB_PREFIX."opt_outgoing_clicks WHERE dwpc_visitor_id = '".$visitor['id']."' ORDER BY id DESC"),ARRAY_A);			
			
			//Neither are set so just die	
			} else {
				
				exit;
				
			}			
			
			//if we already have a conversion for this outgoing click, exit. 
			if($wpdb->query('SELECT * FROM '.OPT_DB_PREFIX.'opt_conversions WHERE opt_outgoing_click_id = '.$click['id']) > 0 )
			{
				$image = "R0lGODlhBQAFAJH/AP///wAAAMDAwAAAACH5BAEAAAIALAAAAAAFAAUAAAIElI+pWAA7\n";
				header('Content-type: image/gif');
				echo base64_decode($image);
				exit;	
			}
		
			//Everything is good let's start logging a conversion
			if(is_array($visitor) && is_array($click)) {
			
				$offer = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_offers WHERE id = '".$click['opt_offer_id']."'",ARRAY_A);
				
				//Check to see if offer exists or die
				if(is_array($offer)) {
								
					if($_REQUEST['payout']!='')	{ $conversion_payout = $_REQUEST['payout'];	}
					else { $conversion_payout = $offer['default_payout']; }
					
					$data = array(
						'time_created' => current_time('mysql'),
						'dwpc_visitor_id' => $click['dwpc_visitor_id'],
						'opt_incoming_click_id' => $click['opt_incoming_click_id'],
						'opt_outgoing_click_id' => $click['id'],
						'opt_landing_page_id' => $click['opt_landing_page_id'],
						'opt_ad_id' => $click['opt_ad_id'],
						'opt_offer_id' => $click['opt_offer_id'],
						'opt_split_test_id' => $click['opt_split_test_id'],
						'opt_split_test_link_id' => $click['opt_split_test_link_id'],
						'payout' => $conversion_payout,
						'ip_address' => $_SERVER['REMOTE_ADDR'],
						't1' => $_REQUEST['t1'],
						't2' => $_REQUEST['t2'],
						't3' => $_REQUEST['t3'],
						't4' => $_REQUEST['t4'],
						't5' => $_REQUEST['t5'],
						'log_offer_name' => $offer['name']
					);
					$dwpc->insert(OPT_DB_PREFIX."opt_conversions", $data);
					
					$image = "R0lGODlhBQAFAJH/AP///wAAAMDAwAAAACH5BAEAAAIALAAAAAAFAAUAAAIElI+pWAA7\n";
					header('Content-type: image/gif');
					echo base64_decode($image);
					exit;		
					
				} else { exit; }
			}		
	}	
	
	//Make sure the conversion is a number and the pass key matches the constant set in opt.php
	if(is_numeric($_REQUEST['conversion']) && $_REQUEST['pass_key']==opt_settings('conversion_key')) {		
		
		//Get click info here
		if(is_numeric($_REQUEST['conversion'])) {
			$click = $wpdb->get_row("SELECT * FROM ".OPT_DB_PREFIX."opt_outgoing_clicks WHERE id = '".$_REQUEST['conversion']."'",ARRAY_A);		
		}		
		
		//if we already have a conversion for this outgoing click, exit. 
		if($wpdb->query('SELECT * FROM '.OPT_DB_PREFIX.'opt_conversions WHERE opt_outgoing_click_id = '.$click['id']) > 0 )
		{
	  		$image = "R0lGODlhBQAFAJH/AP///wAAAMDAwAAAACH5BAEAAAIALAAAAAAFAAUAAAIElI+pWAA7\n";
			header('Content-type: image/gif');
			echo base64_decode($image);
			exit;	
		}
		
		if($_REQUEST['payout']!='')	{ $conversion_payout = $_REQUEST['payout'];	}
		else { $conversion_payout = $offer['default_payout']; }
		
		$data = array(
			'time_created' => current_time('mysql'),
			'dwpc_visitor_id' => $click['dwpc_visitor_id'],
			'opt_incoming_click_id' => $click['opt_incoming_click_id'],
			'opt_outgoing_click_id' => $click['id'],
			'opt_landing_page_id' => $click['opt_landing_page_id'],
			'opt_ad_id' => $click['opt_ad_id'],
			'opt_offer_id' => $click['opt_offer_id'],
			'opt_split_test_id' => $click['opt_split_test_id'],
			'opt_split_test_link_id' => $click['opt_split_test_link_id'],
			'payout' => $conversion_payout,
			'ip_address' => $_SERVER['REMOTE_ADDR'],
			't1' => $_REQUEST['t1'],
			't2' => $_REQUEST['t2'],
			't3' => $_REQUEST['t3'],
			't4' => $_REQUEST['t4'],
			't5' => $_REQUEST['t5'],
			'log_offer_name' => $offer['name']
		);
		$dwpc->insert(OPT_DB_PREFIX."opt_conversions", $data);
	  	
		$image = "R0lGODlhBQAFAJH/AP///wAAAMDAwAAAACH5BAEAAAIALAAAAAAFAAUAAAIElI+pWAA7\n";
		header('Content-type: image/gif');
		echo base64_decode($image);
		exit;	
		
	}
	
}

function opt_set_js_variables($noscript='') {
	global $dwpc;
	
	
	$save_interval = opt_settings('save_interval');
	if($save_interval=='') { opt_settings('save_interval',20000); }

	?>
    <?php if($noscript!=1) { ?><script type="text/javascript"><?php } ?>
    var dwpc_visitor_id = '<?php echo  $dwpc->visitor['cookie'] ?>';
	var dwpc_impression_id = '<?php echo  $dwpc->impression['text_id'] ?>';
	var opt_ajaxurl = "<?php echo  admin_url('admin-ajax.php')  ; ?>";
    
   <?php if($noscript!=1) { ?></script><?php } ?>
    <?php
	
	
	
}

function opt_log_page_load_time() {
	
if($_SERVER['HTTP_X_REQUESTED_WITH']!='XMLHttpRequest') {

global $wpdb;
global $dwpc;

$load_time = timer_stop(0)*1000;

$data['load_time'] = $load_time;

/*if(is_numeric($GLOBALS['opt_visitor']['id']) && OPT_DB_PREFIX!='') {

$data['opt_visitor_id'] = $GLOBALS['opt_visitor']['id'];	
	
}*/

$wpdb->update(DWPC_DB_PREFIX."dwpc_impressions",$data,array('text_id' => $dwpc->impression['text_id']));

}
	
	
}

function opt_geocode_ip($ip_address='') {
	
	if($ip_address!='') {
	
	$data = array();

    $call = "http://freegeoip.net/json/".$ip_address;
    $handle = @fopen($call, "rb");
    $contents = @stream_get_contents($handle);
    @fclose($handle);
    $data[] = @json_decode($contents);
	
	foreach($data as $d) { return $d; }	
	
	}
}


?>