#!/usr/bin/perl

#━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#     [スクリプト作成元]
#         ☆　 Monoceros 0.10　☆
#         kz island (keiko)
#        http://www.kz-island.net/
#━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

##################################################
##						##
## [Edit] → My Diary  v1.0307 (01.03.07)	##
##						##
##   *- CGI Cafe. -*				##
##     URL：http://saya.kiy.jp/			##
##						##
##################################################

##----[注意事項]------------------------------------------------##
##								##
## 1. このスクリプトはフリーソフトです。このスクリプトを使用した##
##    いかなる損害に対しても作者は一切の責任を負いません。	##
##								##
## 2. 設置に関する質問は掲示板にお願いいたします。		##
##    メールによる質問には一切お答えしません。			##
##								##
## 3. このCGIに対する問い合わせを、スクリプト作成元には		##
##    絶対にしないでくださいね。				##
##								##
##━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━##
#
#    ◆必要なファイル[パーミッション]
#      ・news.cgi-----------[755]
#      ・jcode.pl-----------------[755]
#      ・diary.txt（ログ保存用）--[666]
#　　　・count.dat（カウンタ用）--[666]
#
#━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

$version = "ver 0.10";		# バージョン(変更不要)
$method = "POST";		# データ受け渡し方法（get or post)

#######--基本設定---#######

require "jcode.pl";		# 日本語変換ライブラリ

$me   = "webmaster";		# 管理人(あなた)の名前
$pass = "homework";			# パスワード(必ず変更してね！)
$home = "";		# 戻り先URL(HOMEページのURLでも可)
$file = "news.cgi";	# このCGI名
$logfile = "diary.txt";		# ログ用ファイル名


#######--応用設定---#######
$color2 = "#FFFFFF";		# 背景色
$bg 	= ";	# 背景画像がある場合は指定（./img/bg.gif 等）
$title  = ";	# タイトル
$title_c= "#000000";		# タイトル色
$title_f= "Courier New";	# タイトルのフォント
$title_s=  4 ;			# タイトルのフォントサイズ
$title_gif = "img/news_title.gif";	# タイトルに画像を使用する場合のみ指定
$tg_w = '';			# タイトル画像の幅
$tg_h = '';			#   　 〃　   の高さ

##------日記記事表示設定------
$t_bder =  1 ;			# 記事表示テーブルの枠サイズ(太さ) ※「0」にすると枠なしです。
$color0 = "#847340";		# 　　　　〃　　　の枠色 ※枠サイズが「0」の場合は設定不要
$t_bg	= "";	# タイトル部分の背景を画像にする場合指定
$color1 = "#FFFFFF";		# タイトルの文字色
$color3 = "#FFFFFF";		# 記事部分の背景色
$body_c = "#847340";		# 記事の文字色
$date_p =  2 ;			# お天気アイコン＆日付を表示する位置は？（1：コメントの上　2：コメントの下）
$font_size  = "13px";		# 文字の大きさ（pt、px指定などができます。あまりでかくしないほうがいいかも。）
$tablewidth = "80%";		# テーブルの幅（px指定などができます。）

$max	 = 100;			# ログの最大保存数(多くしすぎると危険です。)
$pagemax = 10;			# １ページの最大表示数(あまり多くすると表示に時間がかかりますよ。)
$kensu   = "off";		# 画面下に件数表示を・・・表示する：on　、表示しない:off

#--お天気アイコン--
$tenki = "off";			# お天気アイコン（使う[日記など]：on、使わない[更新履歴など]:off）

#使う場合は、画像の指定(あまり画像が大きくなく、大きさがそろっているもの）
#-----アイコンのパスには、saya_diary.cgiから見た画像ファイルのパスを入れてください。
#			アイコンのパス			　　　アイコンの名前
$weather_gif[0] = "./img/hare.gif";		$weather_name[0] = "晴れ";
$weather_gif[1] = "./img/kumo.gif";		$weather_name[1] = "くもり";
$weather_gif[2] = "./img/ame.gif";		$weather_name[2] = "雨";
$weather_gif[3] = "./img/yuki.gif";		$weather_name[3] = "雪";

# ミニカウンタの設置---------------------------------------
$counter   = 0;			# 0=no、 1=テキスト、 2=GIF画像
$mini_fig  = 5;			# ミニカウンタの桁数
$cnt_color = "#80ccff";		# テキストのとき：ミニカウンタの色
$gif_path  = "./img";		# ＧＩＦのとき　：画像までのディレクトリ
$mini_w    = 8;			#       〃    　：画像の横サイズ
$mini_h    = 12;		#       〃    　：画像の縦サイズ
$cntfile   = "./count.dat";	# カウンタファイル
$cnt_pl    = "left";		# カウンターの表示位置　(画面左：left　画面右：right)

# スタイルシート設定-----------------------------------------
$l_color = "#847340";		# リンク色
$hb_link = "#FFFFFF";		# ポイントした時のバック色
$h_link = "#FF6600";		# 　　　〃　　　の文字色
$tback_color = "#FFFFFF";	# テキストエリア部分の下地色
$tfont_color = "#847340";	# 　　　〃　　　部分の文字色

$style = <<"HTML";

<style type="text/css">
<!--
body {font-size: $font_size; font-family: "MS UI Gothic"; color : $body_c;}
td {font-size: $font_size; font-family: "MS UI Gothic" ; color : $l_color; line-height:18px;}
a:link     {color:$l_color; text-decoration:none;}
a:visited  {color:$l_color; text-decoration:none;}
a:active   {color:silver; text-decoration:none;}
a:hover    {text-decoration:underline overline;background-color:$hb_link; color:$h_link;}
input,textarea,select{	cursor:hand; border-left:1px double $l_color;
border-right:1px double $l_color;
border-top:1px double $l_color;
border-bottom:1px double $l_color;
background-color :$tback_color;
font-size:12px; color:$l_color; background-color:$color2 ;}
-->
</style>

HTML

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


#######################################

print "Content-type: text/html\n\n";

######日付と時刻#######################
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	$year = sprintf("%02d",$year + 1900);
	$month = sprintf("%02d",$mon + 1);
	$mday = sprintf("%02d",$mday);
	if ( substr($month,0,1) == 0 )	{	$month =~ s/0/ /;	}
	if ( substr($mday,0,1) == 0 )	{	$mday =~ s/0/ /;	}
	$hour = sprintf("%02d",$hour);
	$min = sprintf("%02d",$min);
	$sec = sprintf("%02d",$sec);
	$youbi = ('Sun','Mon','Tue','Wed','Thu','Fri','Sat') [$wday];
	$date_now = "$year/$month/$mday($youbi)";


######フォームデコード#################
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/\n//g;
	$value =~ s/\,/，/g;
	&jcode'convert(*value,'sjis');
	$FORM{$name} = $value;
}

#### 配列変数にファイル中身を代入#######
if (!open (DATA,"$logfile")) { &error(bad_file); }
@DATA = <DATA>;
close(DATA);


########分岐############################
if($FORM{'action'} eq "pass") {
	if ($FORM{'pass'} eq $pass) {&edit_html;}
	else {&error(bad_pass);} 
}
elsif($FORM{'action'} eq "resist") {
	if ($FORM{'write'} eq "書き直し"){&edit2; &edit_html;}
	else {&resist; &edit_html;}
}
elsif($FORM{'action'} eq "edit") {&del; &edit; &edit_html;}
elsif($FORM{'action'} eq "pagemain"){ &main_html;}
elsif($FORM{'action'} eq "pageedit$pass"){ &edit_html;}
elsif($FORM{'action'} eq "search") {&search;}
else {&main_html;}

########################################################
#メイン表示部
########################################################
sub main_html {

	$pagemode = "pagemain";

	&header;

	# カウンタ処理
	if ($counter) { &counter; }

	print "<div align=\"center\">\n";
	if ($title_gif eq '') {
		print "<font face=\"$title_f\" color=\"$title_c\" size=$title_s><b>$title</b></font>\n";
	}
	else {
		print "<img src=\"$title_gif\" width=\"$tg_w\" height=\"$tg_h\">\n";
	}
	print "</div><br>\n";

	&listview;

	print "<div align=\"center\">\n";
	print "<form action=\"$file\" method=\"$method\">\n";
	print "<input type=\"hidden\" name=\"action\" value=\"pass\">\n";
	print "<input type=\"password\" name=\"pass\" size=\"10\"> \n";
	print "<input type=\"submit\" value=\"$me用\" onMouseOver=\"this.style.background='$hb_link'\" onMouseOut=\"this.style.background='$tback_color'\">\n";
	print "</form></div>\n";
	&footer;
}

########################################################
#編集表示部
########################################################
sub edit_html {

	if ($checkdel == 1 && $checkedit == 1){&error("bad_edit");}

	$pagemode = "pageedit";

	if ($mode eq "edit"){
		$num3 = $num2;
		$date3 = $date2;
		$subject3 = $subject2;
		$comment3 = $comment2;
		$weather3 = $weather2;
		$resist = "書き直し";
	}
	else{
		$date3 = $date_now;
		$subject3 = "";
		$comment3 = "";
		$weather3 = -1;
		$resist = "書き込み";
	}

	&header;
	print "<div align=\"center\">\n";
	if ($title_gif eq '') {
		print "<font face=\"$title_f\" color=\"$title_c\" size=$title_s><b>$title</b></font>\n";
	}
	else {
		print "<img src=\"$title_gif\" width=\"$tg_w\" height=\"$tg_h\">\n";
	}
	print "</div>\n";
	print "<div align=\"center\">\n";
	print "<form action=\"$file\" method=\"$method\">\n";
	print "<input type=\"hidden\" name=\"action\" value=\"resist\">\n";
	if ($mode eq "edit"){
		print "<input type=\"hidden\" name=\"editnum\" value=\"$num3\" size=\"30\">\n";
	}
	print "<table border=\"0\"><tr><td nowrap>情報元 : </td>\n";
	print "<td><input type=\"text\" name=\"date\" value=\"$date3\" size=\"30\"></td>\n";


	#お天気アイコン
	if ($tenki eq "on"){
		print "<td><select name=\"weather\">\n";
		print "<option value=\"noicon\" selected>お天気</option>\n";

		$i = 0;
		foreach $weather_obj(@weather_name) {
			if ($weather3 == $i){ $selected = "selected";}
			else {$selected = "";}
			print "<option value=\"$i\" $selected>$weather_obj</option>\n";
			$i++;
		}
	}
	else {
		print "<td></td><td>\n";
	}


	print "</select></td></tr>\n";

	print "<tr><td nowrap>題名 : </td>\n";
	print "<td colspan=\"2\"><input type=\"text\" name=\"subject\" size=\"30\" value=\"$subject3\"></td></tr>\n";
	print "<tr><td nowrap></td>\n";
	print "<td colspan=\"2\"><textarea name=\"comment\" rows=\"6\" cols=\"70\">$comment3</textarea>\n";
	print "</td></tr>\n";
	print "<tr><td nowrap valign=\"top\"></td>\n";
	print "<td align=\"right\" colspan=\"2\"><input type=\"submit\" value=\"$resist\" name=\"write\" onMouseOver=\"this.style.background='$hb_link'\" onMouseOut=\"this.style.background='$tback_color'\"></td></tr>\n";

	print "</table></form>\n";
	print "<br><a href=\"$file\">- 書き込み終了 -</a></div><p>\n";

	if($mode ne "edit") { &listview;}


	&footer;
}


########################################################
#ログ表示
########################################################
sub listview {
	$count = @DATA;
	if ($pagemode eq "pageedit"){
		print "<form action=\"$file\" method=\"$method\">\n";
	}

	if ($pagemode eq "pageedit" && $count != ""){
		print "<div align=\"center\">\n";
		print "<input type=\"submit\" value=\"編集/削除\" onMouseOver=\"this.style.background='$hb_link'\" onMouseOut=\"this.style.background='$tback_color'\"></div><p>\n";
	}


	if($FORM{'action'} eq ""){$listcount = 0;}
	elsif($FORM{'nb'} eq "NEXT") {$listcount = $FORM{'pagecount'};}
	elsif($FORM{'nb'} eq "BACK") {$listcount = $FORM{'pagecount'} - $pagemax * 2;}

	$i = 0;
	foreach $line(@DATA) {
	$temp = $listcount + $pagemax;
	if ($i > ($temp - 1)){last;}
	if ($i >= $listcount){
	($num,$date,$subject,$comment,$weather,$d2) = split(/\,/,$line);
	#そのうち消す。
	$comment =~ s/\r/<br>/g;
	#URLを判別してリンクをつける
	$comment =~ s/([^=^\"]|^)(http|ftp)([\w|\!\#\&\=\-\%\@\~\;\+\:\.\?\/]+)/$1<a href=\"$2$3\" target="_blank">$2$3<\/a>/g;
	print "<div align=\"center\">\n";
	print "<table width=\"$tablewidth\" border=\"$t_bder\" cellpadding=\"3\" bordercolor=\"$color0\" cellspacing=\"0\">\n";
	print "<tr bgcolor=\"$color0\"><td background=\"$t_bg\">\n";
	print "<font color=\"$color1\">&nbsp&nbsp&nbsp<b>■ $subject</b></font></td></tr>\n";

	#お天気アイコンの表示・非表示
	if ($tenki eq "on" && $weather ne "noicon"){
		$weather_tag = "<img src=\"$weather_gif[$weather]\">&nbsp&nbsp&nbsp";
	}
	else {$weather_tag = "";}

	#日付表示場所の指定
	print "<tr bgcolor=\"$color3\"><td>\n";
	if ($date_p == 1) {
		print "<div align=\"right\">$weather_tag++$date++</font></div>\n";
		print "<font color=\"$body_c\">$comment\n";
	} else {
		print "<font color=\"$body_c\">$comment\n";
		print "<div align=\"right\">$weather_tag++$date++</font></div>\n";
	}

	print "</td></tr>\n";

	if ($pagemode eq "pageedit"){
		print "<input type=\"hidden\" name=\"action\" value=\"edit\">\n";
		print "<tr bgcolor=\"$color2\" align=\"right\"><td>\n";
		print "<input type=\"hidden\" name=\"num\" value=\"$num\">\n";
		print "<input type=\"radio\" name=\"edit\" value=\"$num\">編集 \n";
		print "<input type=\"checkbox\" name=\"del$num\" value=\"on\">削除\n"; 
		print "</td></tr>\n";
	}
	print "</table></div><br><br><br>\n";
	}
	$i++;
	}

	if ($pagemode eq "pageedit" && $count != ""){ print "</form>\n"; }

	if ($temp < $count || ($temp - $pagemax) > 0){
		print "<div align=\"center\"><table border=\"0\" cellpadding=\"5\"><tr>\n";
		print "<form action=\"$file\" method=\"$method\">\n";
		if($pagemode eq "pageedit"){
			print "<input type=\"hidden\" name=\"action\" value=\"$pagemode$pass\">\n";
		}
		else{
			print "<input type=\"hidden\" name=\"action\" value=\"$pagemode\">\n";
		}
		print "<input type=\"hidden\" name=\"pagecount\" value=\"$temp\">\n";
		if(($temp - $pagemax) > 0){
			print "<td><input type=\"submit\" name=\"nb\" value=\"BACK\" onMouseOver=\"this.style.background='$hb_link'\" onMouseOut=\"this.style.background='$tback_color'\"></td>\n";
		}
		if($temp < $count){
			print "<td><input type=\"submit\" name=\"nb\" value=\"NEXT\" onMouseOver=\"this.style.background='$hb_link'\" onMouseOut=\"this.style.background='$tback_color'\"></td>\n";
		}
		print "</tr></form></table></div>\n";
	}

	#表示件数
	if($kensu eq "on"){
		$less = $temp - $pagemax + 1;
		$most = $temp;
		if ($most >= $count){ $most = $count; }
		print "<p align=\"center\"><b>$less件〜$most件/$count件</b></p>\n";
	}

}


########################################################
#ヘッダー
########################################################
sub header {
	print "<html>\n<head>\n";
	print "<META HTTP-EQUIV=\"Content-type\" CONTENT=\"text/html; charset=x-sjis\">\n";
	print "<title>$title</title>\n";
	print "<!--\n";
	print "****************************************************\n";
	print "My Diary[v0.1129](Monoceros $version by kz-island)\n";
	print "http://saya.kiy.jp/\n"; 
	print "****************************************************\n";
	print "-->\n";
	print "$style\n";
	print "</head>\n";
	print "<body text=\"$color\" link=\"$color\" vlink=\"$color\" alink=\"$color\" bgcolor=\"$color2\" background=\"$bg\">\n";
}

########################################################
#書き込み
########################################################
sub resist {

	if($FORM{'date'} eq "" || $FORM{'subject'} eq "" || $FORM{'comment'} eq ""){
		if ($FORM{'date'} eq ""){$bad_write[0] = 1;}
		if ($FORM{'subject'} eq ""){$bad_write[1] = 1;}
		if ($FORM{'comment'} eq ""){$bad_write[2] = 1;}
		if ($FORM{'weather'} eq "noicon"){$bad_write[3] = 1;}
		&error(bad_write);
	}

	$count = @DATA;
	$FORM{'comment'} =~ s/\r/<br>/g;

	$value = "$count\,$FORM{'date'}\,$FORM{'subject'}\,$FORM{'comment'}\,$FORM{'weather'}\,\n";
	$value =~ s/<!--#(.|\n)*-->//ig;

	unshift(@DATA,$value);

	#最大保存数を越えたら削除し、順番をそろえる。
	if ($count > ($max * 1.2)){
		splice(@DATA,$max,$count);

		$count = @DATA - 1;

		foreach $line(@DATA) {
			($num,$date,$subject,$comment,$weather,$d2) = split(/\,/,$line);
			$value = "$count\,$date\,$subject\,$comment\,$weather\,\n";
			$line = $value;
			$count--;
		}
	}


	#### 書き込み
	if (!open (DATA,">$logfile")) { &error(bad_file); }
	print DATA @DATA;
	close(NOTE);
}

########################################################
#削除
########################################################
sub del{

	$count = @DATA;
	$checkdel = 1;

	#削除
	for ($j = 0; $j <= $count; $j++){
		$i = 0;
		foreach $line(@DATA) {
			($num,$date,$subject,$comment,$weather,$d2) = split(/\,/,$line);
			if ($FORM{"del$num"} eq "on"){
				splice(@DATA,$i,1);
				$checkdel = 0;

				#編集のために編集対象の番号を直す。
				if($FORM{'edit'} > $num){
					$FORM{'edit'} = $FORM{'edit'} - 1;
				}

				last;
			}
			$i++;
		}
	}

	#削除チェックボックスにチェックされていたら・・・
	if($checkdel == 0){
		$count = @DATA - 1;

		foreach $line(@DATA) {
			($num,$date,$subject,$comment,$weather,$d2) = split(/\,/,$line);
			$value = "$count\,$date\,$subject\,$comment\,$weather\,\n";
			$line = $value;
			$count--;
		}

		####書き込み######
		if (!open (DATA,">$logfile")) { &error(bad_file); }
		print DATA @DATA;
		close(NOTE);
	}

}

########################################################
#編集
########################################################
sub edit{

	$count = @DATA;
	$checkedit = 1;
	$i = 0;
	@DATA = reverse(@DATA);
	foreach $line(@DATA) {
		($num,$date,$subject,$comment,$weather,$d2) = split(/\,/,$line);
		if ($FORM{'edit'} eq "$num"){
			($num2,$date2,$subject2,$comment2,$weather2,$d22) = split(/\,/,$DATA[$i]);
			$mode ="edit";
			$checkedit = 0;
			$comment2 =~ s/<br>/\r/g;
			last;
		}
		$i++;
	}
	@DATA = reverse(@DATA);

}

########################################################
#編集2
########################################################
sub edit2{

	if($FORM{'date'} eq "" || $FORM{'subject'} eq "" || $FORM{'comment'} eq ""){
		if ($FORM{'date'} eq ""){$bad_write[0] = 1;}
		if ($FORM{'subject'} eq ""){$bad_write[1] = 1;}
		if ($FORM{'comment'} eq ""){$bad_write[2] = 1;}
		if ($FORM{'weather'} eq "noicon"){$bad_write[3] = 1;}
		&error(bad_write);
	}

	$i = 0;
	$FORM{'comment'} =~ s/\r/<br>/g;

	foreach $line (@DATA) {
		($num,$date,$subject,$comment,$weather,$d2) = split(/\,/,$line);
		if ($FORM{'editnum'} eq "$num"){
			$value = "$num\,$FORM{'date'}\,$FORM{'subject'}\,$FORM{'comment'}\,$FORM{'weather'}\,\n";
			$value =~ s/<!--#(.|\n)*-->//ig;
			$line = $value;
		}
	}

	####書き込み######
	if (!open (DATA,">$logfile")) { &error(bad_file); }
	print DATA @DATA;
	close(NOTE);
}

########################################################
#エラー
########################################################
sub error {
	$error = $_[0];
	if ($error eq "bad_pass") {
		$msg[0] = "パスワードが違います。";
	}
	if ($error eq "bad_file") {
		$msg[0] = "ファイルがオープンできません。";
		$msg[1] = "ログ保存ファイル、『<b>$logfile</b>』 がないか、ファイルが開けません。";
	}
	if ($error eq "bad_edit") {
		$msg[0] = "編集・削除対象の記事がチェックされてません。";
		$msg[1] = "編集・削除したい記事のチェックボックスにチェックを入れてください。";
	}
	if ($error eq "bad_write"){
		if($bad_write[0] == 1) { $msg[0] = "日付が入力されていません。";}
		if($bad_write[1] == 1) { $msg[1] = "題名が入力されていません。";}
		if($bad_write[2] == 1) { $msg[2] = "コメントが入力されていません。";}
		if($bad_write[3] == 1) { $msg[3] = "お天気アイコンが選択されていません。";}
	}

	&header;
	print "<div align=\"center\"><br><br><br>\n";
	print "<p><font size=\"+1\"><b>error</b></font></p>\n";
	foreach $errormsg(@msg) {
		print "<p>$errormsg</p>\n";
	}
	print "<p><br><a href=$file>++ BACK ++</a></p>\n";
	print "</div>\n";
	&footer;
}

## --- カウンタ処理
sub counter {
	# 閲覧時のみカウントアップ
	$match=0;
	if ($FORM{'mode'} eq '') {
		# カウンタロック
		if ($lockkey) { &lock3; }

		$match=1;
	}

	# カウントファイルを読みこみ
	open(NO,"$cntfile") || &error("Can't open $cntfile",'0');
	$cnt = <NO>;
	close(NO);

	# カウントアップ
	if ($match) { $cnt++; }

	# 更新
	open(OUT,">$cntfile") || &error("Write Error : $cntfile");
	print OUT $cnt;
	close(OUT);

	# カウンタロック解除
	if (-e $cntlock) { unlink($cntlock); }

	# 桁数調整
	while(length($cnt) < $mini_fig) { $cnt = '0' . "$cnt"; }
	@cnts = split(//,$cnt);

	print "<DIV align=\"$cnt_pl\"><table><tr><td>\n";

	# GIFカウンタ表示
	if ($counter == 2) {
		foreach (0 .. $#cnts) {
			print "<img src=\"$gif_path/$cnts[$_]\.gif\" alt=\"$cnts[$_]\" width=\"$mini_w\" height=\"$mini_h\">";
		}

	# テキストカウンタ表示
	} else {
		print "<font color=\"$cnt_color\" face=\"verdana,Times New Roman,Arial\">$cnt</font>";
	}

	print "</td></tr></table></DIV>\n";
}
