#!/usr/bin/perl
#       ↑あなたが加入しているプロバイダの｢perl｣言語が使用できる
#         パスを指定します。一般的に｢#!/usr/local/bin/perl｣で大丈夫

#=======================================================================================
#				News Version 98.11
#=======================================================================================
#日本語コード変換モジュール
# require 'jcode.pl';  # 未使用のため無効化（Perl 5.26以降で読み込めずエラーになる）

#---------------------------------------
#メッセージを格納するデータベースファイル
$datafile = 'news.txt';
#---------------------------------------
#ホームページに戻るアドレス
$homepage ='http://www.soh-naika.jp/';
#---------------------------------------
#バックグランドの画像ファイル
$bg_gif = '';
#最新記事画像
$new_gif = 'img/new.gif';
$line_gif = 'img/line.gif';
$bt_gif = 'img/bt.gif';
$title_gif = 'img/title.gif';
#---------------------------------------
#管理者削除モードのパスワード
$password = 'topic4589';
#---------------------------------------
#掲示板の名前
$title = 'そう内科クリニック | お知らせ';
#---------------------------------------
#バックグランドカラー
$bg_color = '#FFFFFF';
#テキストの文字色
$text_color = '#333333';
#リンク文字色
$link_color = '#6666FF';
#Ｖリンク文字色
$vlink_color = '#6666FF';
#Ａリンク文字色
$alink_color = '#6666FF';

#題名の文字色
$subject_color = '#333333';
#題名のバック色
$subject_bgcolor = '#FFFFFF';
#---------------------------------------
#保存する更新履歴（極端に多くするとパフォーマンスが低下します）
$max = 100;
#---------------------------------------
#1ページに表示する件数
$pagevew = 40;
#---------------------------------------
#タグの使用　1 / 0
$tag = 1;
#---------------------------------------
#<body>タグは自動で付けられるのでそれ以降のヘッダー部
$title_html = <<"TITLE_HTML_END";
<!--　ここにページの先頭に表示するタイトルを自由に記入　-->
<!-- 東京メトロ有楽町線　小竹向原駅1番出口から徒歩3分　内科・消化器科　そう内科クリニック | お知らせ -->


<!--ここまで-->
TITLE_HTML_END
#=======================================================================================
#			初期設定が必要なのはここまでです。
#=======================================================================================
#日付と時刻を取得して、すべて２桁に統一する
$ENV{'TZ'} = "JST-9";
($sec,$min,$hour,$day,$month,$year,$yday,$isdst) = localtime(time);
	$year += 1900;
	$month = sprintf("%02d",$month + 1);
	$day = sprintf("%02d",$day);
	$DATE = "$year/$month/$day";

$agent = $ENV{'HTTP_USER_AGENT'};
$textwidth = 120;
if ($agent =~ /MSIE\ 3/i) { $textwidth = $textwidth * 1.5; }
if ($ENV{'REQUEST_METHOD'} eq "POST") {
	read(STDIN, $formdata, $ENV{'CONTENT_LENGTH'});
} else { $formdata = $ENV{'QUERY_STRING'}; }
@pairs = split(/&/,$formdata);
foreach $pair (@pairs) {
	($name, $value) = split(/=/, $pair);
	$value =~ tr/+/ /;
	$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	$value =~ s/</&lt;/g;
	$value =~ s/>/&gt;/g;
	$value =~ s/=/&eq;/g;
	$value =~ s/\n//g;
	$value =~ s/\t/    /g;
	$value = &to_utf8($value);
	if ($QUERY{$name}) { $QUERY{$name} .= " $value"; }
	else { $QUERY{$name} = $value; }
}
if ($QUERY{'button'} ne '次のページ') { $QUERY{'pline'} = 0; }
&data_read;

if ($QUERY{'pass'} eq $password && $QUERY{'action'} eq 'regist') {
	if ($QUERY{'msg'} ne '') {
		if ($tag) { $QUERY{'msg'} = &tag_change($QUERY{'msg'}); }
		$value = join("\t",
			"DATE=$QUERY{'date'}",
			"GIF=$QUERY{'gif'}",
			#"URL=$QUERY{'url'}",
			"MSG=$QUERY{'msg'}",
			"\n"
		);
		if ($QUERY{'editcode'} > 0) {
			$i = 1;
			foreach $line (@DATA) {
				if ($i == $QUERY{'editcode'}) {
					$line = $value;
					last;
				}
				$i++;
			}
		} elsif ($QUERY{'ins_code'} > 0) {
			$i = 1;
			foreach $line (@DATA) {
				push(@NEW_DATA, $line);
				if ($i == $QUERY{'ins_code'}) {
					push(@NEW_DATA, $value);
				}
				$i++;
			}
			@DATA = @NEW_DATA;
		} else { unshift(@DATA, $value); }
		if (&data_save != 1) { &error(bad_save); }
	}
} elsif ($QUERY{'pass'} eq $password && $QUERY{'button'} eq '削除') {
	if ($QUERY{'code'} > 0) {
		$i = 1;
		foreach $line (@DATA) {
			$j = $i - 1;
			if ($i == $QUERY{'code'}) { splice(@DATA, $j, 1); last; }
			$i++;
		}
		if (&data_save != 1) { &error(bad_save); }
	} else { &error(bad_code); }
} elsif ($QUERY{'pass'} eq $password && $QUERY{'button'} eq '訂正') {
	if ($QUERY{'code'} < 1) { &error(bad_code); }
	else {
		$i = 1;
		foreach $line (@DATA) {
			@LINE = split(/\t/,$line);
			foreach (@LINE) {
				($key, $value) = split(/=/,$_);
				$FILE{$key} = $value;
			}
			if ($i == $QUERY{'code'}) { last; }
			$i++;
		}
		$date = $FILE{'DATE'};
		#$url = $FILE{'URL'};
		$msg = $FILE{'MSG'};
		$msg =~ s/&eq;/=/ig;
	}
	&html_head;
	&form(edit);
	print "</body></html>\n";
	exit;
} elsif ($QUERY{'pass'} eq $password && ($QUERY{'button'} eq '挿入' || $QUERY{'button'} eq '新規')) {
	$date = $DATE;
	#$url = '';
	$msg = '';
	&html_head;
	if ($QUERY{'button'} eq '挿入') { &form(ins); }
	elsif ($QUERY{'button'} eq '新規') { &form; }
	print "</body></html>\n";
	exit;
}
if ($QUERY{'vew'}) {
	$vew = $QUERY{'vew'} - 1;
	@LINE = split(/\t/,$DATA[$vew]);
	foreach (@LINE) {
		($key, $value) = split(/=/,$_);
		$FILE{$key} = $value;
	}
	&html_head;
	print "<div align=left>\n";
	print "<table border=0 width=500>\n";
	print "<tr><td rowspan=2>\n";
	if ($FILE{'GIF'} ne '') {
		#if ($FILE{'URL'} ne '') { print "<a href=$FILE{'URL'}>\n"; }
		print "<img src=$FILE{'GIF'} border=0>";
		if ($FILE{'URL'} ne '') { print "</a>\n"; }
	}
	$FILE{'MSG'} =~ s/\r/<br>/ig;
	$FILE{'MSG'} =~ s/&eq;/=/ig;
	$FILE{'MSG'} = &inline_link($FILE{'MSG'});
	print "</td><td bgcolor=$msg_bgcolor valign=top align=left>　<font color=$msg_color>$FILE{'MSG'} </font></td></tr><p>\n";
	print "<tr><td valign=top align=left><font color=#DE1948 size=2>【-$FILE{'DATE'}-】　</font><p>$FILE{'MSG'}<p>\n";
	print "<p align=right><a href=\"javascript:history.back()\"><img src=$bt_gif  border=0 ></a></p>\n";
	print "</td>\n";
	print "</tr>\n";
	print "</table>\n";

	print "</body>\n";
	print "</html>\n";
	exit;
} else {
	&html_head;
	print "<div align=left><left>\n";
	print "<form action=news.cgi method=POST>\n";
		print "<input type=hidden name=pass value=$QUERY{'pass'}>\n";
		if ($QUERY{'pass'} eq $password) {
			print "<table border=0 cellspacing=0><tr>\n";
			print "<td><input type=submit name=button value=新規></td>\n";
			print "<td><input type=submit name=button value=訂正></td>\n";
			print "<td><input type=submit name=button value=挿入></td>\n";
			print "<td><input type=submit name=button value=削除></td>\n";
			print "<td><input type=button value=HomePage onclick=\'location.href=\"$homepage\"\'></td>\n";
			print "</tr></table>\n";
			print "<p>\n";
		}
		if ($QUERY{'pline'} eq '') { $pline = 0; } else { $pline = $QUERY{'pline'}; }
		$end_data = @DATA - 1;
		$page_end = $pline + ($pagevew - 1);
		if ($page_end >= $end_data) { $page_end = $end_data; }
		print "<table width=500><tr><td>\n";

		print "</td></tr>\n";
		$i = 1;
		foreach ($pline .. $page_end) {
			@LINE = split(/\t/,$DATA[$_]);
			foreach (@LINE) {
				($key, $value) = split(/=/,$_);
				$FILE{$key} = $value;
			}
			if ($_ == 0) {
				print "<tr><td  colspan=2 valign=top><img src=$title_gif alt=お知らせ></td></tr>\n";
				print "<tr><td align=left valign=top>\n";
				if ($QUERY{'pass'} eq $password) { print "<input type=radio name=code value=",$_ + 1,">\n"; }
				print "<font color=#DE1948 size=2>【$FILE{'DATE'}】　</font></td><td valign=top align=left><font size=2>$FILE{'MSG'} </font><img src=$new_gif alt=NEW>\n";

				print "</td></tr>\n";
			print "<tr><td valign=top align=left colspan=2><img src=$line_gif></td></tr>\n";}
			if ($i == 1) {
				print "\n";
			}
			if ($_ != 0) {
				print "<tr><td align=left valign=top>";
				if ($QUERY{'pass'} eq $password) { print "<input type=radio name=code value=",$_ + 1,">\n"; }
				print "<font color=#DE1948 size=2>【$FILE{'DATE'}】　</font></td>\n";
				print "<td valign=top align=left><font size=2>$FILE{'MSG'}</font></td></tr>\n";
				print "<tr><td  colspan=2 valign=top><img src=$line_gif></td></tr>\n";
			}
			$i++;
		}

		print "</table>\n";
		$next_line = $page_end + 1;
		if ($page_end ne $end_data && $QUERY{'flags'} ne 'return') {
			print "<input type=hidden name=pline value=$next_line>\n";
			print "<p>\n";
			print "<input type=submit name=button value=\"次のページ\">\n";
		}



	print "</form>\n";
	print "</body>\n";
	print "</html>\n";

	exit;
}
#=======================================================================================
sub html_head {
	print "Content-type: text/html; charset=UTF-8\n\n";
	print "<html>\n";
	print "<head>\n";
	print "<title>$title</title>\n";
	print "</head>\n";
	print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n";
	print "<style type='text/css'>\n";
	print "<!--\n";
	print "a:link    { text-decoration: none; }\n";
	print "a:visited { text-decoration: none; }\n";
	print "a:active  { text-decoration: none; }\n";
	print "a:hover   { ; }\n";
	print "body   { line-height: 1.8em; color: #333; }\n";
	print "-->\n";
	print "</style>\n";

	print "<body bgcolor=$bg_color text=$text_color  link=$link_color vlink=$vlink_color alink=$alink_color>\n";
	print "$title_html\n";
}
#=======================================================================================
sub form {
	local($mode) = $_[0];
	print "<form name=inputform action=news.cgi method=POST>\n";
		print "<input type=hidden name=action value=regist>\n";
		if ($mode eq 'edit') { print "<input type=hidden name=editcode value=$QUERY{'code'}>\n"; }
		if ($mode eq 'ins') { print "<input type=hidden name=ins_code value=$QUERY{'code'}>\n"; }
		print "<input type=hidden name=pass value=$QUERY{'pass'}>\n";
		print "<table border=0>\n";
			print "<tr>";
			print "<td align=right>日付:</td><td><input type=text size=35 name=date value=$date></td></tr>\n";
			#print "<tr><td align=right>URL:</td><td><input type=text size=60 name=url value=$url></td></tr>\n";
			print "</tr>\n";
		print "</table>\n";
		print "<textarea name=msg rows=10 cols=$textwidth>$msg</textarea><br>";
		if ($mode eq 'edit') { print "<input type=submit name=button value=\"$subject 訂正\">\n"; }
		elsif ($mode eq 'ins') { print "<input type=submit name=button value=挿入>\n"; }
		else { print "<input type=submit name=button value=新規書込み>\n"; }
	print "</form>\n";
	#print "[Enter]で改行した位置で改行されます。<br>";
}
#=======================================================================================
sub data_read {
	if (open(DB,"$datafile")) {
		@DATA = <DB>;
		close(DB);
	}
}
#=======================================================================================
sub data_save {
	$datafile =~ /(.+)\..+$/;
	local($filename) = $1;
	if ($filename !~ /.+/) { &error(bad_filename); }
	local($tmpfile) = "$filename.tmp";
	foreach (1 .. 10) {
		unless (-f $tmpfile) { $tmpflag = 1; last; }
		$tmpflag = 0;
		sleep(1);
	}
	if ($tmpflag == 1) {
		$tmp_dummy = "$filename$$\.tmp";
		if (!open(TMP,">$tmp_dummy")) { &error(bad_tmpfile); }
		close(TMP);
		chmod 0666,$tmp_dummy;
		if (!open(TMP,">$tmp_dummy")) { &error(bad_tmpfile); }
		print TMP @DATA;
		close(TMP);
		foreach (1 .. 10) {
			unless (-f $tmpfile) {
				if (!open(TMP,">$tmpfile")) { &error(bad_tmpfile); }
				close(TMP);
				rename($tmp_dummy,$datafile);
				unlink $tmpfile;
				$tmpflag = 1;
				last;
			}
			$tmpflag = 0;
			sleep(1);
		}
	}
	$tmpflag;
}
#=======================================================================================
sub inline_link {
	local($_) = $_[0];
	$_ =~ s/([^=^\"]|^)((http|ftp):[!#-9A-~]+)/$1<a href=$2 target=_top>$2<\/a>/g;
	$_ =~ s/([\w\-\_]+\@[\w\-\_\.]+)/<a href=mailto:$1>$1<\/a>/g;
	$_;
}
#=======================================================================================
sub tag_change {
	local($_) = $_[0];
	$_ =~ s/&eq;/=/g;
	1 while s/(.*)(&lt;(img([!-:A-~\s\=]+))&gt;)/$1<img$4>/i;
	1 while s/(.*)(&lt;(b)&gt;(.*)&lt;\/b&gt;)/$1<b>$4<\/b>/i;
	1 while s/(.*)(&lt;(i)&gt;(.*)&lt;\/i&gt;)/$1<i>$4<\/i>/i;
	1 while s/(.*)(&lt;(font[\s\w\=\#\"\']+)\&gt;(.*)\&lt;\/font\&gt;)/$1<$3>$4<\/font>/i;
	$_ =~ s/=/&eq;/g;
	$_;
}
#=======================================================================================
sub error {
	$error = $_[0];
	if ($error eq "bad_file")	{ $msg = 'ファイルのオープン、入出力に失敗しました。'; }
	elsif ($error eq "bad_filename")	{ $msg = 'ファイル名が不正です。'; }
	elsif ($error eq "bad_mastermode")	{ $msg = '管理者専用です。'; }
	elsif ($error eq "bad_code")	{ $msg = '訂正／削除するコードが見つからないか、<br>パスワードが一致しません。'; }
	elsif ($error eq "bad_pass")	{ $msg = 'パスワードが一致しません。'; }
	elsif ($error eq 'bad_save')	{ $msg = '混雑していて送信に失敗しました。<br>時間をおいて再度送信して下さい。'; }
	elsif ($error eq "bad_tmpfile")	{ $msg = 'テンポラリーが作成できません。<br>ディレクトリのパーミッションを確認してください。'; }
	else { $msg = '原因不明のエラーで処理を継続できません。'; }
	&html_head;
	print "<p>　</p><p>　</p><p>　</p>ERROR</font><p>　</p><p>　</p>\n";
	print "<table border=none width =500><tr>\n";
		print "<td align=left valign=top><p>　</p><p>　</p>\n";
		print "<font size=3><i>$msg</i></font><p>　</p><p>　</p></td>\n";
	print "</tr></table>\n";
	print "</body></html>\n";
	exit;
}

#=======================================================================================
# 入力文字列をUTF-8に統一（UTF-8でなければShift_JIS(CP932)とみなして変換）
sub to_utf8 {
    my $s = shift;

    require Encode;

    eval {
        Encode::decode("UTF-8", $s, Encode::FB_CROAK);
    };

    if ($@) {
        Encode::from_to($s, "cp932", "UTF-8");
    }

    return $s;
}
