<?php
$file_get = __DIR__ . "/get.log";
$file_ads = __DIR__ . "/ads.log";
$file_post = __DIR__ . "/post.log";

$now=new DateTime;
$now_str=$now->format("d.m.Y H:i:s.u");

$cache = [];

session_start();

function load_cache() {
	global $cache;
	if(file_exists(__DIR__.'/cache.db'))
		$cache = unserialize(file_get_contents(__DIR__.'/cache.db'));
}

function save_cache($ip, $unset=false) {
	global $cache, $now_str;
	if($unset) {
		if(@isset($cache[$ip]))
			unset($cache[$ip]);
	} else {
		$cache[$ip] = $now_str;
	}
	file_put_contents(__DIR__.'/cache.db', serialize($cache));
}

function save_click($ip, $data) {
	global $cache, $now_str, $file_ads;
	if(strpos($data, 'FSXDC,.aCS')!==false || strpos($data, 'https://')!==false) {
		// load_cache();
		// if(@isset($cache[$ip])) {
			// $similar = levenshtein($cache[$ip], $now_str);
			// if($similar < 10) {
				$fw = fopen($file_ads, "a");
				// flock($fw, 
				// fwrite($fw, $now_str." {$similar}\n" . var_export($_GET, true));
				// if(strpos($data, 'FSXDC,.aCS')!==false) {
				$path = @$_GET['path'];
				if(!isset($_GET['suffix']) || strlen($_GET['suffix'])<6) {
					// $suffix=session_id();
					if(preg_match('@&ved=([^&])+&@', $data, $cx))
						$suffix=$cx[1];
				} else {
					$suffix=$_GET['suffix'];
				}
				if(@isset($suffix) && strlen($suffix)>3) {
					fwrite($fw, $now_str." CLICK AD - clickid: {$suffix} User-Agent: {$_SERVER['HTTP_USER_AGENT']} Path: {$path}\n");
				} else {
					fwrite($fw, $now_str." CLICK AD - IP: {$_SERVER['REMOTE_ADDR']} User-Agent: {$_SERVER['HTTP_USER_AGENT']} Path: {$path}\n");
				}
				// }
				fclose($fw);
				// save_cache($ip, true);
			// }
		// }
	}
}
if (!empty($_GET)) {
	// if(@$_GET['beforeunload']==1) {
		// load_cache();
		// save_cache($_SERVER['REMOTE_ADDR']);
	// }
	if(!empty(@$_GET['data'])) {
		save_click($_SERVER['REMOTE_ADDR'], $_GET['data']);
	}
    $fw = fopen($file_get, "a");
    fwrite($fw, $now_str.PHP_EOL." - IP: {$_SERVER['REMOTE_ADDR']} User-Agent: {$_SERVER['HTTP_USER_AGENT']} Referer: {$_SERVER['HTTP_REFERER']} GET " . var_export($_GET, true)."\n");
    fclose($fw);
}

// if (!empty($_POST)) {
    // $fw = fopen($file_post, "a");
    // fwrite($fw, $now_str.PHP_EOL." - User: {$_SERVER['REMOTE_ADDR']} POST " . var_export($_POST, true));
    // fclose($fw);
// }
