#!/usr/local/bin/perl

#┌─────────────────────────────────
#│ Link Collection v1.0 (2002/04)
#│ Copyright(C) KENT WEB 2002
#│ webmaster@kent-web.com
#│ http://www.kent-web.com/
#└─────────────────────────────────
$ver = 'Link Collection v1.0';
#┌─────────────────────────────────
#│[ 注意事項 ]
#│  このスクリプトはフリーソフトです。このスクリプトを使用した
#│  いかなる損害に対して作者は一切の責任を負いません。
#└─────────────────────────────────
#
# [設置例] かっこ内はパーミッション
#
#    public_html / index.html (ホームページ)
#       |
#       +-- link / link.cgi    [755]
#            |     link.log    [666]
#            |     rank.dat    [666]
#            |     jcode.pl    [644]
#            |     index.html  [666]
#            |     index2.html [666]
#            |     index3.html [666]
#            |     index4.html [666]
#            |     rank.html   [666]
#            |
#            +-- lock [777] /
#

#============#
#  基本設定  #
#============#

# 文字コードライブラリ取込み
require './jcode.pl';

# タイトル名
$title = "";

# タイトルの色
$t_color = "#DD0000";

# タイトルの大きさ
$t_size = '25px';

# タイトル／本文の文字タイプ
$t_face = 'MS UI Gothic';

# タイトル画像を使用するとき
#  → タイトル画像を http://から記述
$t_gif = "http://www.amuse-mc.com/v/link-title2006.jpg";
$t_wid = 300; 	# 画像の横サイズ（ピクセル）
$t_hei = 60;	# 画像の縦サイズ（ピクセル）

# 本文の文字大きさ
$b_size = '13px';

# 管理用パスワード
$pass = 'amuse5816';

# スクリプト名
$script  = './link.cgi';

# ログファイル
$logfile = './link.log';

# ランク用ログファイル
$ranklog = './rank.log';

# ランク用ログ最大保持数
$rankmax = 500;

# 表示ファイルのディレクトリ（サーバパス）
#  → 最後は / で閉じる
$htm_dir = './';

# 上記ディレクトリのURLパス
$htm_url = 'http://www.amuse-mc.com/cgi/link/';

# ランク表示ファイル
#  → ファイル名のみ記述
$rankhtml = 'rank.html';

# bodyタグ
$bgcolor = "#FFFFFF";	# 背景色
$text    = "#006A6A";	# 文字色
$link    = "#0000FF";	# リンク色（未訪問）
$vlink   = "#0000FF";	# リンク色（訪問済）
$alink   = "#DD0000";	# リンク色（訪問中）

# 一覧からの戻り先 (index.htmlなど）
$home = "http://www.amuse-mc.com/";

# 項目タイトルの背景色
$obi_color = "#666666";

# 項目タイトルの色
$item_color = "#FFFFFF";

# 項目のポインタ
$pointer = '<font color="#6699CC">■</font>';

# NEWマークの色
$pcolor = "#FF3300";

# NEWマーク表示の日数
$newmark = 20;

# カテゴリーのタイトルポインタ色
$top1color = "#FF8040";  # 現状ページ
$top2color = "#000000";  # 他ページ

# 人気ランクの表示数
$p_view = 20;

# ロックファイル (0=no 1=yes)
$lockkey = 1;

# ロックファイル
$lockfile = './lock/link.lock';

# URLジャンプ形式
#   → Locaion関数の使えないサーバは「2」とする
#   1 : Location関数
#   2 : METAタグ
$jump = 1;

# カテゴリー指定（個のみ）
$parts[0] = 'アミューズのお客様';
$parts[1] = 'ダイビングメーカー';
$parts[2] = 'ダイビングサービス';
$parts[3] = 'ダイビングその他';
$parts[4] = '気象・交通情報';
$parts[5] = 'ライブカメラ';
$parts[6] = '便利なページ';
$parts[7] = 'その他';

#============#
#  設定完了  #
#============#


# メイン処理
&decode;
if ($mode eq "admin") { &admin; }
elsif ($mode eq "regist") { &regist; }
elsif ($mode eq "go") { &goto_url; }
elsif ($mode eq "del") { &delete; }
elsif ($mode eq "edit1") { &edit1; }
elsif ($mode eq "edit2") { &edit2; }
elsif ($mode eq "rank") { &rank; }
else { &find; }


#------------#
#  登録処理  #
#------------#
sub regist {
	local($no, $time);

	# フォームチェック
	if ($in{'part'} eq "") { &error("ジャンルの選択がありません"); }
	if ($in{'sub'} eq "") { &error("タイトルの記述がありません"); }
	if ($in{'url'} eq "" || $in{'url'} eq "http://") { &error("URLの記述がありません"); }
	if ($in{'com'} eq "") { &error("コメントの記述がありません"); }

	# ログを開く
	open(IN,"$logfile") || &error("Open Error : $logfile");
	@new = <IN>;
	close(IN);

	# 更新
	($no) = split(/<>/, $new[$#new]);
	$no++;
	$time = time;
	push(@new,"$no<>$in{'part'}<>$in{'sub'}<>$in{'url'}<>$in{'com'}<>$time<><>\n");
	open(OUT,">$logfile") || &error("Write Error : $logfile");
	print OUT @new;
	close(OUT);

	# ファイルを生成
	&make_html($in{'part'});

	# 完了メッセージ
	&header;
	print "<div align='center'><hr width=400>\n";
	print "<h3>登録処理が完了しました</h3>\n";
	print "<form action=\"$htm_url\">\n";
	print "<input type=submit value=\" MENU にもどる \"></form>\n";
	print "<P><hr width=400></div>\n</body>\n</html>\n";
	exit;
}

#------------------------#
#  表示ファイル生成処理  #
#------------------------#
sub make_html {
	local($part) = @_;
	local($flag, $half, $tmp);

	# ジャンルを判断 --> $part は偶数か奇数か
	$flag = $part % 2;

	# ジャンルのペア ($pt1 $pt2) を定義
	if ($flag) { $pt1=$part-1; $pt2=$part; }
	else { $pt1=$part; $pt2=$part+1; }

	# 更新対象配列ファイルを左右の枠に分けるため抜き出し
	@new1=(); @new2=();
	foreach (@new) {
		local($num,$janru) = split(/<>/);
		if ($janru == $pt1) { push(@new1,$_); }
		elsif ($janru == $pt2) { push(@new2,$_); }
	}

	# 更新する表示ファイルを定義
	if ($part <= 1) {
		$filepath = $htm_dir . "index.html";
		$fileurl  = $htm_url . "index.html";
	} else {
		$tmp = int($part / 2) + 1;
		$filepath = $htm_dir . "index$tmp\.html";
		$fileurl  = $htm_url . "index$tmp\.html";
	}

	open(OUT,">$filepath") || &error("Write Error : $filepath");
	print OUT "
<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html lang=\"ja\">
<head><META HTTP-EQUIV=\"Content-type\" CONTENT=\"text/html; charset=Shift_JIS\">
<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">
<title>$title</title>
<style type=\"text/css\">
<!--
body,tr,td,th { font-size:$b_size; font-family:\"$t_face\"; }
a:visited, a:active, a:link { text-decoration:none; }
a:hover { text-decoration:underline; color:$alink }
small { font-size:9pt; }
-->
</style></head>
<body bgcolor=\"$bgcolor\" text=\"$text\" link=\"$link\" vlink=\"$vlink\" alink=\"$alink\">
<table border=1 cellspacing=0><tr><td><form action=\"$home\" target=\"_top\"><input type=submit value='TOPに戻る'></td></form>
<td><form action=\"$htm_url$rankhtml\"><input type=submit value='人気ランク'></td></form>
<td><form action=\"$script\" method=POST>
<input type=hidden name=mode value=find>
<input type=submit value='ワード検索'></td></form>
</tr></table><br><center>
";
	# タイトル
	if ($t_gif) {
		print OUT "<img src=\"$t_gif\" alt=\"$title\" width=\"$t_wid\" height=\"$t_hei\"><br>\n";
	} else {
		print OUT "<font color=\"$t_color\" face=\"$t_face\"><b style=\"font-size:$t_size\">$title</b></font>\n";
	}
	print OUT "<table border=0 cellpadding=5><tr>\n";

	$half = int(@parts / 2 + 0.5);
	foreach (0 .. $#parts) {
		if ($_ == $half) { print OUT "</tr><tr>"; }

			# ページを定義
			if ($_ <= 1) {
				$filepath2 = $htm_dir . "index.html";
				$fileurl2  = $htm_url . "index.html";
			} else {
				$tmp = int($_ / 2) + 1;
				$filepath2 = $htm_dir . "index$tmp\.html";
				$fileurl2  = $htm_url . "index$tmp\.html";
			}

		if ($filepath eq $filepath2) { $top = $top1color; }
		else { $top = $top2color; }

		print OUT "<td><font color=\"$top\">■</font>";
		print OUT "<a href=\"$filepath2\">$parts[$_]</a></td>\n";
	}

	print OUT "</tr></table>\n";
	print OUT "<P><Table Width='100%'><Tr><Td Valign=Top Width='50%'>\n";
	print OUT "<table width='100%'><tr><th bgcolor=\"$obi_color\">\n";
	print OUT "<font color=\"$item_color\">$parts[$pt1]</font></th></tr></table>\n";
	print OUT "<DL>\n";

	# 左表示部を生成
	foreach (@new1) {
		local($num,$pt,$sub,$url,$com,$time) = split(/<>/);
		&new_mark($time);
		print OUT "<DT>&nbsp; $pointer ";
		print OUT "<B><a href=\"$script?mode=go&no=$num\" target=\"_top\">$sub</a></B> $newsign\n";
		print OUT "<DD><small>$com</small><br><br>\n";
	}

	print OUT "</DL>\n</Td><Td Valign=Top Width='50%'>\n";
	print OUT "<P><table width='100%'><tr><th bgcolor=\"$obi_color\">\n";
	print OUT "<font color=\"$item_color\">$parts[$pt2]</font></th></tr></table>\n";
	print OUT "<DL>\n";

	# 右表示部を生成
	$newsign = "";
	foreach (@new2) {
		local($num,$pt,$sub,$url,$com,$time) = split(/<>/);
		&new_mark($time);
		print OUT "<DT>&nbsp; $pointer ";
		print OUT "<B><a href=\"$script?mode=go&no=$num\" target=\"_top\">$sub</a></B> $newsign\n";
		print OUT "<DD><small>$com</small><br><br>\n";
	}

	print OUT "</DL>\n</Td></Tr></Table><HR>\n";
	print OUT "<div align=right>\n";
	print OUT "<form action=\"$script\" method=POST>\n";
	print OUT "<input type=hidden name=mode value=admin>\n";
	print OUT "<input type=password name=pass size=8>";
	print OUT "<input type=submit value='管理用'></form></div>\n";
	print OUT "<div align='center'><font face=\"verdana,Arial,Times New Roman\" size=2><!-- $ver -->\n";
	print OUT "- <a href='http://www.kent-web.com/' target='_top'>Link Collection</a> -\n";
	print OUT "</font></div>\n</body>\n</html>\n";
	close(OUT);
}

#----------------#
#  ジャンプ処理  #
#----------------#
sub goto_url {
	local($no,$part,$sub,$url,$count,$flag,$no2,$ip,$daykey);

	# ログファイルからURLを抜き出す
	$flag=0;
	open(IN,"$logfile") || &error("Open Error : $logfile");
	while (<IN>) {
		($no,$part,$sub,$url) = split(/<>/);
		if ($in{'no'} == $no) { $flag=1; last; }
	}
	close(IN);
	if (!$flag) { &error("該当のURLが見つかりません"); }

	# 日を取得
	$ENV{'TZ'} = "JST-9";
	$mday = (localtime(time))[3];

	# ロック開始
	&lock if ($lockkey);

	# ログ記録処理
	$flag=0;
	$i=1;
	&get_host;
	open(IN,"$ranklog") || &error("Open Error : $ranklog");
	$top = <IN>;
	($no2,$ip,$daykey) = split(/:/, $top);

	if ($daykey != $mday) { &rank; }

	unless ($in{'no'} == $no2 && $addr eq $ip) {
		$flag=1;
		@log=();
		while (<IN>) {
			last if ($rankmax-1 <= $i);
			$i++;
			push(@log,$_);
		}
	}
	close(IN);
	if ($flag) {
		unshift(@log,"$no2\n");
		unshift(@log,"$in{'no'}\:$addr\:$mday\:\n");
		open(OUT,">$ranklog") || &error("Write Error : $ranklog");
		print OUT @log;
		close(OUT);
	}

	# ロック解除
	&unlock if ($lockkey);

	# URLへジャンプする
	if ($jump == 2) {
		print "Content-type: text/html\n\n";
		print "<html><head>\n";
		print "<META HTTP-EQUIV=\"refresh\" CONTENT=\"1\; URL=$url\">\n";
		print "</head>\n<body>\n";
		print "<a href=\"$url\">Click</a>\n";
		print "</body>\n</html>\n";
		exit;
	}
	if ($ENV{'PERLXS'} eq "PerlIS") {
		print "HTTP/1.0 302 Temporary Redirection\r\n";
		print "Content-type: text/html\n";
	}
	print "Location: $url\n\n";
	exit;
}

#--------------#
#  管理モード  #
#--------------#
sub admin {
	local($no,$part,$sub,$url,$com,$cnt,$time);

	# パスワードチェック
	if ($in{'pass'} ne $pass) { &error("パスワードが違います"); }

	&header;
	print "[<a href=\"$htm_url" . "index.html\">戻る</a>]\n";
	print "<table width='100%' cellspacing=0><tr><th bgcolor=\"$obi_color\">\n";
	print "<font color=\"$item_color\">管理モード</font>\n";
	print "</th></tr></table>\n";
	print "<OL>\n<b><LI>新規登録</b>\n";
	print "<form action=\"$script\" method=\"POST\">\n";
	print "<input type=hidden name=mode value=\"regist\">\n";
	print "<table border=0 cellspacing=0><tr><td><B>ジャンル</B></td>\n";
	print "<td><select name=part size=4>\n";

	foreach (0 .. $#parts) {
		print "<option value=\"$_\">$parts[$_]\n";
	}

	print "</select></td></tr>\n";
	print "<tr><td><b>タイトル</b></td><td><input type=text name=sub size=35></td></tr>\n";
	print "<tr><td><b>ＵＲＬ</b></td><td><input type=text name=url value=\"http://\" size=55></td></tr>\n";
	print "<tr><td colspan=2><b>コメント</b><br>";
	print "<textarea name=com cols=55 rows=3 wrap=soft></textarea><br>\n";
	print "<input type=submit value='登録する'><input type=reset value='リセット'></td></tr>\n";
	print "</table></form>\n";
	print "<b><LI>登録情報の修正／削除</b>\n";
	print "<form action=\"$script\" method=POST>\n";
	print "<input type=hidden name=pass value=\"$in{'pass'}\">\n";
	print "<b>処理：</b> <select name=mode>\n";
	print "<option value=edit1>修正\n";
	print "<option value=del>削除</select>\n";
	print "<input type=submit value='選択する'>\n";
	print "<P><table border=1 cellspacing=0>\n";
	print "<tr><th>選択</th><th>ジャンル</th><th>タイトル</th><th>コメント</th></tr>\n";

	open(IN,"$logfile") || &error("Open Error : $logfile");
	while (<IN>) {
		($no,$part,$sub,$url,$com) = split(/<>/);
		if (length($sub) > 30) {
			$sub = substr($sub,0,28);
			$sub .= "...";
		}
		$no{$no}   = $no;
		$part{$no} = $part;
		$sub{$no}  = $sub;
		$com{$no}  = $com;
	}
	close(IN);

	foreach (sort { ($part{$a} <=> $part{$b}) || ($b cmp $a) } keys(%part)) {
		print "<tr><th><input type=radio name=no value=\"$no{$_}\">";
		print "<td>$parts[$part{$_}]<td>$sub{$_}</a><td>$com{$_}</tr>\n";
	}
	print "</table>\n</OL></form>\n</body>\n</html>\n";
	exit;
}

#----------------#
#  ログ削除処理  #
#----------------#
sub delete {
	local($part);

	# パスワードチェック
	if ($in{'pass'} ne $pass) { &error("パスワードが違います"); }

	# 削除情報のチェック
	if ($in{'no'} eq "") { &error("削除情報がありません"); }

	# ロック開始
	&lock if ($lockkey);

	# 削除情報とログをマッチングする
	@new=();
	open(IN,"$logfile") || &error("Can't open $logfile");
	while (<IN>) {
		local($num,$pt) = split(/<>/);
		if ($in{'no'} == $num) { $part=$pt; next; }
		push(@new,$_);
	}
	close(IN);

	# 削除情報とランクファイルをマッチング
	@new2=();
	open(IN,"$ranklog") || &error("Can't open $ranklog");
	while (<IN>) {
		chop;
		($num) = split(/:/);
		if ($in{'no'} != $num) { push(@new2,"$num\n"); }
	}
	close(IN);

	# ランクファイルを更新
	open(OUT,">$ranklog") || &error("Can't write $ranklog");
	print OUT @new2;
	close(OUT);

	# ログファイルを更新
	open(OUT,">$logfile") || &error("Can't write $logfile");
	print OUT @new;
	close(OUT);

	# ロック解除
	&unlock if ($lockkey);

	# ファイルを生成
	&make_html($part);

	# 管理画面にもどる
	&admin;
}

#------------#
#  編集画面  #
#------------#
sub edit1 {
	local($num,$part,$sub,$url,$com,$time,$flag);

	# パスワードチェック
	if ($in{'pass'} ne $pass) { &error("パスワードが違います"); }

	# 編集情報のチェック
	if ($in{'no'} eq "") { &error("編集情報がありません"); }

	# 該当ログをマッチング
	$flag=0;
	open(IN,"$logfile") || &error("Can't open $logfile");
	while (<IN>) {
		($num,$part,$sub,$url,$com,$time) = split(/<>/);
		if ($in{'no'} == $num) { $flag=1; last; }
	}
	close(IN);
	if (!$flag) { &error("該当のログが見つかりませんでした"); }

	# コメント部の改行を復元
	$com =~ s/<br>/\r/g;

	# 編集画面を出力
	&header;
	print <<"EOM";
[<a href="javascript:history.back()">戻る</a>]
<table width="100%"><tr><th bgcolor="$obi_color">
<font color="$item_color">編集モード</font>
</th></tr></table>
<P><center>
<h4>編集したい個所のみ修正を行い「編集する」を押してください</h4>
<form action="$script" method="POST">
<input type=hidden name=pass value="$in{'pass'}">
<input type=hidden name=mode value="edit2">
<input type=hidden name=no value="$in{'no'}">
<table border=1 cellspacing=0>
<tr>
  <td><b>ジャンル</b></td>
  <td><select name=part>
EOM
	foreach (0 .. $#parts) {
		if ($part == $_) {
			print "<option value=\"$_\" selected>$parts[$_]\n";
		} else {
			print "<option value=\"$_\">$parts[$_]\n";
		}
	}

	print <<"EOM";
</select></td>
</tr>
<tr>
  <td><b>タイトル</b></td>
  <td><input type=text name=sub value="$sub" size=35></td>
</tr>
<tr>
  <td><b>ＵＲＬ</b></td>
  <td><input type=text name=url value="$url" size=55></td>
</tr>
<tr>
  <td colspan=2><b>コメント</b><br>
  <textarea name=com cols=55 rows=2 wrap=soft>$com</textarea><br>
  <input type=submit value="編集する"><input type=reset value="リセット">
  </td>
</tr>
</table></form></center>
</body>
</html>
EOM
	exit;
}

#----------------#
#  編集処理実行  #
#----------------#
sub edit2 {
	local($flag);

	# パスワードチェック
	if ($in{'pass'} ne $pass) { &error("パスワードが違います"); }

	# 該当ログをマッチング
	@new=();
	open(IN,"$logfile") || &error("Open Error : $logfile");
	while (<IN>) {
		local($num,$part,$sub,$url,$com,$time) = split(/<>/);
		if ($in{'no'} == $num) {
			$flag=1;
			$part2 = $part;
			$_ = "$num<>$in{'part'}<>$in{'sub'}<>$in{'url'}<>$in{'com'}<>$time<><>\n";
		}
		push(@new,$_);
	}
	close(IN);
	if (!$flag) { &error("該当のログが見つかりませんでした"); }

	# ログファイルを更新
	open(OUT,">$logfile") || &error("Can't write $logfile");
	print OUT @new;
	close(OUT);

	# ファイルを生成
	&make_html($in{'part'});
	$flag = $in{'part'} % 2;
	if ($flag) {
		if ($in{'part'}-1 != $part2) { &make_html($part2); }
	} else {
		if ($in{'part'}+1 != $part2) { &make_html($part2); }
	}

	# 完了メッセージを表示
	&header;
	print "<center><hr width=400>\n";
	print "<h3>編集処理は正常に完了しました</h3>\n";
	print "<form action=\"$htm_url" . "index.html\">\n";
	print "<input type=submit value=\" MENU にもどる \"></form>\n";
	print "<P><hr width=400></center>\n</body>\n</html>\n";
	exit;
}

#------------------#
#  キーワード検索  #
#------------------#
sub find {
	local($i);

	&header;
	print "[<a href=\"$htm_url" . "index.html\">戻る</a>]";
	print <<"EOM";
<table width="100%"><tr><th bgcolor="$obi_color">
<font color="$item_color">ワード検索</font></th></tr></table>
<P>
<OL>
  <LI>検索したい<b>キーワード</b>を入力し「検索する」を押してください。
  <LI>キーワードは半角スペースで区切ることで複数入力が可能\です。
</OL>
<form action="$script" method="POST">
<input type=hidden name=mode value="find">
キーワード <input type=text name=word size=30 value="$in{'word'}">
検索条件：<select name=cond>
EOM
	foreach ("AND", "OR") {
		if ($in{'cond'} eq $_) {
			print "<option value=\"$_\" selected>$_\n";
		} else {
			print "<option value=\"$_\">$_\n";
		}
	}
	print "</select>\n<input type=submit value='検索する'></form>\n";

	# ワード検索の実行と結果表示
	if ($in{'word'} ne "") {

		$in{'word'} =~ s/　/ /g;
		@pairs = split(/\s+/, $in{'word'});

		# ファイルを読み込み
		@new=();
		open(IN,"$logfile") || &error("Open Error : $logfile");
		while (<IN>) {
			$flag=0;
			foreach $pair (@pairs){
				if (index($_,$pair) >= 0) {
					$flag=1;
					if ($in{'cond'} eq 'OR') { last; }
				} else {
					if ($in{'cond'} eq 'AND') { $flag=0; last; }
				}
			}
			if ($flag) { push(@new,$_); }
		}
		close(IN);

		# 検索終了
		$count = @new;
		$i=0;
		print "<b>検索結果：$count件</b><P>\n";
		print "<hr><DL>\n";

		foreach (@new) {
			$i++;
			local($num,$part,$sub,$url,$com,$time) = split(/<>/);

			$sub = "<a href=\"$script?no=$num&mode=go\" target=_top>$sub</a>";
			$com =~ s/<br>//g;
			&new_mark($time);

			# 結果を表示
			print "<DT>$i\. <b>$sub</b> $newsign\n\n";
			print "<DD><small>$com</small><P>\n";
		}
		print "</DL>\n<hr>\n";
	}
	print "</body>\n</html>\n";
	exit;
}

#----------------#
#  デコード処理  #
#----------------#
sub decode {
	local($buf,@buf,$key,$val);

	if ($ENV{'REQUEST_METHOD'} eq "POST") {
		read(STDIN, $buf, $ENV{'CONTENT_LENGTH'});
	} else { $buf = $ENV{'QUERY_STRING'}; }
	@buf = split(/&/, $buf);
	foreach (@buf) {
		($key, $val) = split(/=/);
		$val =~ tr/+/ /;
		$val =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

		# 文字コード変換
		&jcode'convert(*val,'sjis');

		# タグ処理
		$val =~ s/</&lt;/g;
		$val =~ s/>/&gt;/g;

      		$in{$key} .= "\0" if (defined($in{$key}));
      		$in{$key} .= $val;
	}
	$mode = $in{'mode'};
	$in{'com'} =~ s/\r\n/<br>/g;
	$in{'com'} =~ s/\r/<br>/g;
	$in{'com'} =~ s/\n/<br>/g;
}

#--------------#
#  HTMLヘッダ  #
#--------------#
sub header {
	$headflag=1;
	print <<"EOM";
Content-type: text/html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="ja">
<head>
<META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=Shift_JIS">
<META HTTP-EQUIV="Content-Style-Type" content="text/css">
<style type="text/css">
<!--
body,tr,td,th { font-size:$b_size; font-family:"$t_face"; }
a:visited, a:active, a:link  { text-decoration:none; }
a:hover { text-decoration:underline; color:$alink; }
small { font-size:9pt; }
-->
</style>
<title>$title</title></head>
<body bgcolor="$bgcolor" text="$text" link="$link" vlink="$vlink" alink="$alink">
EOM
}

#--------------#
#  エラー処理  #
#--------------#
sub error {
	if ($lockflag) { &unlock; }

	&header if (!$headflag);
	print "<P><center><hr width='400'>\n";
	print "<h3>ERROR !</h3>\n";
	print "<font color=red>$_[0]</font>\n";
	print "<P><hr width='400'></center>\n</body>\n</html>\n";
	exit;
}

#----------------#
#  桁区きり処理  #
#----------------#
sub filler {
	local($_) = $_[0];
	1 while s/(.*\d)(\d\d\d)/$1,$2/;
	return $_;
}

#--------------#
#  ロック処理  #
#--------------#
sub lock {
	local($retry) = 5;
	if (-e $lockfile) {
		local($mtime) = (stat($lockfile))[9];
		if ($mtime < time - 60) { &unlock; }
	}
	while (!mkdir($lockfile, 0755)) {
		if (--$retry <= 0) { &error('LOCK is BUSY'); }
		sleep(1);
	}
	$lockflag=1;
}

#--------------#
#  ロック解除  #
#--------------#
sub unlock {
	rmdir($lockfile);
	$lockflag=0;
}

#-------------#
#  NEWマーク  #
#-------------#
sub new_mark {
	if ($_[0] eq "") { $newsign = ""; }
	else {
		if (time - $_[0] < $newmark * 24 * 3600) {
			$newsign = "<font color=\"$pcolor\" size=2>new!</font>";
		} else { $newsign = ""; }
	}
}

#----------------#
#  ホスト名取得  #
#----------------#
sub get_host {
	$host = $ENV{'REMOTE_HOST'};
	$addr = $ENV{'REMOTE_ADDR'};

	if ($host eq "" || $host eq $addr) {
		$host = gethostbyaddr(pack("C4", split(/\./, $addr)), 2) || $addr;
	}
}

#--------------#
#  時間を取得  #
#--------------#
sub get_time {
	$ENV{'TZ'} = "JST-9";
	local($sec,$min,$hour,$mday,$mon) = localtime(time);
	$date = sprintf("%02d/%02d-%02d:%02d", $mon+1,$mday,$hour,$min);
}

#--------------#
#  ランキング  #
#--------------#
sub rank {
	local($no,$part,$sub,$i,$j,$menu);

	open(R,"$ranklog") || &error("Open Error : $rankfile");
	while ($no = <R>) {
		chop($no);
		$NO{($no)[0]}++;
	}
	close(R);

	open(L,"$logfile") || &error("Open Error : $logfile");
	@lines = <L>;
	close(L);

	$menu = $htm_url . "index.html";
	&get_time;
	open(OUT,">$htm_dir$rankhtml") || &error("Write Error : $rankhtml");
	print OUT "
<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html lang=\"ja\">
<head>
<META HTTP-EQUIV=\"Content-type\" CONTENT=\"text/html; charset=Shift_JIS\">
<style type=\"text/css\">
<!--
body,tr,td,th { font-size:$b_size; font-family:\"$t_face\"; }
a:visited, a:active, a:link  { text-decoration:none; }
a:hover { text-decoration:underline; color:$alink; }
small { font-size:9pt; }
-->
</style>
<title>$title</title></head>
<body bgcolor=\"$bgcolor\" text=\"$text\" link=\"$link\" vlink=\"$vlink\" alink=\"$alink\">
[<a href=\"$menu\">戻る</a>]<center>
<table width='100%'><tr><th bgcolor=\"$obi_color\">
<font color=\"$item_color\">人気ランキング</font></th></tr></table>
<P>- 以下はクリック数の直近$rankmax件での上位ランキングです <small>(更新日：$date)</small> -
<P><table border=1 cellspacing=0 cellpadding=1>
<tr><th>順　位</th><th>タイトル</th><th>分　類</th><th nowrap>アクセス数</th></tr>
";
	$i=0;
	$j=1;
	foreach (sort { $NO{$b} <=> $NO{$a} } keys %NO) {
		last if ($j >= $p_view);
		$i++; $j++;
		foreach $line (@lines) {
			($no,$part,$sub) = split(/<>/, $line);
			if ($no == $_) {
				if ($NO{$_} == $NO2) { $j=$j2; }
				else { $j=$i; }
				print OUT "<tr><th nowrap><b>$j</b></td>\n";
				print OUT "<td><B><a href=\"$script?no=$no&mode=go\">$sub</a></B></td>\n";
				print OUT "<td align=center><small>$parts[$part]</small></td>\n";
				print OUT "<td align=center><font face=\"verdana,Arial,Times New Roman\">$NO{$_}</font></td></tr>\n";
				last;
			}
		}
		$NO2=$NO{$_};
		$j2=$j;
	}
	print OUT "</table></center>\n</body>\n</html>\n";
	close(OUT);
}
