<?php

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

function onView()
{
	if (!isset($_GET['id']))
		return;
	
	$dir = getJinBaseDir() . "/files/banner/banner{$_GET['id']}";
	$file = $dir . '/items.php';
	
	if (!file_exists($file))
		return;
	
	include $file;
	
	# 0.00 - 100.00
	srand();
	$r = rand(0, 10000) / 100.0;
	$sum = 0;
	
	foreach ($items as $id => $item)
	{
		$sum += $item[2];
		
		if ($sum >= $r)
			break;
	}
		
	$clickURL = dirname("http://{$_SERVER['SERVER_NAME']}{$_SERVER['PHP_SELF']}") . '/click.php';
	$code = strlen($item[0]) ? "<img border=0 src=\"$item[0]\">" : $item[3];
	
	echo "
		var qs = 'id={$_GET['id']}&item_id=$id&url=$item[1]';
		
		if (document.location.search == '')
			qs = '?' + qs;
		else
			qs = document.location.search + '&' + qs;
		
		document.write('<a target=\"_blank\" style=\"text-decoration: none\" href=\"$clickURL' + qs + '\">$code</a>');
	";
	
	$ref = preg_replace_callback("|([%:\r\n])|i", "packURL", $_SERVER['HTTP_REFERER']);
	$file = sprintf("%s/%s-%d.stat", $dir, date("YmdGis"), getmypid());
	$fd = fopen($file, 'w');
	fwrite($fd, "item_id:$id\nreferer:$ref\nviews:1\n");
	fclose($fd);
	
	return;
}

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

onView();

?>
