#!/usr/bin/perl

#-- #!/usr/bin/perl --#


#┌─────────────────────────────────
#│ Sun Board v3.7 (2004/09/02)
#│ Copyright (c) KentWeb
#│ webmaster@kent-web.com
#│ http://www.kent-web.com/
#└─────────────────────────────────
$ver = 'Sun Board v3.7';
#┌─────────────────────────────────
#│ [注意事項]
#│ 1. このスクリプトはフリーソフトです。このスクリプトを使用した
#│    いかなる損害に対して作者は一切の責任を負いません。
#│ 2. 設置に関する質問はサポート掲示板にお願いいたします。
#│    直接メールによる質問は一切お受けいたしておりません。
#└─────────────────────────────────
#
# This file is "sunbbs1.cgi"
#
# [ ディレクトリツリー 2010.03.17 ]
#
#  earthquake_info/sunbbs/
#                   +-- index.html（トップページ）
#                   +-- index_bbs1.html
#                   +-- index_bbs2.html
#                   +-- index2_bbs1.html
#                   +-- index2_bbs2.html
#                   +-- index_sun1.html
#                   +-- index_sun2.html
#                   +-- menu.html
#                   +-- top1.html
#                   +-- top2.html
#                   +-- image/
#                   |      +-- tb-logo.gif 
#                   |      +-- title.gif 
#                   |      +-- Thumbs.db 
#                   +-- cgi/
#                         +-- sunbbs1.cgi
#                         +-- sunbbs2.cgi
#                         +-- sunbbslog1.cgi
#                         +-- sunbbslog2.cgi
#                         +-- jcode.pl      [604]
#                         +-- pastno.dat    [606] ... 過去ログ時
#                         +-- lock/
#                         +-- past/

#-------------------------------------------------
#  ▼設定項目
#-------------------------------------------------

# コード変換ライブラリ取込
require './jcode.pl';

# タイトル名

#-- 2005.09.14 編集 Start --#
#$title = "掲 示 板";
#-- 2005.09.14 編集 End --#

# タイトルの色
#-- 2005.09.14 編集 Start --#
#$t_color = "#D8D8D8";
$t_color = "#0000E0";
#-- 2005.09.14 編集 End --#

# タイトルのサイズ
#-- 2005.09.14 編集 Start --#
#$t_size = '24px';
$t_size = '16px';
#-- 2005.09.14 編集 End --#

# 本文の文字サイズ
#-- 2005.09.14 編集 Start --#
#$b_size = '13px';
$b_size = '15px';
#-- 2005.09.14 編集 End --#

# 壁紙 (http://から指定）
$bg = "";

# 背景色
$bc = "#FFFFFF";

# 文字色
$tx = "#000000";

# リンク色
#-- 2005.09.14 編集 Start --#
#$lk = "#8000FF";	# 未訪問
#$vl = "#FF80FF";	# 訪問済
#$al = "#CC0000";	# 訪問中
$lk = "#000000";	# 未訪問
$vl = "#000000";	# 訪問済
$al = "#000000";	# 訪問中
#-- 2005.09.14 編集 End --#

# 管理用パスワード(英数字)
#-- 2005.09.14 編集 Start --#
#$pass = '0123';
$pass = 'saigai';
#-- 2005.09.14 編集 End --#

# 戻り先 (index.htmlなど)
#-- 2005.09.14 編集 Start --#
#$home = "../index.html";
$home = "./index_bbs1.html";
#-- 2005.09.14 編集 End --#

# 記事の最大保持数
$max = 40;

# 表示ファイル第1ページの記事数
#-- 2005.09.14 編集 Start 20(Default)→10 --#
#-- 2010.03.17 編集 Start 10→20(Default) --#
$pagelog = 20;
#$pagelog = 10;
#-- 2010.03.17 編集 End --#
#-- 2005.09.14 編集 End --#

# 自動リンク (0=no 1=yes)
$autolink = 1;

# CGIスクリプト自身をURLで指定
#-- 2005.09.14 編集 Start --#
#$script = 'http://www.xxx.xxx/sunbbs/sunbbs.cgi';
$script = '/earthquake_info/sunbbs/cgi/sunbbs1.cgi';
#-- 2005.09.14 編集 End --#

# 表示ファイル(index.html)のあるディレクトリをURLで指定
#  → 最後は / で閉じる
#-- 2005.09.14 編集 Start --#
#$htm_url = 'http://www.xxx.xxx/xxx/sunbbs/';
$htm_url = '/earthquake_info/sunbbs/';
#-- 2005.09.14 編集 End --#

# 表示ファイル(index.html)のあるディレクトリをサーバパスで指定
#  → 最後は / で閉じる
#  → フルパスなら / から始まるパス（http://からではない）
#-- 2006.03.03 編集 Start --#
$htm_dir = '../';
#-- 2006.03.03 編集 End --#

# 新着情報ボードモード (0=no 1=yes)
#  → 書き込みは管理者限定となります
#-- 2005.09.14 編集 Start --#
#$whatsnew = 0;
$whatsnew = 1;
#-- 2005.09.14 編集 End --#

# 題名部の色
$obi_color = "#B22222";

# 題名部ポインタ
$point  = '■';

# 戻り先部ポインタ
$point2 = '■';

# ポインタの色
$p_color = "#FFCC33";

# 題名の色
$s_color = "#FFFFFF";

# タイトルGIF画像 (http://から記述)
$t_gif = "";

# タイトル画像の大きさ
$tg_w = 250;	# 横幅
$tg_h = 54;	# 高さ

# ログファイル名
#  → フルパスなら / から記述（http://からではない）
$logfile = './sunbbslog1.cgi';

# 表示ファイルHTML (第1ページ)
#  → ファイル名のみを記述
#-- 2005.09.14 編集 Start --#
#$htmfile = "index.html";
$htmfile = "index_bbs1.html";
#-- 2005.09.14 編集 End --#

# 表示ファイルHTML (第2ページ)
#  → ファイル名のみを記述
#-- 2005.09.14 編集 Start --#
#-- 2010.03.17 編集 Start index2.html→index2_bbs1.html --#
$nexthtm = "index2_bbs1.html";
#-- 2010.03.17 編集 End --#
#-- 2005.09.14 編集 End --#

# ロックファイル処理
#   0 : なし
#   1 : あり（symlink関数）
#   2 : あり（mkdir関数）
$lockkey = 0;

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

# ブラウザのキャッシュ取込を拒否 (0=no 1=yes)
$nocashe = 1;

# 投稿後に内容確認画面を表示 (0=no 1=yes)
$msg_check = 1;

# 投稿があるとメール通知する (0=no 1=yes)
$mailing = 0;

# メールアドレス(メール通知する時)
$mailto = 'xxx@xxx.xxx';

# sendmailパス（メール通知する時）
#-- 2005.09.14 編集 Start --#
#$sendmail = '/usr/lib/sendmail';
#-- 2005.09.14 編集 End --#

## --- 管理者コメント（タイトル下部にちょっとしたコメントを表示できます）
#-- 2005.09.14 編集 Start --#
#$message = <<"END_OF_MSG";
#私のホームページはいかがでしたか？
#お気軽にメッセージをお書きください。
#END_OF_MSG
#-- 2005.09.14 編集 End --#

# ホスト取得方法
# 0 : gethostbyaddr関数を使わない
# 1 : gethostbyaddr関数を使う
$gethostbyaddr = 0;

# 投稿アクセス制限（半角スペースで区切る）
#  → 拒否するホスト名又はIPアドレスを記述（アスタリスク可）
#  → 記述例 $deny = '*.anonymizer.com 211.154.120.*';
$deny = '';

#---(以下は「過去ログ」機能を使用する場合の設定です)---#
#
# 過去ログ生成 (0=no 1=yes)
$pastkey = 0;

# 過去ログ用NOファイル
$nofile  = './pastno.dat';

# 過去ログのディレクトリ
# → フルパスなら / から記述（http://からではない）
# → 最後は必ず / で閉じる
$pastdir = './past/';

# 過去ログ１ファイルの行数
# → この行数を超えると次ページを自動生成します
#-- 2005.09.14 編集 Start 300(Default)→50 --#
#-- 2010.03.17 編集 Start 50→300(Default) --#
$log_line = 300;
#-- 2010.03.17 編集 End --#
#-- 2005.09.14 編集 End --#

## サニタイジングライブラリ
require './sanitize.pl';

#-------------------------------------------------
#  ▲設定完了
#-------------------------------------------------

&decode;
if ($mode eq 'regist') { &regist; }
elsif ($mode eq 'form') { &form; }
elsif ($mode eq 'find') { &find; }
elsif ($mode eq 'admin') { &admin; }
elsif ($mode eq 'mente') { &mente; }
elsif ($mode eq 'edit') { &edit; }
elsif ($mode eq 'userdel') { &userdel; }
elsif ($mode eq "past" && $pastkey) { &past; }
elsif ($mode eq "check") { &check; }
&location;

#-------------------------------------------------
#  アクセス制限
#-------------------------------------------------
sub axscheck {
	# アクセスチェック
	local($flag)=0;
	foreach ( split(/\s+/, $deny) ) {
		s/\./\\\./g;
		s/\*/\.\*/g;
		s/\?/\.\?/g;
		if ($host =~ /$_/i || $addr =~ /$_/i) { $flag=1; last; }
	}
	if ($flag) { &error("アクセスを許可されていません"); }
}

#-------------------------------------------------
#  投稿フォーム
#-------------------------------------------------
sub form {
	local($res_sub,$res_com,$date,$next,$back,$last,$i,$cnam,$ceml,$curl,$cpwd);

	# ホスト名チェック
	if (!$whatsnew) {
		&get_host;
		&axscheck;
	}

	print &header;
	print "[<a href=\"javascript:history.back()\">［戻る］</a>]\n";
	print "<blockquote><form action=\"@{[&sanitize::ez_sanitize($script)]}\" method=\"POST\">\n";
	print "<input type=hidden name=mode value=\"regist\">\n";
	print "<input type=hidden name=pass value=\"$in{'pass'}\">\n";

	# 掲示板モードのとき
	if (!$whatsnew) {

	  	($cnam,$ceml,$curl,$cpwd) = &get_cookie;
		$curl ||= 'http://';

	  	## 返信の場合
	  	if ($in{'no'}) {
			local($num,$date,$name,$email,$sub,$com);

			# ログを開く
			open(IN,"$logfile") || &error("Can't open $logfile");
			while (<IN>) {
				($num,$date,$name,$email,$sub,$com) = split(/<>/);
				if ($in{'no'} == $num) { last; }
			}
			close(IN);

			# 返信用項目を作成
			if ($sub =~ /^Re/) {
				$sub =~ s/Re//;
				$res_sub = "Re\[$num\]" . "$sub";
			} else {
				$res_sub = "Re\[$num\]\: $sub";
			}
			$res_com = "&gt; $com";
			$res_com =~ s/<br>/\r&gt; /ig;
	  	}
	  	print "<table><tr><td><b>おなまえ</b></td>";
	  	print "<td><input type=text name=name size=27 value=\"@{[&sanitize::ez_sanitize($cnam)]}\"></td></tr>\n";
	  	print "<tr><td><b>Ｅメール</b></td>";
	  	print "<td><input type=text name=email size=27 value=\"@{[&sanitize::ez_sanitize($ceml)]}\"></td></tr>\n";

	# 新着ボードモードのとき
	} else {
		# 認証
		if ($in{'pass'} ne $pass) { &error("［パスワードが違います］"); }

		$date = &get_time;
	    	print "▼［以下のフォームから記事を投稿して下さい。］<br>\n";
		print "<font color = red>このページは社外からも閲覧できます。守秘義務情報等の記入はご注意下さい。</font>\n";
#-- 2005.09.14 編集 Start --#
#	    	print "<P><table><tr><td nowrap><b>日　時</b>\n";
#	    	print "<td><input type=text name=date value=\"$date\" size=30>\n";
	    	print "<input type=hidden name=date value=\"@{[&sanitize::ez_sanitize($date)]}\">\n";
	}
#	print "<tr><td><b>タイトル</b></td>";
	print "<table><tr><td><b>タイトル</b></td>";
#-- 2005.09.14 編集 Start --#
	print "<td><input type=text name=sub size=35 value=\"$res_sub\"> ";
	print "<input type=submit value='投稿する'><input type=reset value='リセット'></td></tr>\n";
	print "<tr><td colspan=2><b>コメント</b><br>";
	print "<textarea name=comment cols=60 rows=7 wrap=soft>$res_com</textarea></td></tr>\n";
#-- 2005.09.14 編集 Start --#
#	print "<tr><td><b>ＵＲＬ</b>";
#	print "<td><input type=text name=url size=50 value=\"$curl\"></td></tr>\n";
#-- 2005.09.14 編集 End --#

	if (!$whatsnew) {
	  	print "<tr><td><b>削除キー</b></td>";
	  	print "<td><input type=password name=pwd size=8 maxlength=8 value=\"@{[&sanitize::ez_sanitize($cpwd)]}\"> ";
	  	print "(記事を削除時に使用。英数字で8文字以内)</td></tr>\n";
	} else {
		print "<tr><td><b>タグ有効</b></td>";
		print "<td><input type=checkbox name=tag value=1> ";
		print "（コメント内でタグを有効にする場合はチェック）</td></tr>\n";
	}

	print "</table></form></blockquote><hr>\n";
	if ($in{'page'} == 2) {
		$next = $pagelog+1;
		$last = $max;
	} else {
		$next = 0;
		$last = $pagelog;
  }

  $i=0;
  open(IN,"$logfile") || &error("Open Error: $logfile");
  while (<IN>) {
    $i++;
    if ($i < $next) { next; }
    if ($i > $last) { last; }
    print &log_view($_, $in{'page'});
  }
  close(IN);

  print "</body>\n</html>\n";
  exit;
}

#-------------------------------------------------
#  投稿処理
#-------------------------------------------------
sub regist {
  local($no,$date,$log,$pw,@lines);

  # ホスト名取得
  &get_host;

  # チェック
  if ($whatsnew) {
    if ($in{'pass'} ne $pass) { &error("［パスワードが違います］"); }
  } else {
    # ホスト名チェック
    &axscheck;
    if ($in{'name'} eq "") { &error("［なまえの記入がありません］"); }
  }
  if ($in{'comment'} eq "") { &error("［コメントに記入がありません］"); }
  if ($in{'url'} eq "http://") { $in{'url'} = ''; }

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

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

  # 二重投稿の禁止
  local($num,$name,$com) = (split(/<>/, $lines[0]))[0,2,5];
  &error("[二重投稿は禁止です]") if ($in{'name'} eq $name && $in{'comment'} eq $com);

  # 記事Noカウント
  $no = $num + 1;

  # 削除キーを暗号化
  if ($in{'pwd'} ne "") { $pw = &encrypt($in{'pwd'}); }

  # 日付処理、タグ有効キー
  if ($whatsnew) { $date = $in{'date'}; }
  else { $date = &get_time; $in{'tag'}=0; }

  # ログを更新
  while ($max <= @lines) {
    $log = pop(@lines);
    unshift(@data,$log) if ($pastkey);
  }
  &pastlog if ($pastkey);
  unshift (@lines,"$no<>$date<>$in{'name'}<>$in{'email'}<>$in{'sub'}<>$in{'comment'}<>$in{'url'}<>$host<>$pw<>$in{'tag'}<>\n");
  open(OUT,">$logfile") || &error("Write Error: $logfile");
  print OUT @lines;
  close(OUT);

  # HTMLファイルを生成
  &html_regist("$htm_dir$htmfile","1");
  &html_regist("$htm_dir$nexthtm","2") if ($pagelog < @lines);

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

  # クッキー発行
  if (!$whatsnew) { &set_cookie($in{'name'},$in{'email'},$in{'url'},$in{'pwd'}); }

  # メール通知処理
  if ($mailing && $in{'email'} ne $mailto) { &mail_to; }

  # HTMLファイルへ戻る
  &location;
  exit;
}

#-------------------------------------------------
#  HTML生成処理
#-------------------------------------------------
sub html_regist {
  local($i,$next,$back,$data);
  local($file,$page) = @_;

  open(WR,">$file") || &error("Write Error: $file");
  print WR &header('HTML');

#-- 2005.09.14 編集 Start --#
  # タイトル部
#  if ($t_gif eq '') {
#      print WR "<div align=center>\n<font color=\"$t_color\"><b style=\"font-size:$t_size\">$title</b></font>\n";
#  } else {
#      print WR "<img src=\"$t_gif\" width=$tg_w height=$tg_h alt=\"$title\">\n";
#  }
#-- 2005.09.14 編集 End --#

  # リンク部
#-- 2005.09.14 編集 Start --#
#  print WR "<br><br><B><font color=\"$p_color\">$point2</font>";
#  print WR "<a href=\"$home\" target=\"_top\">Home</a>\n";
#  print WR "<a href=\"$home\">[トップページへ戻る]</a>\n";
#-- 2005.09.14 編集 End --#

  if (!$whatsnew) {
#-- 2005.09.16 編集 Start --#
#    print WR "<font color=\"$p_color\">$point</font>";
#    print WR "<a href=\"$script?mode=form\">Post</a>\n";
#    print WR "<div align=center><a href=\"$htmfile\">[投稿する]</a>\n";
#-- 2005.09.16 編集 End --#
  }

#-- 2005.09.16 編集 Start --#
#  print WR "<font color=\"$p_color\">$point</font>";
#-- 2005.09.14 編集 Start --#
#  print WR "<font color=\"$p_color\">$point</font>";
  print WR "<div align=center><font color=\"$p_color\">$point</font>";
#-- 2005.09.14 編集 Start --#
#  print WR "<a href=\"$script?mode=find\">Search</a>\n";
#  print WR "<a href=\"$script?mode=find\">[検索する]</a>\n";
  print WR "<a href=\"$script?mode=find\">［検索］</a>\n";
#-- 2005.09.164 編集 End --#

  # 過去ログ
  if ($pastkey) {
    print WR "<font color=\"$p_color\">$point</font>";
#-- 2005.09.14 編集 Start --#
#    print WR "<a href=\"$script?mode=past\">Log</a>\n";
    print WR "<a href=\"$script?mode=past\">［ログ］</a>\n";
#-- 2005.09.14 編集 End --#
  }

  print WR "<font color=\"$p_color\">$point</font>";
#-- 2005.09.14 編集 Start --#
#  print WR "<a href=\"$script?mode=admin\">Admin</a></B>\n<div align=center>\n";
  print WR "<a href=\"$script?mode=admin\">［管理者メニュー］</a></B><br><br></div>\n";

#-- 2005.09.14 編集 End --#

  # タイトル部
#-- 2005.09.14 編集 Start --#
#  if ($t_gif eq '') {
#      print WR "<font color=\"$t_color\" size=6><b style=\"font-size:$t_size\">$title</b></font>\n";
#  } else {
#      print WR "<img src=\"$t_gif\" width=$tg_w height=$tg_h alt=\"$title\">\n";
#  }
#-- 2005.09.14 編集 End --#

  # ひとことメッセージを表示
#-- 2005.09.14 編集 Start --#
#  $message =~ s/\r\n/<br>/g;
#  $message =~ s/\r/<br>/g;
#  $message =~ s/\n/<br>/g;

#  print WR "<P>$message</div><hr>\n";
#-- 2005.09.14 編集 End --#

  # 記事を展開
  if ($page == 2) {
    $next = $pagelog+1;
    $last = $max;
  } else {
    $next = 0;
    $last = $pagelog;
  }
  $i=0;
  open(IN,"$logfile") || &error("Open Error: $logfile");
  while ($data = <IN>) {
    $i++;
    if ($i < $next) { next; }
    if ($i > $last) { last; }
    print WR &log_view($data, $page);
  }
  close(IN);
  if (!$whatsnew) { print WR "<table align=left><tr>\n"; }

  # 次／前ページのリンクを生成
  if (@lines > $pagelog && $page == 1) {
      print WR "<td><form action=\"$htm_url$nexthtm\">";
      print WR "<input type=submit value=\"次ページ\"></td></form>\n";
  } elsif (@lines > $pagelog && $page == 2) {
      print WR "<td><form action=\"$htm_url$htmfile\">";
      print WR "<input type=submit value=\"前ページ\"></Td></form>\n";
  }
  print WR "</table>\n";

  # 削除フォーム
  if (!$whatsnew) {
      print WR "<table align=right><tr><td>\n";
      print WR "<form action=\"$script\" method=\"POST\">\n";
      print WR "記事No <input type=text name=no size=4>\n";
      print WR "削除キー <input type=password name=pwd size=4>\n";
      print WR "<input type=hidden name=mode value=userdel>\n";
      print WR "<input type=submit value='［記事削除］'></td></form></table><br clear=all>\n";
  }

  # 著作権を表示（削除不可）
  print WR "<div align=center style='font-size:10px;font-family:Verdana,Helvetica,Arial'><!-- $ver -->\n";
  print WR "- <a href='http://www.kent-web.com/' target='_top'>SunBoard</a> -\n";
  print WR "</div>\n</body>\n</html>\n";
  close(WR);
}


#-------------------------------------------------
#  表示部戻り
#-------------------------------------------------
sub location {
  # 投稿確認画面の表示
  if ($msg_check) {
    print &header;
    print "<br><br><div align=center>\n";
    print "<h3>［処理は正常に完了しました］</h3>\n";
    print "<form action=\"@{[&sanitize::ez_sanitize($htm_url.$htmfile)]}\">\n";
    print "<input type=submit value='［閲覧画面へ戻る］'></form>\n";
    print "</div>\n</body>\n</html>\n";
    exit;
  }

  # IISサーバ対応
  if ($ENV{PERLXS} eq "PerlIS") {
    print "HTTP/1.0 302 Temporary Redirection\r\n";
    print "Content-type: text/html\n";
  }
  print "Location: @{[&sanitize::ez_sanitize($htm_url.$htmfile)]}\n\n";
}

#-------------------------------------------------
#  管理用初期画面
#-------------------------------------------------
sub admin {
  # ログイン画面
  if ($in{'pass'} eq '') {
    print &header;
    print "<table width='100%'><tr><th bgcolor=\"@{[&sanitize::ez_sanitize($obi_color)]}\">\n";
    print "<font color=\"@{[&sanitize::ez_sanitize($s_color)]}\">［入室画面］</font></table>\n";
    print "<div align=center><h4>［管理用パスワードを入力して下さい］</h4>\n";
    print "<form action=\"@{[&sanitize::ez_sanitize($script)]}\" method=\"POST\">\n";
    if ($whatsnew) {
        print "<input type=radio name=mode value=form checked>［書込］\n";
        print "<input type=radio name=mode value=admin>［ログ］<P>\n";
    } else {
        print "<input type=hidden name=mode value=admin>\n";
    }
    print "<input type=password name=pass size=8>\n";
    print "<input type=submit value=' 認証 '></form>\n";
    
    print "<BR><BR><BR><font color=\"FF0000\" size=\"+1\"><B>このページは社外からも閲覧できます。</B></font>\n";
    print "<BR><font color=\"FF0000\" size=\"+1\"><B>守秘義務情報等の記入はご注意下さい。</B></font>\n";
    print "</div>\n";
    print "</body>\n</html>\n";
    exit;

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

  # 修正
  if ($in{'ope'} eq 'mente' && $in{'no'}) {

    &mente;

  # 削除
  } elsif ($in{'ope'} eq 'del' && $in{'no'}) {

    local($i,$i2,$no,@lines);

    if ($lockkey) { &lock; }

    @lines=();
    $i=0;
    open(IN,"$logfile") || &error("Open Error: $logfile");
    while (<IN>) {
      $i++;
      ($no) = split(/<>/);
      if ($in{'no'} == $no) { $i2=$i; next; }
      push(@lines,$_);
    }
    close(IN);

    open(OUT,">$logfile") || &error("Write Error: $logfile");
    print OUT @lines;
    close(OUT);

    if ($i2 > $pagelog) { &html_regist($nexthtm, 2); }
    elsif ($i2 <= $pagelog) {
      &html_regist("$htm_dir$htmfile", 1);
      &html_regist("$htm_dir$nexthtm", 2) if ($pagelog < @lines);
    }

    if ($lockkey) { &unlock; }
  }

  # 管理画面
  print &header;
  print <<"EOM";
[<a href="@{[&sanitize::ez_sanitize($htm_url.$htmfile)]}">［戻る］</a>]
<table width="100%"><tr><th bgcolor="@{[&sanitize::ez_sanitize($obi_color)]}">
<font color="@{[&sanitize::ez_sanitize($s_color)]}">［管理画面］</font></table>
<form action="@{[&sanitize::ez_sanitize($script)]}" method="POST">
<input type=hidden name=mode value="admin">
<input type=hidden name=pass value="$in{'pass'}">
<select name=ope>
<option value=mente>［修正］
<option value=del>［削除］</select>
<input type=submit value=" 選択する ">
<dl>
EOM

  local($no,$date,$name,$email,$sub,$com,$url,$host);

  # ログ表示
  open(IN,"$logfile") || &error("Open Error: $logfile");
  while (<IN>) {
    ($no,$date,$name,$email,$sub,$com,$url,$host) = split(/<>/);
    $name = "<a href=\"mailto:$email\">$name</a>" if ($email);
    $com =~ s/<br>//g; $com =~ s/</&lt;/g; $com =~ s/>/&gt;/g;
    if (length($com) > 60) { $com=substr($com,0,58); $com .= "..."; }

    print "<dt><hr><input type=radio name=no value=\"@{[&sanitize::ez_sanitize($no)]}\">\n";
    print "[<b>@{[&sanitize::ez_sanitize($no)]}</b>] <b>$sub</b> - $name\n";
    print "<dd>@{[&sanitize::ez_sanitize($date)]} (@{[&sanitize::ez_sanitize($host)]})\n<dd>$com\n";
  }
  close(IN);

  print <<'EOM';
<dt><hr>
</dl>
</form>
</body>
</html>
EOM
  exit;
}

#-------------------------------------------------
#  記事編集
#-------------------------------------------------
sub mente {
  if ($in{'num'}) {

    local($no,$date,$name,$email,$sub,$com,$url,$host,$pwd,$tag,$i,$i2,@lines);

    if ($lockkey) { &lock; }

    # タグキー
    if (!$whatsnew) { $in{'tag'}=0; }

    @lines=();
    $i=0;
    open(IN,"$logfile") || &error("Open Error: $logfile");
    while (<IN>) {
      $i++;
      ($no,$date,$name,$email,$sub,$com,$url,$host,$pwd,$tag) = split(/<>/);
      if ($in{'num'} == $no) {
        $i2=$i;
        $_ = "$no<>$date<>$in{'name'}<>$in{'email'}<>$in{'sub'}<>$in{'comment'}<>$in{'url'}<>$host<>$pwd<>$in{'tag'}<>\n";
      }
      push(@lines,$_);
    }
    close(IN);
    open(OUT,">$logfile") || &error("Write Error: $logfile");
    print OUT @lines;
    close(OUT);

    if ($i2 <= $pagelog) { &html_regist("$htm_dir$htmfile", 1); }
    elsif ($i2 > $pagelog) { &html_regist("$htm_dir$nexthtm", 2); }

    if ($lockkey) { &unlock; }

    &admin;
  }

  print &header;
  print <<"EOM";
[<a href="@{[&sanitize::ez_sanitize($htm_url.$htmfile)]}">［戻る］</a>]
<table width="100%"><tr><th bgcolor="@{[&sanitize::ez_sanitize($obi_color)]}">
<font color="@{[&sanitize::ez_sanitize($s_color)]}">［管理画面］</font></table>
<form action="@{[&sanitize::ez_sanitize($script)]}" method="POST">
<input type=hidden name=pass value="$in{'pass'}">
<input type=hidden name=mode value="mente">
<input type=hidden name=num value="$in{'no'}">
<table>
EOM

  local($no,$date,$name,$email,$sub,$com,$url,$ho,$pw,$tag);

  # ログ展開
  open(IN,"$logfile") || &error("Open Error: $logfile");
  while (<IN>) {
    ($no,$date,$name,$email,$sub,$com,$url,$ho,$pw,$tag) = split(/<>/);
    last if ($in{'no'} == $no);
  }
  close(IN);

  $com =~ s/<br>/\r/g;

  if (!$whatsnew) {
      print "<tr><td><b>おなまえ</b></td>";
      print "<td><input type=text name=name size=25 value=\"$name\"></td></tr>\n";
      print "<tr><td><b>E-mail</b></td>";
      print "<td><input type=text name=email size=25 value=\"$email\"></td></tr>\n";
  }
  print "<tr><td><b>[タイトル]</b></td>";
  print "<td><input type=text name=sub size=35 value=\"$sub\">\n";
  print "<input type=submit value='編集する'>";
  print "<input type=reset value='リセット'></td></tr>\n";
  print "<tr><td colspan=2><b>コメント</b><br>\n";
  print "<textarea name=comment cols=55 rows=6 wrap=soft>$com</textarea></td></tr>\n";
#-- 2005.09.14 編集 Start --#
#  print "<tr><td nowrap><b>URL</b>";
#  print "<td><input type=text name=url size=60 value=\"$url\"></td></tr>\n";
#-- 2005.09.14 編集 End --#
  if ($whatsnew) {
    if ($tag == 1) { $chk="checked"; } else { $chk=""; }
    print "<tr><td><b>タグ有効</b></td>";
    print "<td><input type=checkbox name=tag value=1 @{[&sanitize::ez_sanitize($chk)]}> ";
    print "（コメント内でタグを有効にする場合はチェック）</td></tr>\n";
  }
  print "</table></form>\n</body>\n</html>\n";
  exit;
}

#-------------------------------------------------
#  記事削除処理
#-------------------------------------------------
sub userdel {
  local($num,$date,$name,$email,$sub,$com,$url,$host,$pwd,$i,$flag,$check,$pwd2,@lines);

  # フォームチェック
  if ($in{'no'} eq "") { &error("［記事NOが入力されていません］"); }
  if ($in{'pwd'} eq "") { &error("［削除キーが入力されていません］"); }

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

  # ログファイルを開く
  @lines=();
  $flag=0; $i=0;
  open(IN,"$logfile") || &error("Open Error: $logfile");
  while (<IN>) {
    $i++;
    ($num,$date,$name,$email,$sub,$com,$url,$host,$pwd) = split(/<>/);
    if ($in{'no'} == $num) {
      $i2=$i;
      $flag=1;
      if ($pwd eq '') { $flag=2; last; }
      else { $pwd2=$pwd; next; }
    }
    push(@lines,$_);
  }
  close(IN);
  if ($flag == 0) { &error("［該当の記事NOが見当たりません］"); }
  if ($flag == 2) { &error("［削除キーが設定されていません］"); }

  # 削除キー照合
  $check = &decrypt($in{'pwd'}, $pwd2);
  if ($check ne 'yes') { &error("［削除キーが違います］"); }

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

  # HTMLファイルを生成
  if ($i2 > $pagelog) { &html_regist($nexthtm, 2); }
  elsif ($i2 <= $pagelog) {
    &html_regist("$htm_dir$htmfile", 1);
    &html_regist("$htm_dir$nexthtm", 2) if ($pagelog < @lines);
  }

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

  # 初期画面に戻る
  &location;
  exit;
}

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

  if ($ENV{'REQUEST_METHOD'} eq "POST") {
    &error("投稿量OVER") if ($ENV{'CONTENT_LENGTH'} > 51200);
    read(STDIN, $buf, $ENV{'CONTENT_LENGTH'});
  } else {
    $buf = $ENV{'QUERY_STRING'};
  }

  undef(%in);
  foreach ( split(/&/, $buf) ) {
    ($key,$val) = split(/=/);
    $val =~ tr/+/ /;
    $val =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("H2", $1)/eg;

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

    # エスケープ
    $val =~ s/\0//g;
    $val =~ s/<>/&LT;&GT;/g;
    $val =~ s/&/&amp;/g;
    $val =~ s/"/&quot;/g;
    $val =~ s/</&lt;/g;
    $val =~ s/>/&gt;/g;
    $val =~ s/\r\n/<br>/g;
    $val =~ s/\r/<br>/g;
    $val =~ s/\n/<br>/g;
    $val =~ s/[\x00-\x20]+/ /g;

    $in{$key} = $val;
  }
  $mode = $in{'mode'};
  if ($in{'sub'} eq "") { $in{'sub'} = "無題"; }
}

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

  print &header;
  print "<div align=center><hr width=400><h3>ERROR !</h3>\n";
#-- 2005.09.14 編集 Start --#
#  print "<font color=\"$t_color\"><B>$_[0]</B></font>\n";
  print "<font color=\"@{[&sanitize::ez_sanitize($t_color)]}\"><B>@{[&sanitize::ez_sanitize($_[0])]}</B></font><BR><BR>\n";
  print "[<a href=\"javascript:history.back()\">［戻る］</a>]<BR><BR>\n";
#-- 2005.09.14 編集 End --#
  print "<p><hr width=400></div>\n</body>\n</html>\n";
  exit;
}

#-------------------------------------------------
#  クッキー発行
#-------------------------------------------------
sub set_cookie {
  local(@cook) = @_;
  local($gmt, $cook, @t, @m, @w);

  @t = gmtime(time + 60*24*60*60);
  @m = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
  @w = ('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

  # 国際標準時を定義
  $gmt = sprintf("%s, %02d-%s-%04d %02d:%02d:%02d GMT",
      $w[$t[6]], $t[3], $m[$t[4]], $t[5]+1900, $t[2], $t[1], $t[0]);

  # 保存データをURLエンコード
  foreach (@cook) {
    s/(\W)/sprintf("%%%02X", unpack("C", $1))/eg;
    $cook .= "$_<>";
  }

  # 格納
  print "Set-Cookie: SUN_BOARD=$cook; expires=@{[&sanitize::ez_sanitize($gmt)]}\n";
}

#-------------------------------------------------
#  クッキー取得
#-------------------------------------------------
sub get_cookie {
  local($key, $val, *cook);

  # クッキーを取得
  $cook = $ENV{'HTTP_COOKIE'};

  # 該当IDを取り出す
  foreach ( split(/;/, $cook) ) {
    ($key, $val) = split(/=/);
    $key =~ s/\s//g;
    $cook{$key} = $val;
  }

  # データをURLデコードして復元
  foreach ( split(/<>/, $cook{'SUN_BOARD'}) ) {
    s/%([0-9A-Fa-f][0-9A-Fa-f])/pack("H2", $1)/eg;

    push(@cook,$_);
  }
  return (@cook);
}

#-------------------------------------------------
#  ワード検索
#-------------------------------------------------
sub find {
  print &header;
  print <<"EOM";
[<a href="@{[&sanitize::ez_sanitize($htm_url.$htmfile)]}">［戻る］</a>]
<table width="100%"><tr><th bgcolor="@{[&sanitize::ez_sanitize($obi_color)]}">
<font color="@{[&sanitize::ez_sanitize($s_color)]}">［ワード検索］</font></th></tr></table>
<ul>
<li>検索したいキーワードを入力し検索条件を選択して検索ボタンを押してください。
<li>複数のキーワードを入力するときは、半角スペースで区切って下さい。
<form action="@{[&sanitize::ez_sanitize($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=\"@{[&sanitize::ez_sanitize($_)]}\" selected>@{[&sanitize::ez_sanitize($_)]}\n";
    } else {
      print "<option value=\"@{[&sanitize::ez_sanitize($_)]}\">@{[&sanitize::ez_sanitize($_)]}\n";
    }
  }
  print "</select>\n<input type=submit value='［検索］ '></form>\n</ul>\n";

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

    local($wd,$flag,$count,$no,$date,$name,$email,$sub,$com,$url,$ho,$pw,$tag,@wd,@new);

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

    @new=();
    open(IN,"$logfile") || &error("Can't open $logfile");
    while (<IN>) {
      $flag=0;
      foreach $wd (@wd) {
        if (index($_,$wd) >= 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;
    print "検索結果：<b>@{[&sanitize::ez_sanitize($count)]}</b>件<dl>\n";
    foreach (@new) {
      ($no,$date,$name,$email,$sub,$com,$url,$ho,$pw,$tag) = split(/<>/);
        $name = "<a href=\"mailto:$email\">$name</a>" if ($email);
      if ($url) {
        if ($url !~ m|https?://|i) { $url = "http://$url"; }
          $url = "&lt;<a href=\"$url\" target=\"_top\">URL</a>&gt;";
      }
      print "<dt><hr>\n";
      if ($whatsnew) {
        $com = &tagview($com) if ($tag == 1);
#-- 2005.09.14 編集 Start --#
#        print "[<b>$no</b>] <b>$sub</b> Date：$date $url<br><br>\n";
        print "<TABLE><TR><TD>[<b>@{[&sanitize::ez_sanitize($no)]}</b>] <b>$sub</b></TD></TR><TR><TD>投稿日時：@{[&sanitize::ez_sanitize($date)]} $url</TD></TR></TABLE><br><br>\n";
#-- 2005.09.14 編集 End --#
      } else {
        print "[<b>@{[&sanitize::ez_sanitize($no)]}</b>] <b>$sub</b> 投稿者：<b>$name</b> ";
        print "投稿日：@{[&sanitize::ez_sanitize($date)]} $url<br><br>\n";
      }
      print "<dd>$com<br><br>\n";
    }
    print "<dt><hr></dl>\n";
  }
  print "</body>\n</html>\n";
  exit;
}

#-------------------------------------------------
#  HTMLヘッダ
#-------------------------------------------------
sub header {
  local($_);
  return if ($headflag);

  if ($_[0] ne 'HTML') {
    $_ .= "Content-type: text/html\n\n";
    $headflag=1;
  }
  $_ .= "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
  $_ .= "<html lang=\"ja\"><head>\n";
  $_ .= "<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">\n" if ($nocashe);
  $_ .= "<META HTTP-EQUIV=\"Content-type\" CONTENT=\"text/html; charset=Shift_JIS\">\n";
  $_ .= "<META HTTP-EQUIV=\"Content-Style-Type\" content=\"text/css\">\n";
  $_ .= "<STYLE type=\"text/css\"><!--\n";
  $_ .= "body,tr,td,th { font-size:@{[&sanitize::ez_sanitize($b_size)]}; font-family:'MS UI Gothic'; }\n";
  $_ .= "a:link    { text-decoration:none; }\n";
  $_ .= "a:visited { text-decoration:none; }\n";
  $_ .= "a:active  { text-decoration:none; }\n";
  $_ .= "a:hover { text-decoration:underline; color:@{[&sanitize::ez_sanitize($al)]}; }\n--></STYLE>\n";
  $_ .= "<title>@{[&sanitize::ez_sanitize($title)]}</title></head>\n";

  if ($bg) {
    $_ .= "<body background=\"@{[&sanitize::ez_sanitize($bg)]}\" bgcolor=\"@{[&sanitize::ez_sanitize($bc)]}\" text=\"@{[&sanitize::ez_sanitize($tx)]}\" link=\"@{[&sanitize::ez_sanitize($lk)]}\" vlink=\"@{[&sanitize::ez_sanitize($vl)]}\" alink=\"@{[&sanitize::ez_sanitize($al)]}\">\n";
  } else {
    $_ .= "<body bgcolor=\"@{[&sanitize::ez_sanitize($bc)]}\" text=\"@{[&sanitize::ez_sanitize($tx)]}\" link=\"@{[&sanitize::ez_sanitize($lk)]}\" vlink=\"@{[&sanitize::ez_sanitize($vl)]}\" alink=\"@{[&sanitize::ez_sanitize($al)]}\">\n";
  }
  $_;
}

#-------------------------------------------------
#  パスワード暗号
#-------------------------------------------------
sub encrypt {
  local($inpw) = $_[0];
  local(@SALT, $salt, $encrypt);

  @SALT = ('a'..'z', 'A'..'Z', '0'..'9', '.', '/');
  srand;
  $salt = $SALT[int(rand(@SALT))] . $SALT[int(rand(@SALT))];
  $encrypt = crypt($inpw, $salt) || crypt ($inpw, '$1$' . $salt);
  $encrypt;
}

#-------------------------------------------------
#  パスワード照合
#-------------------------------------------------
sub decrypt {
  local($inpw, $logpw) = @_;
  local($salt, $check);

  $salt = $logpw =~ /^\$1\$(.*)\$/ && $1 || substr($logpw, 0, 2);
  $check = "no";
  if (crypt($inpw, $salt) eq $logpw || crypt($inpw, '$1$' . $salt) eq $logpw)
    { $check = "yes"; }
  $check;
}

#-------------------------------------------------
#  ロック処理
#-------------------------------------------------
sub lock {
  local($retry) = 5;

  if (-e $lockfile) {
    local($mtime) = (stat($lockfile))[9];
    if ($mtime < time - 30) { &unlock; }
  }

  # symlink関数式ロック
  if ($lockkey == 1) {
    while (!symlink(".", $lockfile)) {
      if (--$retry <= 0) { &error('LOCK is BUSY'); }
      sleep(1);
    }

  # mkdir関数式ロック
  } elsif ($lockkey == 2) {
    while (!mkdir($lockfile, 0755)) {
      if (--$retry <= 0) { &error('LOCK is BUSY'); }
      sleep(1);
    }
  }
  $lockflag=1;
}

#-------------------------------------------------
#  ロック解除
#-------------------------------------------------
sub unlock {
  if ($lockkey == 1) { unlink($lockfile); }
  elsif ($lockkey == 2) { rmdir($lockfile); }

  $lockflag=0;
}

#-------------------------------------------------
#  ホスト名取得
#-------------------------------------------------
sub get_host {
  $host = $ENV{'REMOTE_HOST'};
  $addr = $ENV{'REMOTE_ADDR'};
  if ($gethostbyaddr && ($host eq "" || $host eq $addr)) {
    $host = gethostbyaddr(pack("C4", split(/\./, $addr)), 2);
  }
  if ($host eq "") { $host = $addr; }
}

#-------------------------------------------------
#  時間取得
#-------------------------------------------------
sub get_time {
  local($date,@week);

  $ENV{'TZ'} = "JST-9";
#-- 2005.09.16 編集 Start --#
#  local($min,$hour,$mday,$mon,$year,$wday) = (localtime(time))[1..6];
#  @week = ('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
  local($sec,$min,$hour,$mday,$mon,$year,$wday) = (localtime(time))[0..6];
  @week = ('日','月','火','水','木','金','土');
#-- 2005.09.16 編集 End --#

  # 日時のフォーマット
  if ($whatsnew) {
#-- 2005.09.16 編集 Start --#
#    $date = sprintf("%04d-%02d-%02d (%s)",
#        $year+1900,$mon+1,$mday,$week[$wday],$hour,$min);
    $date = sprintf("%04d年%02d月%02d日(%s) %02d:%02d:%02d",
        $year+1900,$mon+1,$mday,$week[$wday],$hour,$min,$sec);
  } else {
#    $date = sprintf("%04d/%02d/%02d(%s) %02d:%02d",
#        $year+1900,$mon+1,$mday,$week[$wday],$hour,$min);
    $date = sprintf("%04d/%02d/%02d(%s) %02d:%02d:%02d",
        $year+1900,$mon+1,$mday,$week[$wday],$hour,$min,$sec);
#-- 2005.09.16 編集 End --#
  }
  $date;
}

#-------------------------------------------------
#  自動リンク
#-------------------------------------------------
sub auto_link {
  $_[0] =~ s/([^=^\"]|^)(http\:[\w\.\~\-\/\?\&\+\=\:\@\%\;\#\%]+)/$1<a href=\"$2\" target=\"_top\">$2<\/a>/g;
}

#-------------------------------------------------
#  メール送信
#-------------------------------------------------
#-- 2005.09.16 編集 Start --#
#sub mail_to {
#  local($msub,$mbody,$com);
#
#  # メールタイトルを定義
#  $msub = &base64("[$title : $no] $in{'sub'}");
#
#  $com = $in{'comment'};
#  $com =~ s/<br>/\n/ig;
#  $com =~ s/&amp;/&/g;
#  $com =~ s/&quot;/"/g;
#  $com =~ s/&lt;/</g;
#  $com =~ s/&gt;/>/g;
#
  # メール本文を定義
#  $mbody = <<EOM;
#投稿日時：$date
#ホスト名：$host
#ブラウザ：$ENV{'HTTP_USER_AGENT'}
#
#おなまえ：$in{'name'}
#Ｅメール：$in{'email'}
#タイトル：$in{'sub'}
#ＵＲＬ  ：$in{'url'}
#
#$com
#EOM

  # sendmail起動
#  open(MAIL,"| $sendmail -t");
#  print MAIL "To: $mailto\n";
#  print MAIL "From: $mailto\n";
#  print MAIL "Subject: $msub\n";
#  print MAIL "Content-type: text/plain; charset=ISO-2022-JP\n";
#  print MAIL "Content-Transfer-Encoding: 7bit\n";
#  print MAIL "X-Mailer: $ver\n\n";
#  foreach ( split(/\n/, $mbody) ) {
#    &jcode'convert(*_, 'jis', 'sjis');
#    print MAIL $_, "\n";
#  }
#  close(MAIL);
#}
#-- 2005.09.16 編集 End --#

#-------------------------------------------------
#  BASE64変換
#-------------------------------------------------
#  とほほのWWW入門で公開されているルーチンを
#  参考にしました。( http://tohoho.wakusei.ne.jp/ )
sub base64 {
  local($sub) = @_;
  &jcode'convert(*sub, 'jis', 'sjis');

  $sub =~ s/\x1b\x28\x42/\x1b\x28\x4a/g;
  $sub = "=?iso-2022-jp?B?" . &b64enc($sub) . "?=";
  $sub;
}
sub b64enc {
  local($ch)="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  local($x, $y, $z, $i);
  $x = unpack("B*", $_[0]);
  for ($i=0; $y=substr($x,$i,6); $i+=6) {
    $z .= substr($ch, ord(pack("B*", "00" . $y)), 1);
    if (length($y) == 2) {
      $z .= "==";
    } elsif (length($y) == 4) {
      $z .= "=";
    }
  }
  $z;
}

#-------------------------------------------------
#  ログ表示
#-------------------------------------------------
sub log_view {
  local($_);
  local($data, $page) = @_;
  local($num,$date,$name,$email,$sub,$com,$url,$host,$pw,$tag) = split(/<>/, $data);
  if ($url && $url !~ m|https?://|i) { $url = "http://$url"; }

  # 掲示板モードの場合
  if (!$whatsnew) {
    &auto_link($com) if ($autolink);

    $_ .= "<table width='100%' cellpadding=2><tr>\n";
    $_ .= "<td bgcolor=\"$obi_color\">　<font color=\"$p_color\">$point</font>\n";
    $_ .= "<font color=\"$s_color\"><b>$sub</b></font></table>\n";
    $_ .= "<table cellspacing=0 cellpadding=1>\n";
    $_ .= "<tr><td width=15><td>No.<td>： <B>$num</B> &nbsp; [<a href=\"$script?mode=form&no=$num&page=$page\">返信</a>]\n";
    $_ .= "<tr><td width=15><td>Name<td>： <b>$name</b>\n";
#-- 2005.09.14 編集 Start --#
#    $_ .= "<tr><td width=15><td>Date<td>： $date\n";
    $_ .= "<tr><td width=15><td>投稿日時<td>： $date\n";
#-- 2005.09.14 編集 End --#
    $_ .= "<tr><td width=15><td>Mail<td>： <a href=\"mailto:$email\">$email</a>\n" if ($email);
    $_ .= "<tr><td width=15><td>URL<td>： <a href=\"$url\" target=\"_top\">$url</a>\n" if ($url);
    $_ .= "</table>\n<blockquote>$com</blockquote><hr>\n";

  # 新着ボードの場合
  } else {
    $com = &tagview($com) if ($tag == 1);
    &auto_link($com) if ($autolink);

    $_ .= "<table width='100%' cellpadding=2><tr>\n";
    $_ .= "<td bgcolor=\"$obi_color\">　<font color=\"$p_color\">$point</font>\n";
    $_ .= "<font color=\"$s_color\"><b>$sub</b></font></table>\n";
#-- 2005.09.14 編集 Start --#
#    $_ .= "<table><tr><td width=15><td>Date: $date</table>\n";
    $_ .= "<table><tr><td width=15><td>投稿日時: $date</table>\n";
#-- 2005.09.14 編集 End --#
    $_ .= "<blockquote>$com\n";
    $_ .= "<P><a href=\"$url\" target=\"_top\">$url</a>\n" if ($url);
    $_ .= "</blockquote><hr>\n";
  }
  $_;
}

#-------------------------------------------------
#  過去ログ生成
#-------------------------------------------------
sub pastlog {
  local($pno,$pdate,$pname,$pmail,$psub,$pcom,$purl,$pho,$ppw,$ptag,$count,$pastfile,@past,@temp);
  local($past_flag)=0;

  # 過去NOを開く
  open(NO,"$nofile") || &error("Open Error: $nofile");
  $count = <NO>;
  close(NO);
  $count = sprintf("%04d", $count);

  # 過去ログのファイル名を定義
  $pastfile = "$pastdir$count\.dat";

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

  # 規定の行数をオーバーすると次ファイルを自動生成
  if ($#past > $log_line-2) {
    $past_flag=1;

    # カウントファイル更新
    $count++;
    open(NO,">$nofile") || &error("Write Error: $nofile");
    print NO $count;
    close(NO);
    $pastfile = "$pastdir$count\.dat";
    @past=();
  }

  @temp=();
  foreach (@data) {
    ($pno,$pdate,$pname,$pmail,$psub,$pcom,$purl,$pho,$ppw,$ptag) = split(/<>/);
    if ($pmail) { $pname = "<a href=\"mailto:$pmail\">$pname</a>"; }
    if ($purl) {
      if ($purl !~ m|https?://|i) { $purl = "http://$purl"; }
      $purl = "&lt;<a href=\"$purl\" target='_top'>URL</a>&gt;";
    }
    if ($whatsnew) {
      $pcom = &tagview($pcom) if ($ptag == 1);
#-- 2005.09.14 編集 Start --#
#      push(@temp,"<hr>[<b>$pno</b>] <b>$psub</b> Date：$pdate $purl<br><blockquote>$pcom</blockquote>\n");
      push(@temp,"<hr>[<b>$pno</b>] <b>$psub</b> 投稿日時：$pdate $purl<br><blockquote>$pcom</blockquote>\n");
#-- 2005.09.14 編集 End --#
    } else {
      push(@temp,"<hr>[<b>$pno</b>] <b>$psub</b> 投稿者：<b>$pname</b> 投稿日：$pdate $purl<br><blockquote>$pcom</blockquote><!-- $pho -->\n");
    }
  }

  # 過去ログを更新
  unshift(@past,@temp);
  open(OUT,">$pastfile") || &error("Write Error: $pastfile");
  print OUT @past;
  close(OUT);

  if ($past_flag) { chmod(0666,$pastfile); }
}

#-------------------------------------------------
#  過去ログ
#-------------------------------------------------
sub past {
  local($pastno,$next,$back,$count);

  open(IN,"$nofile") || &error("Open Error: $nofile");
  $pastno = <IN>;
  close(IN);
  if (!$in{'pastlog'}) { $in{'pastlog'} = $pastno; }
  $in{'pastlog'} = sprintf("%04d", $in{'pastlog'});

  print &header;
  print <<"EOM";
[<a href="@{[&sanitize::ez_sanitize($htm_url.$htmfile)]}">[戻る]</a>]
<table width="100%"><tr><th bgcolor="@{[&sanitize::ez_sanitize($obi_color)]}">
<font color="@{[&sanitize::ez_sanitize($s_color)]}">[過去ログ][$in{'pastlog'}]</font></th></tr></table>
<P><table><tr><td>
<form action="@{[&sanitize::ez_sanitize($script)]}" method="POST">
<input type=hidden name=mode value=past>
過去ログ：<select name=pastlog>
EOM
  $pastkey = $pastno;
  while ($pastkey > 0) {
    $pastkey = sprintf("%04d", $pastkey);
    if ($in{'pastlog'} == $pastkey) {
      print "<option value=\"@{[&sanitize::ez_sanitize($pastkey)]}\" selected>@{[&sanitize::ez_sanitize($pastkey)]}\n";
    } else {
      print "<option value=\"@{[&sanitize::ez_sanitize($pastkey)]}\">@{[&sanitize::ez_sanitize($pastkey)]}\n";
    }
    $pastkey--;
  }
  print "</select>\n<input type=submit value='移動'></td></form>\n";
  print "<td width=30><td><form action=\"@{[&sanitize::ez_sanitize($script)]}\" method=\"POST\">\n";
  print "<input type=hidden name=mode value=past>\n";
  print "<input type=hidden name=pastlog value=\"$in{'pastlog'}\">\n";
  print "キーワード：<input type=text name=word size=30 value=\"$in{'word'}\">\n";
  print "条件：<select name=cond>\n";

  foreach ('AND', 'OR') {
    if ($in{'cond'} eq $_) {
      print "<option value=\"@{[&sanitize::ez_sanitize($_)]}\" selected>@{[&sanitize::ez_sanitize($_)]}\n";
    } else {
      print "<option value=\"@{[&sanitize::ez_sanitize($_)]}\">@{[&sanitize::ez_sanitize($_)]}\n";
    }
  }
  print "</select>\n 表\示：<select name=view>\n";
  if ($in{'view'} eq "") { $in{'view'} = $pagelog; }
  foreach (5,10,15,20,25,30) {
    if ($in{'view'} eq $_) {
      print "<option value=\"@{[&sanitize::ez_sanitize($_)]}\" selected>@{[&sanitize::ez_sanitize($_)]}件\n";
    } else {
      print "<option value=\"@{[&sanitize::ez_sanitize($_)]}\">@{[&sanitize::ez_sanitize($_)]}件\n";
    }
  }
  print "</select>\n<input type=submit value='［検索］'>",
  "</td></form></tr></table>\n";

  # 表示ログを定義
  $in{'pastlog'} =~ s/\D//g;
  $file = "$pastdir$in{'pastlog'}\.dat";

  # ワード検索処理
  if ($in{'word'} ne "") {

    local($flag,$wd,$count,@wd,@new);

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

    @new=();
    open(IN,"$file") || &error("Open Error: $file");
    while (<IN>) {
      $flag=0;
      foreach $wd (@wd) {
        if (index($_,$wd) >= 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;
    print "<p>検索結果：<b>@{[&sanitize::ez_sanitize($count)]}</b>件\n";
    if ($in{'page'} eq '') { $in{'page'} = 0; }
    $end_data = @new - 1;
    $page_end = $in{'page'} + $in{'view'} - 1;
    if ($page_end >= $end_data) { $page_end = $end_data; }

    $next = $page_end + 1;
    $back = $in{'page'} - $in{'view'};

    $eword = &url_enc($in{'word'});
    if ($back >= 0) {
      print "[<a href=\"@{[&sanitize::ez_sanitize($script)]}?mode=past&page=@{[&sanitize::ez_sanitize($back)]}&word=@{[&sanitize::ez_sanitize($eword)]}&view=$in{'view'}&cond=$in{'cond'}&pastlog=$in{'pastlog'}\">前の$in{'view'}件</a>]\n";
    }
    if ($page_end ne $end_data) {
      print "[<a href=\"@{[&sanitize::ez_sanitize($script)]}?mode=past&page=@{[&sanitize::ez_sanitize($next)]}&word=@{[&sanitize::ez_sanitize($eword)]}&view=$in{'view'}&cond=$in{'cond'}&pastlog=$in{'pastlog'}\">次の$in{'view'}件</a>]\n";
    }

    # 表示開始
    foreach ($in{'page'} .. $page_end) { print @{[&sanitize::ez_sanitize($new[$_])]}; }
#-- 2005.09.16 編集 Start --#
    print "<hr>\n</body>\n</html>\n";
#    print "<hr><span style="font-size:14px;">All rights reserved, Copyright (c) 2005 KAJIMA CORPORATION</span>\n</body>\n</html>\n";
#-- 2005.09.16 編集 End --#
    exit;
  }

  # ページ区切り処理
  $start = $in{'page'} + 1;
  $end   = $in{'page'} + $pagelog;

  $i=0;
  open(IN,"$file") || &error("Open Error: $file");
  while (<IN>) {
    $i++;
    if ($i < $start) { next; }
    if ($i > $end) { last; }
    print $_;
  }
  close(IN);

  print "<hr>\n";

  $next = $in{'page'} + $pagelog;
  $back = $in{'page'} - $pagelog;

  print "<table>\n";
  if ($back >= 0) {
    print "<td><form action=\"@{[&sanitize::ez_sanitize($script)]}\" method=\"POST\">\n";
    print "<input type=hidden name=mode value=past>\n";
    print "<input type=hidden name=pastlog value=\"$in{'pastlog'}\">\n";
    print "<input type=hidden name=page value=\"@{[&sanitize::ez_sanitize($back)]}\">\n";
    print "<input type=submit value=\"前の@{[&sanitize::ez_sanitize($pagelog)]}件\"></td></form>\n";
  }
  if ($next < $i) {
    print "<td><form action=\"@{[&sanitize::ez_sanitize($script)]}\" method=\"POST\">\n";
    print "<input type=hidden name=mode value=past>\n";
    print "<input type=hidden name=pastlog value=\"$in{'pastlog'}\">\n";
    print "<input type=hidden name=page value=\"@{[&sanitize::ez_sanitize($next)]}\">\n";
    print "<input type=submit value=\"次の@{[&sanitize::ez_sanitize($pagelog)]}件\"></td></form>\n";
  }
  print "</table>\n</body>\n</html>\n";
  exit;
}

#-------------------------------------------------
#  URLエンコード
#-------------------------------------------------
sub url_enc {
  local($_) = @_;

  s/(\W)/'%' . unpack('H2', $1)/eg;
  s/\s/+/g;
  $_;
}

#-------------------------------------------------
#  タグ復元
#-------------------------------------------------
sub tagview {
  local($_) = @_;

  s/&lt;/</g;
  s/&gt;/>/g;
  s/&quot;/"/g;
  s/&amp;/&/g;

  $_;
}

#-------------------------------------------------
#  チェックモード
#-------------------------------------------------
sub check {
  print &header;
  print "<h2>Check Mode</h2>\n";
  print "<ul>\n";

  # 3ファイルチェック
  foreach ("$logfile", "$htm_dir$htmfile", "$htm_dir$nexthtm") {
    # パス
    if (-e $_) { print "<li>@{[&sanitize::ez_sanitize($_)]} のパス：OK\n"; }
    else { print "<li>@{[&sanitize::ez_sanitize($_)]} のパス：NG\n"; }

    # パーミッション
    if (-r $_ && -w $_) { print "<li>@{[&sanitize::ez_sanitize($_)]} のパーミッション：OK\n"; }
    else { print "<li>@{[&sanitize::ez_sanitize($_)]} のパーミッション：NG\n"; }
  }

  # ロックディレクトリ
  print "<li>ロック形式：";
  if ($lockkey == 0) { print "ロック設定なし\n"; }
  else {
    if ($lockkey == 1) { print "symlink\n"; }
    else { print "mkdir\n"; }

    ($lockdir) = $lockfile =~ /(.*)[\\\/].*$/;
    print "<li>ロックディレクトリ：@{[&sanitize::ez_sanitize($lockdir)]}\n";

    if (-d $lockdir) {
      print "<li>ロックディレクトリのパス：OK\n";
      if (-r $lockdir && -w $lockdir && -x $lockdir) {
        print "<li>ロックディレクトリのパーミッション：OK\n";
      } else {
        print "<li>ロックディレクトリのパーミッション：NG → @{[&sanitize::ez_sanitize($lockdir)]}\n";
      }
    } else { print "<li>ロックディレクトリのパス：NG → @{[&sanitize::ez_sanitize($lockdir)]}\n"; }
  }

  # 過去ログ
  print "<li>過去ログ：";
  if ($pastkey == 0) { print "設定なし\n"; }
  else {
    print "設定あり\n";

    # NOファイル
    if (-e $nofile) {
      print "<li>NOファイルパス：OK\n";
      if (-r $nofile && -w $nofile) { print "<li>NOファイルパーミッション：OK\n"; }
      else { print "<li>NOファイルパーミッション：NG → @{[&sanitize::ez_sanitize($nofile)]}\n"; }
    } else { print "<li>NOファイルのパス：NG → @{[&sanitize::ez_sanitize($nofile)]}\n"; }

    # ディレクトリ
    if (-d $pastdir) {
      print "<li>過去ログディレクトリパス：OK\n";
      if (-r $pastdir && -w $pastdir && -x $pastdir) {
        print "<li>過去ログディレクトリパーミッション：OK\n";
      } else {
        print "<li>過去ログディレクトリパーミッション：NG → @{[&sanitize::ez_sanitize($pastdir)]}\n";
      }
    } else { print "<li>過去ログディレクトリのパス：NG → @{[&sanitize::ez_sanitize($pastdir)]}\n"; }
  }

  print "</ul>\n</body>\n</html>\n";
  exit;
}


__END__

