<?php

function getJinBaseDir()
{
	$parts = explode('/', dirname(__FILE__));
	$numOfParts = count($parts);
	unset($parts[$numOfParts - 1]);
	unset($parts[$numOfParts - 2]);
		
	return join('/', $parts);
}

function onClick()
{
	if (!isset($_GET['url']))
		return;
	
	$ref = preg_replace_callback("|([%:\r\n])|i", "packURL", $_SERVER['HTTP_REFERER']);
	$file = sprintf("%s/%s-%d.stat", getJinBaseDir() . "/files/banner/banner{$_GET['id']}", date("YmdGis"), getmypid());
	$fd = fopen($file, 'w');
	fwrite($fd, "item_id:{$_GET['item_id']}\nreferer:$ref\nclicks:1\n");
	fclose($fd);
	
	$param = 'camp_id=banner' . $_GET['id'];
	$url = $_GET['url'];
	
	if (is_integer(strpos($url, 'camp_id=')))
		$url = preg_replace("/([?&])camp_id=.*?(?=&|#|\z)/", "\${1}$param", $url);
	else
		$url .= is_integer(strpos($url, '?')) ? "&$param" : "?$param";
	
	redirect($url);
	
	return;
}

function packURL($matches)
{
	return sprintf("%%%02X", ord($matches[1]));
}

function redirect($url)
{
	if(!headers_sent())
		header("Location: $url");
	else
	{
		echo "\n" . '<meta http-equiv="Refresh" content="0;url=' . $url . '">' . "\n" .
		'</head>' . "\n" .
		'<body>' . "\n" .
		'Enter here if your browser does not support redirecting <a href="$url">click here</a>.<br>' . "\n" .
		'</body>' . "\n" .
		'</html>' . "\n";
	} 
	
	return;
}

onClick();
	
?>