<?php

require '../app.inc.php';

# configure the stuff below

# your logfile
$todaylog = "/var/log/apache/drbeat.li/access.log";

# ignore the domains below (yours)
# do not add trailing slashes, must start with http://
# you can add as many as you like
# if your site is on a directory on a server, 
# example: http://something.edu/~username/,
# add the /~username to the ignore list

$ignore = array();
$ignore[] = "http://www.bolli.homeip.net";
$ignore[] = "http://bolli.homeip.net";
$ignore[] = "http://www.drbeat.li";

# end of config

function noquery($uri) {
    $parts = explode('?', $uri);
    return $parts[0];
}

$uri = $_GET['uri'];

# use HTTP referrer if it is present and no uri was given
if ($_SERVER['HTTP_REFERER'] !== null && $uri == null)
	$uri = $_SERVER['HTTP_REFERER'];

# lose any query arguments
$uri = noquery($uri);

$referrers = array();

error_reporting(1);

# escape $ignore array
for ($count = 0; $count < sizeof($ignore); ++$count) {
	$ignore[$count] = str_replace("/", "\/", $ignore[$count]);
	$ignore[$count] = '/^' . str_replace(".", "\.", $ignore[$count]) . '/';
}

# read the log file
if (!posix_access($todaylog, POSIX_R_OK))
    return;
$fd = fopen($todaylog, "r");
if (!$fd)
	return;
while ($x = fgets($fd, 1024)) {

	list( , , , , , , $log_uri, , , , $referrer, ) = explode(" ", $x);

	if ($uri !== null and $uri != $log_uri)
		continue;

	$referrer = substr($referrer, 1, -1);	// trim off quotes
	if ($referrer == '-')		// no empty referrers
		continue;
	foreach ($ignore as $toig)
		if (preg_match($toig, $referrer))
			continue 2;	// no ignored referrers
	$referrer = htmlentities($referrer);
	$referrers[] = "<a href=\"$referrer\" rel=\"nofollow\">$referrer</a>";
}
fclose($fd);

$counts = array_values(array_count_values($referrers));
$referrers = array_values(array_unique($referrers));

$app = new Application('Referrer log' . ($uri !== null ? " for $uri" : ''));

$app->head_add = "<meta name=\"robots\" content=\"noindex,nofollow\" />\n";
$app->header();

foreach($referrers as $i => $ref)
	print "$ref [{$counts[$i]}]<br />\n";

$app->footer(1);

?>