<?php
$gyunyu = "/www/sabachikubi/public_html/GYUNYU";

function gethtmlfile( $str ){
	$dir = opendir( $str );
	$fpath = "";
	$ftime = 0;
	while( $fname = readdir( $dir ) ){
		$stat = stat( "$str/$fname" );
		if( preg_match( "/.*\.html/", $fname ) == true ){
			if( $stat[ "mtime" ] > $ftime || $ftime == 0 ){
				$fpath = $fname;
				$ftime = $stat[ "mtime" ];
				break;
			}
		}
	}

	return $fpath;
}
/**/

require( "saba.lib" );
require( "counter.php" );

$fname = "referer.".date( "Y_m_d", time() ).".dat";
if( file_exists( "./cgi-bin/log/referer_dat/".$fname ) == false ){
	touch( "./cgi-bin/log/referer_dat/".$fname );
}

$fp = FALSE;
while( $fp == FALSE ){
	$fp = fopen( "./cgi-bin/log/referer_dat/".$fname, "a" );
}

flock( $fp, 2 );

$ref = getenv( "HTTP_REFERER" );
$host = getenv( "REMOTE_ADDR" );

$outstr = date( "Y年m月d日(D)Ah時i分", time() )."\t".$host."\t".$ref."\n";
fputs( $fp, $outstr );

flock( $fp, 3 );
fclose( $fp );

$today = time();
$ynum = ( int )( date( "Y", $today ) );
$mnum = ( int )( date( "n", $today ) );
$mtmp = $mnum;
for( $ytmp = $ynum; $ytmp > 1980; $ytmp-- ){
	while( 1 ){
		$fname = sprintf( "%s/%04d_%02d", $gyunyu, $ytmp, $mtmp );
		if( is_dir( $fname ) == true ){
			$gyunyu_fname = $fname."/".gethtmlfile( $fname );
			break 2;
		}
		$mtmp--;
		if( $mtmp == 0 ){
			$mtmp = 12;
			break;
		}
	}
}

$saba = file( "sabasabasaba.html" );
foreach( $saba as $line ){
	$line = rtrim( $line );
	$line = preg_replace( "/###counter###/", $numcnt, $line );
	if( preg_match( "/(.*)###twitter###(.*)/", $line, $match ) == true ){
		echo $match[ 1 ];
		require( "twitter.php" );
		echo $match[ 2 ];
	} else if( preg_match( "/(.*)###gyunyu###(.*)/", $line, $match ) == true ){
		echo $match[ 1 ];
		chdir( $fname );
		readfile( $gyunyu_fname );
		echo $match[ 2 ];
	} else {
		echo "$line\n";
	}
}
?>
