<?php
// 京

// webalizerdir = permission : 705 !
// webalizerのPathを指定
// <a href="ref.php?...">なリンクが貼られるので /public_html/ref.phpとかにおいて

$dir = '../webalizer/';

if ( ! is_dir($dir) ) {
	die('no valid dir');
}

// ファイル名を得る
$files = array();
$dh = opendir($dir);
while ( FALSE !== ($file = readdir($dh)) ) {

	if ( ! preg_match('/^usage_\d{4}\d{2}\.html$/', $file, $m) ) {
		continue;
	}

	array_push($files, $m[0]);

}
closedir($dh);

rsort($files, SORT_STRING);

// 表示設定
if ( empty($files) || ! is_array($files) ) {

		ob_start();
			header('HTTP/1.1 404');
				echo('no referer data');
			header('Content-Length: '.ob_get_length());
		ob_end_flush();
		exit();

}
elseif ( isset($_GET['year']) && is_numeric($_GET['year']) && isset($_GET['month']) && is_numeric($_GET['month']) ) {

	$filename = $dir. 'usage_'. $_GET['year']. $_GET['month']. '.html';

	if ( ! file_exists($filename) ) {
		ob_start();
			header('HTTP/1.1 404');
				echo('file not found');
			header('Content-Length: '.ob_get_length());
		ob_end_flush();
		exit();
	}

	ob_start();

		header('Content-Type: text/html; charset=Shift_JIS');
		header('Cache-Control: no-cache');
		header('Pragma: no-cache');

		if ( $buf = get_referers($filename) ) {
			echo $buf;
		}
		else {
			echo 'no referrer';
		}

		header('Content-Length: '.ob_get_length());

	ob_end_flush();

}
else {

	ob_start();

		header('Content-Type: text/html; charset=Shift_JIS');
		header('Cache-Control: no-cache');
		header('Pragma: no-cache');

			echo render_files($files);

		header('Content-Length: '.ob_get_length());

	ob_end_flush();

}

exit();




function render_files(&$files) {

	$html = <<<_EOF_
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>Monthly Referer</title>
</head>
<body>

<ul>
_EOF_;

	foreach( $files as $file ) {
		if ( preg_match('/usage_(\d{4})(\d{2})\.html$/', $file, $m) ) {
			$html .= '<li><a href="'.basename(__FILE__).'?year='.$m[1].'&amp;month='.$m[2].'">'.$m[1].'年'.$m[2].'月</a></li>'."\n";
		}
	}

	$html .= <<<_EOF_
</ul>
</body>
</html>

_EOF_;

	return $html;

}



function get_referers($filename) {

	if ( ! $lines = file($filename) ) {
		die($filename.'can\'t open');
	}

	if ( empty($lines) || ! is_array($lines) ) {
		return FALSE;
	}

	$html = <<<_EOF_
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>Monthly Referer</title>
</head>
<body>

<ol>

_EOF_;

	$flg = 0;
	$find = FALSE;
	foreach ( $lines as $line ) {

		if ( $flg === 1 && (FALSE !== strpos($line, '</TABLE>')) ) {
			$flg = 0;
			break;
		}
		if ( FALSE !== strpos($line, 'Total Referrers') ) {
			$flg = 1;
			continue;
		}
		if ( $flg === 1 ) {
			if ( preg_match('#<TD ALIGN=left NOWRAP><FONT SIZE="-1">(.+?)</FONT>#i', $line, $m) ) {
				$find = TRUE;
				$html .= '<li>'.$m[1].'</li>'."\n";
			}
		}

	}

	if ( $find === FALSE ) {
		$html .= '<li>no referer found</li>';
	}

	$html .= <<<_EOF_
</ol>
</body>
</html>

_EOF_;

	return $html;

}



?>
