#!/usr/local/bin/perl

###############################################
#   col3.cgi
#      V2.2 (2010.10.3)
#                     Copyright(C) CGI-design
###############################################

require './cgi-lib.pl';

$script = 'topics_img.cgi';
$base = '../topics_img';				#データ格納ディレクトリ
$colfile = "$base/topics_img.txt";			#記事
$opfile = "$base/option.txt";
$cgi_lib'maxdata = 1000000;			#入力最大容量（byte）

open (IN,"$opfile") || &error("OPEN ERROR");	$opdata = <IN>;		close IN;
if (!$opdata) {
	$pass = &crypt('123456');
	chmod(0666,$opfile);	open(OUT,">$opfile") || &error("OPEN ERROR");
	print OUT "$pass<>インフォメーション・更新情報<><><><>$base/img<>$base/img<>#ffffff,#333333,#3366FF,#0000FF<>10<><>250";
	close OUT;
	chmod(0666,$colfile);
}

###　メイン処理　###
&ReadParse;
while (($n,$val) = each %in) {
	if ($n eq 'img') {next;}
	$val =~ s/&/&amp;/g;	$val =~ s/</&lt;/g;		$val =~ s/>/&gt;/g;		$val =~ s/"/&quot;/g;	$val =~ s/\r\n|\r|\n/<br>/g;
	$in{$n} = $val;
}
$mode = $in{'mode'};
$num = $in{'num'};

open (IN,"$opfile") || &error("OPEN ERROR");
($pass,$title,$com_adm,$home,$bg_img,$savedir,$loaddir,$colors,$page,$dspw,$max_wh) = split(/<>/,<IN>);
close IN;
($bg_color,$text_color,$title_color,$sub_color) = split(/,/,$colors);
if ($page == 0) {$page = 20;}

if ($mode eq 'dsp') {&dsp;}
elsif ($mode eq 'admin') {&admin;}
else {&main;}

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

###ヘッダ
sub header {
	print "Content-type: text/html\n\n";

	print <<"EOM";
<!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">
<title>$title</title>
<link rel="stylesheet" type="text/css" href="$base/style.css">
</head>
EOM
#	print "<html><head><META HTTP-EQUIV=\"Content-type\" CONTENT=\"text/html; charset=Shift_JIS\">\n";
#	print "<title>$title</title><link rel=\"stylesheet\" type=\"text/css\" href=\"$loaddir/style.css\"></head>\n";

	$head = 1;
}

###トップページ
sub main {
	&header;
	print "<body bgcolor=\"$bg_color\" text=\"$text_color\">\n";
#	print "<body background=\"$bg_img\" bgcolor=\"$bg_color\" text=\"$text_color\"><center>\n";

#	print "<table width=98%><tr><td width=80 valign=top>";
#	if ($home) {print "<a href=\"$home\">HOME</a>";}
#	print "</td><td align=center><font color=\"$title_color\" size=\"+1\"><b>$title</b></font></td><td width=80 align=right><a href=\"$script?mode=admin\">[管理]</a></td></tr></table>\n";
#	print "<table><tr><td>$com_adm</td></tr></table>\n";

	&list;

	print <<"EOM";
<table class="list">
<tr>
<td class="page">
EOM
	if (0 <= $back) {print "<a href=\"$script?num=$back\">&lt;&lt;BACK</a>　";}
	if ($next <= $m) {print "<a href=\"$script?num=$next\">NEXT&gt;&gt;</a>";}
	print <<"EOM";
</td>
<td class="page"><div align="right"><a href="$script?mode=admin" target="_blank">＿</a></div></td>
</tr>
</table>
EOM
#	print "<div style=\"margin-top:8px;\"></div>\n";
#	if (0 <= $back) {print "<a href=\"$script?num=$back\">&lt;&lt; 前ページ</a>　　";}
#	print "全 ",$m+1,"件　　";
#	if ($next <= $m) {print "<a href=\"$script?num=$next\">次ページ &gt;&gt;</a>";}

}

###トップのリスト
sub list {
	$back = $num - $page;
	$next = $num + $page;
	$m = -1;
	print "<table class=\"list\">\n";
#	print "<table width=$dspw cellspacing=0 cellpadding=0>\n";
	open (IN,"$colfile") || &error("OPEN ERROR");
	while (<IN>) {
		$m++;
		if ($m < $num || $next <= $m) {next;}
		($no,$date,$sub) = split(/<>/);

		print "<tr>\n";
#		print "<tr valign=bottom><td height=24 style=\"border-bottom:1px dotted $text_color;\">";

		if ($mode eq 'admin') {
		print "<td class=\"fixed\"><input type=submit name=$no value=\"修正\"></td>\n";
#		print "<input type=submit name=$no value=\"修正\"> ";
		 $tar = ' target="_blank"';} else {$tar = '';}

	print <<"EOM";
<th nowrap><font color="$title_color">■&nbsp;</font>$date</th>
<td><a href="$script?mode=dsp&no=$no&num=$num" onclick="window.open('$script?mode=dsp&no=$no&num=$num', '', 'scrollbars=yes,width=700,height=750'); return false;"><font color="$sub_color">$sub</font></a></td>
</tr>
EOM
#		print "<a href=\"$script?mode=dsp&no=$no&num=$num\"$tar>■$sub</a></td>\n";
#		print "<td width=80 style=\"border-bottom:1px dotted $text_color;\">$date</td></tr>\n";

	}
	close IN;
	print "</table>\n";
}

###記事表示
sub dsp {
	&header;
	print "<body bgcolor=\"$bg_color\" text=\"$text_color\">\n";
	print "<center>\n";
#	print "<body background=\"$bg_img\" bgcolor=\"$bg_color\" text=\"$text_color\"><center>\n";
#	print "<table width=97%><tr><td><a href=\"$script?num=$num\">戻る</a></td></tr></table>\n";
	open (IN,"$colfile") || &error("OPEN ERROR");
	while (<IN>) {
		($no,$date,$sub,$com,$imgt,$imgw,$imgh) = split(/<>/);
		if ($no eq $in{'no'}) {last;}
	}
	close IN;
	$com =~ s/([^=^\"]|^)(https?\:[\w\.\~\-\/\?\&\+\=\:\@\%\;\#\%]+)/$1<a href="$2" target="_blank">$2<\/a>/g;

	print <<"EOM";
<img src="$base/topics_title.jpg" alt="インフォメーション・更新情報" width="660" height="106">
<table class="dsp">
<tr>
<td><p class="date">$date</p>
<p class="title">$sub</p>
<p>
EOM
	if ($imgt) {
	print "<img src=\"$loaddir/$no.$imgt\" width=$imgw height=$imgh border=0 align=right>";
	}

	print <<"EOM";
$com</p></td>
</tr>
</table>
<br>
<a href="JavaScript:window.close()">【×閉じる】</a>
</center>
EOM


#	print "<table width=$dspw cellspacing=0 cellpadding=0>\n";
#	print "<tr><td><font color=\"$sub_color\" size=\"+1\"><b>■ $sub</b></font></td><td align=right valign=bottom nowrap>$date</td></tr>\n";
#	print "<tr><td colspan=2><hr size=1>\n";
#	if ($imgt) {
#	print "<a href=\"$loaddir/$no.$imgt\" target=\"_blank\"><img src=\"$loaddir/$no.$imgt\" width=$imgw height=$imgh border=0 hspace=7 align=right></a>";
#	}
#	print "$com<br clear=right><br><hr size=1></td></tr></table>\n";
}

###管理画面
sub admin {
	&header;
	print "<body><center>\n";
	$inpass = $in{'pass'};
	if ($inpass eq '') {

	print <<"EOM";
<table class="admin_top">
<tr>
<td><a href="../index.html"><font color="#FFFFFF">【トップページへ】</font></a>　<a href="$script"><font color="#FFFFFF">【更新履歴一覧へ】</font></a></td>
</tr>
</table>
<br><br><br><br>
<h4>パスワードを入力して下さい</h4>
<form action="$script" method="POST">
<input type=hidden name=mode value="admin">
<input type=password size=10 maxlength=8 name=pass>
<input type=submit value=" 認証 ">
</form>
</center>
</body>
</html>
EOM

#		print "<table width=97%><tr><td><a href=\"$script\">戻る</a></td></tr></table>\n";
#		print "<br><br><br><br><h4>パスワードを入力して下さい</h4>\n";
#		print "<form action=\"$script\" method=POST>\n";
#		print "<input type=hidden name=mode value=\"admin\">\n";
#		print "<input type=password size=10 maxlength=8 name=pass>\n";
#		print "<input type=submit value=\" 認証 \"></form>\n";
#		print "</center></body></html>\n";

		exit;
	}
	$mat = &decrypt($inpass,$pass);
	if (!$mat) {&error("パスワードが違います");}


	print <<"EOM";
<table class="admin_top">
<tr>
<td><a href="../index.html"><font color="#FFFFFF">【トップページへ】</font></a>　<a href="$script"><font color="#FFFFFF">【更新履歴一覧へ】</font></a></td>
<form action=\"$script\" method=POST>
<td class="bota">
<input type=hidden name=mode value="admin">
<input type=hidden name=pass value="$inpass">
<input type=submit value="新規/修正">&nbsp;
<input type=submit name=set value="基本設定">
</td>
</form>
</table>
<br>
EOM

#	print "<table width=95% bgcolor=\"#8c4600\"><tr><td>　<a href=\"$script\"><font color=\"#ffffff\"><b>Return</b></font></a></td>\n";
#	print "<form action=\"$script\" method=POST><td align=right>\n";
#	print "<input type=hidden name=mode value=\"admin\">\n";
#	print "<input type=hidden name=pass value=\"$inpass\">\n";
#	print "<input type=submit value=\"記事編集\">\n";
#	print "<input type=submit name=set value=\"基本設定\"></td></form><td width=10></td></tr></table><br>\n";

	if ($in{'set'}) {&setup;} else {&edtin;}
}

###リスト表示
sub edtin {
	if ($in{'newwrt'}) {&newwrt;}
	elsif ($in{'edtwrt'}) {&edtwrt;}
	elsif ($in{'delwrt'}) {&delwrt;}

	&in_form;
	print "<hr width=650>修正、削除する場合は「修正」をクリックして下さい。<br><br>\n";
	print "<form action=\"$script\" method=POST>\n";
	print "<input type=hidden name=mode value=\"admin\">\n";
	print "<input type=hidden name=pass value=\"$inpass\">\n";
	print "<input type=hidden name=edt value=\"1\">\n";
	print "<input type=hidden name=num value=\"$num\">\n";
	&list;
	print "</form>\n";

	print "<table><tr>";
	if (0 <= $back) {
		print "<form action=\"$script\" method=POST><td>\n";
		print "<input type=hidden name=mode value=\"admin\">\n";
		print "<input type=hidden name=pass value=\"$inpass\">\n";
		print "<input type=hidden name=num value=\"$back\">\n";
		print "<input type=submit value=\"前ページ\"></td></form>\n";
	}
	print "<td width=60 align=center>全 ",$m+1,"件</td>\n";
	if ($next <= $m) {
		print "<form action=\"$script\" method=POST><td>\n";
		print "<input type=hidden name=mode value=\"admin\">\n";
		print "<input type=hidden name=pass value=\"$inpass\">\n";
		print "<input type=hidden name=num value=\"$next\">\n";
		print "<input type=submit value=\"次ページ\"></td></form>\n";
	}
	print "</tr></table>\n";
}

###フォーム
sub in_form {
	print "<form action=\"$script\" method=POST enctype=\"multipart/form-data\">\n";
	print "<input type=hidden name=mode value=\"admin\">\n";
	print "<input type=hidden name=pass value=\"$inpass\">\n";
	if ($in{'edt'}) {
		open (IN,"$colfile") || &error("OPEN ERROR");
		while (<IN>) {
			($no,$date,$sub,$com) = split(/<>/);
			if ($in{$no}) {last;}
		}
		close IN;
		print "<input type=hidden name=no value=\"$no\">\n";
		print "<input type=hidden name=num value=\"$num\">\n";
		$com =~ s/<br>/\r/g;
	} else {
		($sec,$min,$hour,$mday,$mon,$year) = localtime;
		$date = sprintf("%4d年%d月%d日",$year+1900,++$mon,$mday);
#		$date = sprintf("%4d.%2d.%2d",$year+1900,++$mon,$mday);
		$sub = $com = '';
	}

	print <<"EOM";
<table class="form">
<tr>
<th>日付</th>
<td><input type=text size=20 name=date value="$date" style="ime-mode:inactive;"></td>
</tr>
<tr>
<th>題名</th>
<td><input type=text size=60 name=sub value="$sub" style="ime-mode:active;"></td>
</tr>
<tr>
<th valign=top>内容</th>
<td><textarea cols=70 rows=20 name=com style="ime-mode:active;">$com</textarea></td>
</tr>
<tr>
<th>画像</th>
<td><input type=file size=60 name=img></td>
</tr>
<tr><td>&nbsp;</td><td>
EOM

#	print "<table bgcolor=\"#e6e4ce\" cellspacing=10><tr><td><table cellspacing=1 cellpadding=0>\n";
#	print "<tr><td>日付&nbsp;</td><td><input type=text size=20 name=date value=\"$date\" style=\"ime-mode:inactive;\"></td></tr>\n";
#	print "<tr><td>題名</td><td><input type=text size=60 name=sub value=\"$sub\" style=\"ime-mode:active;\"></td></tr>\n";
#	print "<tr><td valign=top><br>内容</td><td><textarea cols=80 rows=20 name=com style=\"ime-mode:active;\">$com</textarea></td></tr>\n";
#	print "<tr><td>画像</td><td><input type=file size=60 name=img></td></tr>\n";
#	print "<tr><td></td><td>\n";


	if ($in{'edt'}) {

		print "<input type=submit name=edtwrt value=\"修正する\">　　　　&nbsp;\n";
		print "<span class=\"kakomi\">　<input type=submit name=delwrt value=\"削除\">　</span>\n";

#		print "<table width=100%><tr><td><input type=submit name=edtwrt value=\"修正する\"></td>\n";
#		print "<td width=40 bgcolor=red><input type=submit name=delwrt value=\"削除\"></td></tr></table>\n";
	} else {
		print "<input type=submit name=newwrt value=\"新規登録\">";
	}

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

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

###
sub newwrt {
	open (IN,"$colfile") || &error("OPEN ERROR");		@new = <IN>;		close IN;
	($no) = split(/<>/,$new[0]);
	$no++;
	&img("$savedir/$no",'img');
	unshift(@new,"$no<>$in{'date'}<>$in{'sub'}<>$in{'com'}<>$type<>$width<>$height<>\n");
	open (OUT,">$colfile") || &error("OPEN ERROR");		print OUT @new;		close OUT;
}


###
sub edtwrt {
	&img("$savedir/$in{'no'}",'img');
	@new = ();
	open (IN,"$colfile") || &error("OPEN ERROR");
	while (<IN>) {
		($no,$date,$sub,$com,$imgt,$imgw,$imgh) = split(/<>/);
		if ($no eq $in{'no'}) {
			if ($type) {$imgt = $type; $imgw = $width; $imgh = $height;}
			push(@new,"$no<>$in{'date'}<>$in{'sub'}<>$in{'com'}<>$imgt<>$imgw<>$imgh<>\n");
		} else {push(@new,$_);}
	}
	close IN;
	open (OUT,">$colfile") || &error("OPEN ERROR");		print OUT @new;		close OUT;
}

###
sub delwrt {
	@new = ();
	open (IN,"$colfile") || &error("OPEN ERROR");
	while (<IN>) {
		($no,$date,$sub,$com,$imgt) = split(/<>/);
		if ($no eq $in{'no'}) {if ($imgt) {unlink "$savedir/$no.$imgt";}} else {push(@new,$_);}
	}
	close IN;
	open (OUT,">$colfile") || &error("OPEN ERROR");		print OUT @new;		close OUT;
}

###設定フォーム
sub setup {
	if ($in{'wrt'}) {
		if ($in{'newpass'} ne '') {$pass = &crypt($in{'newpass'});}
		$title = $in{'title'};
		$com_adm = $in{'com_adm'};
		$home = $in{'home'};		$bg_img = $in{'bg_img'};
		$savedir = $in{'savedir'};	$loaddir = $in{'loaddir'};
		$colors = $in{'colors'};	$colors =~ s/\0/,/g;
		$page = $in{'page'};		$dspw = $in{'dspw'};
		$max_wh = $in{'max_wh'};

		open (OUT,">$opfile") || &error("OPEN ERROR");
		print OUT "$pass<>$title<>$com_adm<>$home<>$bg_img<>$savedir<>$loaddir<>$colors<>$page<>$dspw<>$max_wh";
		close OUT;
	}
	print "下記に入力後、「設定する」を押して下さい。<br><br>\n";
	print "<form action=\"$script\" method=POST>\n";
	print "<input type=hidden name=mode value=\"admin\">\n";
	print "<input type=hidden name=pass value=\"$inpass\">\n";
	print "<input type=hidden name=set value=\"1\">\n";
	print "<input type=submit name=wrt value=\"設定する\"><br><br>\n";

	print "<table border=0 cellpadding=10 cellspacing=0 bgcolor=\"#E6E6E6\"><tr><td><table class=\"setup\">\n";
#	print "<table bgcolor=\"#dddddd\" cellspacing=10><tr><td><table cellspacing=1 cellpadding=0>\n";
	print "<tr><td><b>タイトル</b></td><td><input type=text size=60 name=title value=\"$title\"></td></tr>\n";
	$com_adm =~ s/<br>/\r/g;
#	print "<tr><td valign=top><br><b>コメント</b></td><td><textarea cols=60 rows=6 name=com_adm>$com_adm</textarea></td></tr>\n";
#	print "<tr><td><b>ホームURL</b></td><td><input type=text size=60 name=home value=\"$home\"></td></tr>\n";
#	print "<tr><td><b>壁紙</b></td><td><input type=text size=60 name=bg_img value=\"$bg_img\"></td></tr>\n";
	print "<tr><td><b>画像格納ディレクトリ</b></td><td><input type=text size=60 name=savedir value=\"$savedir\"></td></tr>\n";
	print "<tr><td><b>画像読出ディレクトリ</b></td><td><input type=text size=60 name=loaddir value=\"$loaddir\"></td></tr>\n";

	print "<tr><td></td><td><a href=\"$loaddir/color.htm\" target=\"_blank\">カラーコード</a></td></tr>\n";
	@name = ('基本背景色','基本文字色','タイトル色','題名色');
	@colors = split(/,/,$colors);
	for (0 .. $#name) {
		print "<tr><td><b>$name[$_]</b></td><td><table cellspacing=0 cellpadding=0><tr>\n";
		print "<td><input type=text name=colors size=10 value=\"$colors[$_]\" style=\"ime-mode:inactive;\"></td>\n";
		print "<td width=5></td><td width=80 bgcolor=\"$colors[$_]\"></td></tr></table></td></tr>\n";
	}
	print "<tr><td><b>記事表\示</b></td><td><input type=text size=4 name=page value=\"$page\" style=\"text-align:right; ime-mode:disabled;\">件/ページ　　</td></tr>\n";
#	print "<tr><td><b>記事表\示</b></td><td><input type=text size=4 name=page value=\"$page\" style=\"text-align:right; ime-mode:disabled;\">件/ページ　　表\示幅<input type=text size=4 name=dspw value=\"$dspw\" style=\"text-align:right; ime-mode:disabled;\">px</td></tr>\n";
	print "<tr><td><b>画像表\示</b></td><td><input type=text size=4 name=max_wh value=\"$max_wh\" style=\"text-align:right; ime-mode:disabled;\">px</td></tr>\n";
	print "<tr><td><b>パスワード変更</b></td><td><input type=password size=10 maxlength=8 name=newpass> （英数8文字以内）</td></tr>\n";
	print "</table></td></tr></table></form>\n";
}

###
sub img {
	$type=$width=$height=$big=$mac='';
	$imgdata = $in{"$_[1]"};
	if (!$imgdata) {return;}

	foreach (@in) {
		if (/$_[1]/ and /Content-Type:(.+)/i) {
			if ($1 =~ /image\/.*jpeg/i) {$type = 'jpg';}
			elsif ($1 =~ /image\/gif/i) {$type = 'gif';}
			elsif ($1 =~ /image\/.*png/i) {$type = 'png';}
		}
		if (/application\/x-macbinary/i) {$mac = 1;}
	}
	if (!$type) {&error("このファイルはアップロードできません");}

	if ($mac) {
		$leng = substr($imgdata,83,4);
		$leng = unpack("%N",$leng);
		$imgdata = substr($imgdata,128,$leng);
	}
	$img_file = "$_[0].$type";
	open (IMG,">$img_file") || &error("$img_fileファイルを作成できません");
	binmode IMG;
	print IMG $imgdata;
	close IMG;
	chmod (0666,$img_file);

	($t,$width,$height) = &getImageSize("$img_file");
	if (!$width || !$height) {&error("ファイルを認識できません");}

	if ($max_wh && ($max_wh < $width || $max_wh < $height)) {
		if ($height < $width) {$height = int($height * $max_wh / $width); $width = $max_wh;}
		else {$width = int($width * $max_wh / $height); $height = $max_wh;}
		$big = 1;
	}
}

#=========================================
# Get Image Pixel Size.（出典：stdio-902）
#=========================================
sub getImageSize {
	local($file_name) = @_;
	local($head);

	return if (!open IMG, $file_name);
	binmode IMG;
	read IMG, $head, 8;
	if ($head eq "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a") {
		local($width, $height);
		if (read(IMG, $head, 4) != 4 || read(IMG, $head, 4) != 4 || $head ne 'IHDR') {
			close IMG;
			return "PNG", 0;
		}
		read IMG, $head, 8;
		close IMG;
		$width = unpack "N", substr($head, 0, 4);
		$height = unpack "N", substr($head, 4, 4);
		return "PNG", $width, $height;
	}
	$head = substr $head, 0, 3;
	if ($head eq "\x47\x49\x46") {
		local($head, $width, $height);
		seek IMG, 6, 0;
		read IMG, $head, 4;
		close IMG;
		($width, $height) = unpack "vv", $head;
		return "GIF", $width, $height;
	}
	$head = substr $head, 0, 2;
	if ($head eq "\xff\xd8") {
		local($head, $width, $height, $w1, $w2, $h1, $h2, $l1, $l2, $length);
		seek IMG, 2, 0;
		while (read IMG, $head, 1) {
			last if ($head eq "");
			if ($head eq "\xff") {
				$head = getc IMG;
				if ($head =~ /^[\xc0-\xc3\xc5-\xcf]$/) {
					seek IMG, 3, 1;
					last if (read(IMG, $head, 4) != 4);
					close IMG;
					($h1, $h2, $w1, $w2) = unpack "C4", $head;
					$height = $h1 * 256 + $h2;
					$width  = $w1 * 256 + $w2;
					return "JPG", $width, $height;
				} elsif ($head eq "\xd9" || $head eq "\xda") {
					last;
				} else {
					last if (read(IMG, $head, 2) != 2);
					($l1, $l2) = unpack "CC", $head;
					$length = $l1 * 256 + $l2;
					seek IMG, $length - 2, 1;
				}
			}
		}
		close IMG;
		return "JPG", 0;
	}
	return 0;
}

###
sub crypt {
	@salt = ('a' .. 'z','A' .. 'Z','0' .. '9');
	srand;
	$salt = "$salt[int(rand($#salt))]$salt[int(rand($#salt))]";
	return crypt($_[0],$salt);
}

###
sub decrypt {
	$salt = $_[1] =~ /^\$1\$(.*)\$/ && $1 || substr($_[1],0,2);
	if (crypt($_[0],$salt) eq $_[1] || crypt($_[0],'$1$' . $salt) eq $_[1]) {return 1;}
	return 0;
}

###
sub error {
	if (!$head) {&header; print "<body><center>\n";}
	print "<br><br><br><br><h3>ERROR !!</h3><font color=red><b>$_[0]</b></font>\n";
	print "</center></body></html>\n";
	exit;
}
