<?php

	function get_client_ip() {
		$ipaddress = '';
		if (isset($_SERVER['HTTP_CLIENT_IP']))
			$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
		else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
			$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
		else if(isset($_SERVER['HTTP_X_FORWARDED']))
			$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
		else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
			$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
		else if(isset($_SERVER['HTTP_FORWARDED']))
			$ipaddress = $_SERVER['HTTP_FORWARDED'];
		else if(isset($_SERVER['REMOTE_ADDR']))
			$ipaddress = $_SERVER['REMOTE_ADDR'];
		else
			$ipaddress = 'UNKNOWN';
		return $ipaddress;
	}
	
	function _bot_detected() {
	  return (
		isset($_SERVER['HTTP_USER_AGENT'])
		&& preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])
	  );
	}

	$cookie_name = "AdsCustomerCode";	
	if( !isset($_COOKIE[$cookie_name]) && !_bot_detected() ) 
	{            
		// set cookie.
		$code = strtoupper(substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 4)), 0, 4));
		setcookie($cookie_name, $code, time() + (86400 * 30 * 3), "/");

		// db log.
		$ip = get_client_ip();
		$domain = "sextortion.co.uk";
		$url = $_SERVER["REQUEST_URI"];
		$referer = "";

		$utm_source = "";
		$utm_term = "";
		$utm_campaign = "";
		$gclid = "";
		
		$hostname = "localhost";	
		$username = "dfc_www";
		$password = "7ucBa7sjYUaR";
		$database = "visits";

		$mysqli = new mysqli($hostname, $username, $password, $database);
		if( !mysqli_connect_error() ) 
		{
		
			if( isset( $_GET["utm_source"] ) ) $utm_source = $mysqli->real_escape_string($_GET["utm_source"]);
			if( isset( $_GET["utm_term"] ) ) $utm_term = $mysqli->real_escape_string($_GET["utm_term"]);
			if( isset( $_GET["utm_campaign"] ) ) $utm_campaign = $mysqli->real_escape_string($_GET["utm_campaign"]);
			if( isset( $_GET["gclid"] ) ) $gclid = $mysqli->real_escape_string($_GET["gclid"]);
			if( isset( $_SERVER['HTTP_REFERER'] ) ){ $referer = $_SERVER['HTTP_REFERER']; }
			$user_agent = addslashes(strip_tags(trim($_SERVER['HTTP_USER_AGENT'])));
	
			$sql = "
				INSERT INTO 
					visits.ad_tracking 
				SET
					id='',
					ip='".$ip."',
					code='".$code."',
					utm_source='".$utm_source."',
					utm_term='".$utm_term."',
					utm_campaign='".$utm_campaign."',
					gclid='".$gclid."',
					domain='".$domain."',
					url='".$url."',
					referer='".$referer."',
					user_agent='".$user_agent."',
					sync='0',
					date_entered=NOW()
			";
			mysqli_query($mysqli, $sql);
		
		}
		$cookie_value = $code;
	} else {
		$cookie_value = $_COOKIE[$cookie_name];
        }
	
?>
