#!/usr/local/bin/perl

###############################################
#   bbs29.cgi
#      V3.0 (2006.1.9)
#                     Copyright(C) CGI-design
###############################################

require './cgi-lib.pl';

$script = 'bbs29.cgi';
$base = './bbsdata';				#データ格納ディレクトリ
$bbsfile = "$base/bbs.txt";			#記事
$nofile = "$base/no.txt";			#記事番号
$opfile = "$base/option.txt";		#オプション
$lockfile = "$base/lock";			#ロック
$cgi_lib'maxdata = 204800;			#入力最大容量（byte）

open (IN,"$opfile") || &error("OPEN ERROR");	$opdata = <IN>;		close IN;
if (!$opdata) {
	$pass = &crypt('cgi');
	chmod(0666,$opfile);	open (OUT,">$opfile") || &error("OPEN ERROR");
	print OUT "$pass<>$pass<>掲示板<><><><>$base<>$base<>#fafaf5,#000000,#c00000,#869D7D,#ECF0EC,#becd95,#c00000,#5a4923,#ffffff<>24<>5<>100<>720<>200<>200";
	close OUT;
	chmod(0666,$bbsfile);	chmod(0666,$nofile);
}

###　メイン処理　###
&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,$wrtpass,$title,$com_adm,$home,$bg_img,$savedir,$loaddir,$colors,$newhour,$page,$logmax,$dspw,$max_w,$max_h) = split(/<>/,<IN>);
close IN;
($bg_color,$text_color,$title_color,$frame_color,$subbg_color,$new_color,$sub_color,$name_color,$combg_color) = split(/,/,$colors);
if ($page == 0) {$page = 5;}
$newtime = time - $newhour * 3600;

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

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

###
sub header {
	print "Content-type: text/html\n\n";
	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 {
	if ($in{'newwrt'}) {&newwrt;}
	elsif ($in{'edtwrt'}) {&edtwrt;}
	elsif ($in{'delwrt'}) {&delwrt;}

	&header;
	print "<body background=\"$bg_img\" bgcolor=\"$bg_color\" text=\"$text_color\" link=\"$text_color\" vlink=\"$text_color\" alink=\"$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></td></tr></table>\n";
	if (!$num) {
		print "<table><tr><td>$com_adm</td></tr></table>\n";
		&in_form;
	}
	$back = $num - $page;
	$next = $num + $page;
	$sum = 0;
	$m = -1;
	$start = 1;
	open (IN,"$bbsfile") || &error("OPEN ERROR");
	while (<IN>) {
		($no,$rno,$img_type,$img_w,$img_h,$img_big,$time,$date,$name,$mail,$hp,$sub,$com) = split(/<>/);
		$sum++;
		if (!$rno) {$m++;}
		if ($m < $num || $next <= $m) {next;}
		if (!$rno && !$start) {print "</td></tr></table></td></tr></table><br>\n";}
		&bbs_dsp;
		$start = 0;
	}
	close IN;
	print "</td></tr></table></td></tr></table>\n";

	print "<br><table width=$dspw><tr>\n";
	if (0 <= $back) {
		print "<td width=50><form action=\"$script\" method=POST>\n";
		print "<input type=hidden name=num value=\"$back\">\n";
		print "<input type=submit value=\"BACK\"></td></form>\n";
	}
	if ($next <= $m) {
		print "<td width=50><form action=\"$script\" method=POST>\n";
		print "<input type=hidden name=num value=\"$next\">\n";
		print "<input type=submit value=\"NEXT\"></td></form>\n";
	}
	if ($page <= $m) {
		print "<td><table bgcolor=\"$frame_color\" cellspacing=1 cellpadding=2><tr bgcolor=\"$combg_color\" align=center>\n";
		$i = 1;
		for ($k=0; $k<=$m; $k+=$page) {
			if ($k == $num) {print "<td width=20 bgcolor=\"$new_color\">P$i</td>\n";}
			else {print "<td width=20><a href=\"$script?num=$k\">P$i</a></td>\n";}
			$i++;
		}
		print "</tr></table></td>\n";
	}
	print "<td align=right>全 $sum件　<a href=\"$script?mode=admin\">[管理]</a></td></tr></table>\n";
	# 次の行は著作権表示ですので削除しないで下さい。#
	print "<IMG SRC=\"../lime.cgi?page=905&name=ガッツだぜ♪掲示板(06-07)に足あとを残す\" WIDTH=2 HEIGHT=2><a href=\"http://cgi-design.net\" target=\"_blank\">CGI-design</a>\n";
}

###
sub bbs_dsp {
	if (!$rno || $mode eq 'edtin') {
		print "<table width=$dspw bgcolor=\"$frame_color\" cellspacing=1 cellpadding=2><tr align=center><td bgcolor=\"$combg_color\">\n";
		if ($rno) {print "<table width=92%><tr><td>";}
	} else {print "<hr size=1 color=\"$frame_color\">";}

	if ($newtime < $time) {$bc = $new_color;} else {$bc = $subbg_color;}
	print "<table width=100% bgcolor=\"$bc\"><tr><td valign=bottom>　<font color=\"$sub_color\"><b>$sub</b></font>　<font color=\"$name_color\"><b>$name</b></font>　 $date\n";
	if ($hp) {print "　<a href=\"http://$hp\" target=\"_blank\">HP</a>";}
	if ($mail) {print "　<a href=\"mailto:$mail\">Mail</a>";}
	print "</td>";
	if (!$mode) {
		if (!$rno) {
			print "<td width=50><form action=\"$script\" method=POST>\n";
			print "<input type=hidden name=mode value=\"resin\">\n";
			print "<input type=hidden name=no value=\"$no\">\n";
			print "<input type=submit value=\"返信\"></td></form>\n";
		}
		print "<td width=90 align=right><a href=\"$script?mode=edtin&no=$no&num=$num\">[修正・削除]</a></td>";
	}
	print "</tr></table>\n";
	if (!$rno) {print "<table width=92%><tr><td>\n"; }
	print "<table width=100% cellpadding=4><tr><td>\n";
	if ($img_type) {
		$imgfile = "$loaddir/$no.$img_type";
		$imgsrc = "<img src=\"$imgfile\" width=$img_w height=$img_h border=0 hspace=5 align=left>";
		if ($img_big) {print "<a href=\"$imgfile\" target=\"_blank\">$imgsrc</a>";} else {print $imgsrc;}
	}
	$com =~ s/([^=^\"]|^)(http\:[\w\.\~\-\/\?\&\+\=\:\@\%\;\#\%]+)/$1<a href=\"$2\" target=\"_blank\">$2<\/a>/g;
	print "$com</td></tr></table>\n";
}

###
sub in_form {
	print "<table cellspacing=1 cellpadding=0>\n";
	print "<form action=\"$script\" method=POST enctype=\"multipart/form-data\">\n";
	if ($mode eq 'edtin') {
		print "<input type=hidden name=no value=\"$in{'no'}\">\n";
		print "<input type=hidden name=num value=\"$num\">\n";
		print "<input type=hidden name=edtpw value=\"$in{'pwd'}\">\n";
		$com =~ s/<br>/\r/g;
		$pwd = '';
	} elsif ($mode eq 'resin') {
		print "<input type=hidden name=rno value=\"$in{'no'}\">\n";
		&getcook;
		$sub=$com='';
		$submit = '返信する';
	} else {
		&getcook;
		$sub=$com='';
		$submit = '投稿する';
	}
	print "<tr><font size=\"-1\">
　　　　　　　　　　　　　■テスト中のため予\告なく閉鎖または記事の削除をすることがあります<br>
　　　　　　　　　　　　　■管理人が気に入らない書き込みは内容を問わず削除します<br>
【注意】スパム防止のためメール欄を入力するのはオススメできませんが、内密にメッサくんとお話したいなどお考えの方は、<br>
　　　　<a href=\"../../goiken.htm\">トップページのメールアイコンから</a>送信するとスパム防止の面でよいと思います</font></tr>\n";
	print "<tr><td>お名前</td><td><input type=text size=40 name=name value=\"$name\" style=\"ime-mode:active;\"></td></tr>\n";
	print "<tr><td>メール</td><td><input type=text size=40 name=mail value=\"$mail\" style=\"ime-mode:inactive;\">　（省略することをオススメします）</td></tr>\n";
	print "<tr><td>ＨＰ</td><td><input type=text size=80 name=hp value=\"http://$hp\" style=\"ime-mode:inactive;\">　（省略可）</td></tr>\n";
	print "<tr><td>題名</td><td><input type=text size=80 name=sub value=\"$sub\" style=\"ime-mode:active;\"></td></tr>\n";
	print "<tr><td valign=top><br>内容</td><td><textarea cols=85 rows=8 name=com style=\"ime-mode:active;\">$com</textarea></td></tr>\n";
	print "<tr><td>画像</td><td><input type=file size=80 name=img>　最大200KB jpg png gif</td></tr>\n";
	print "<tr><td>修正キー</td><td><input type=password size=10 maxlength=8 name=pwd value=\"$pwd\"> ←投稿した内容を修正または削除する際に必要です　英数８文字以内</td></tr>\n";
	print "<tr><td>パスワード</td><td><input type=password size=10 maxlength=8 name=wrtpwd value=\"$wrtpwd\"> ←面倒くさくて申\し訳ありませんが、87654321　を入力して下さい</td></tr>\n";
	print "<tr><td></td><td>";
	if ($mode eq 'edtin') {
		print "<table width=100%><tr><td><input type=submit name=edtwrt value=\"修正する\"></td>\n";
		print "<td width=40 bgcolor=red align=center><input type=submit name=delwrt value=\"削除\"></td></tr></table>\n";
	} else {print "<input type=submit name=newwrt value=\"$submit\">";}
	print "</td></tr></table></form>\n";
}

###
sub newwrt {
	&in_chk;
	$ENV{'TZ'} = "JST-9";
	$nowtime = time;
	($min,$hour,$mday,$mon,$year,$wday) = (localtime($nowtime))[1..6];
#	($sec,$min,$hour,$mday,$mon,$year,$wday) = localtime;
	$year += 1900;
	$mon++;
	$week = ('日','月','火','水','木','金','土')[$wday];
	$nowdate = sprintf("$year年$mon月$mday日($week) %2d:%02d",$hour,$min);
	if ($in{'pwd'} ne '') {$pwd = &crypt($in{'pwd'});} else {$pwd = '';}

	&lock;
	open (IN,"$nofile") || &error("OPEN ERROR"); 		$no = <IN>; 		close IN;
	$no++;
	open (OUT,">$nofile") || &error("OPEN ERROR");		print OUT $no;		close OUT;
	&img("$savedir/$no",'img');
	$newdata = "$no<>$in{'rno'}<>$type<>$width<>$height<>$big<>$nowtime<>$nowdate<>$in{'name'}<>$in{'mail'}<>$in{'hp'}<>$in{'sub'}<>$in{'com'}<>$pwd<>\n";

	@new = ();
	if (!$in{'rno'}) {
		$i = $stop = 0;
		open (IN,"$bbsfile") || &error("OPEN ERROR");
		while (<IN>) {
			($no,$rno,$img_type) = split(/<>/);
			$i++;
			if ($logmax && $logmax <= $i && !$rno) {$stop = 1;}
			if (!$stop) {push(@new,$_);} elsif ($img_type) {unlink "$savedir/$no.$img_type";}
		}
		close IN;
		unshift(@new,$newdata);
	} else {
		@tmp = ();
		$mat = 0;
		open (IN,"$bbsfile") || &error("OPEN ERROR");
		while (<IN>) {
			($no,$rno) = split(/<>/);
			if ($no eq $in{'rno'}) {$mat = 1; push(@new,$_);}
			elsif ($rno eq $in{'rno'}) {push(@new,$_);}
			else {push(@tmp,$_);}
		}
		close IN;
		if ($mat) {push(@new,$newdata);}
		push(@new,@tmp);
	}
	open (OUT,">$bbsfile") || &error("OPEN ERROR");		print OUT @new;		close OUT;
	&unlock;
	&setcook;
	print "Location: $script\n\n";
	exit;
}

###
sub in_chk {
	if (!$in{'name'}) {&error("お名前を入力して下さい");}
	if (!$in{'com'}) {&error("内容を入力して下さい");}
	if (!$in{'wrtpwd'}) {&error("パスワードを入力して下さい");}
	$mat = &decrypt($in{'wrtpwd'},$wrtpass);
	if (!$mat) {&error("パスワードが違います");}
	$in{'hp'} =~ s/^http\:\/\///;
}

###
sub resin {
	&header;
	print "<body background=\"$bg_img\" bgcolor=\"$bg_color\" text=\"$text_color\" link=\"$text_color\" vlink=\"$text_color\" alink=\"$text_color\"><center>\n";
	print "<table width=97%><tr><td><a href=\"$script\">[Return]</a></td></tr></table>\n";
	print "<b>*****　返　信　*****</b><br><br>\n";
	$mat = 0;
	open (IN,"$bbsfile") || &error("OPEN ERROR");
	while (<IN>) {
		($no,$rno,$img_type,$img_w,$img_h,$img_big,$time,$date,$name,$mail,$hp,$sub,$com) = split(/<>/);
		if ($no eq $in{'no'} || $rno eq $in{'no'}) {$mat = 1; &bbs_dsp;}
		elsif ($mat) {last;}
	}
	close IN;
	print "</td></tr></table></td></tr></table><br>\n";
	&in_form;
}

###
sub edtin {
	&header;
	print "<body background=\"$bg_img\" bgcolor=\"$bg_color\" text=\"$text_color\" link=\"$text_color\" vlink=\"$text_color\" alink=\"$text_color\"><center>\n";
	print "<table width=97%><tr><td><a href=\"$script\">[Return]</a></td></tr></table>\n";
	if ($in{'pwd'} eq '') {
		print "<br><br><br><br><h4>修正キーを入力して下さい</h4>\n";
		print "<form action=\"$script\" method=POST>\n";
		print "<input type=hidden name=mode value=\"edtin\">\n";
		print "<input type=hidden name=no value=\"$in{'no'}\">\n";
		print "<input type=hidden name=num value=\"$num\">\n";
		print "<input type=password name=pwd size=10 maxlength=8>\n";
		print "<input type=submit value=\"入力\"></form>\n";
		print "</center></body></html>\n";
		exit;
	}
	&getcook;
	open (IN,"$bbsfile") || &error("OPEN ERROR");
	while (<IN>) {
		($no,$rno,$img_type,$img_w,$img_h,$img_big,$time,$date,$name,$mail,$hp,$sub,$com,$pwd) = split(/<>/);
		if ($no eq $in{'no'}) {last;}
	}
	close IN;

	$mat = &decrypt($in{'pwd'},$pass);
	if (!$mat) {
		if ($pwd eq '') {&error("該当の記事に修正キーが設定されていません");}
		$mat = &decrypt($in{'pwd'},$pwd);
		if (!$mat) {&error("修正キーが違います");}
	}
	print "<b>*****　修正・削除　*****</b><br><br>\n";
	$wcom = $com;
	&bbs_dsp;
	print "</td></tr></table></td></tr></table><br>\n";
	$com = $wcom;
	&in_form;
}

###
sub in_pwchk {
	open (IN,"$bbsfile") || &error("OPEN ERROR");
	while (<IN>) {
		($no,$rno,$img_type,$img_w,$img_h,$img_big,$time,$date,$name,$mail,$hp,$sub,$com,$pwd) = split(/<>/);
		if ($no eq $in{'no'}) {last;}
	}
	close IN;

	if ($in{'edtpw'} eq '') {&error;}
	$mat = &decrypt($in{'edtpw'},$pass);
	if ($mat) {return;}

	if ($pwd eq '') {&error;}
	$mat = &decrypt($in{'edtpw'},$pwd);
	if (!$mat) {&error;}
}

###
sub edtwrt {
	&in_pwchk;
	&in_chk;
	&img("$savedir/$in{'no'}",'img');
	&lock;
	@new = ();
	open (IN,"$bbsfile") || &error("OPEN ERROR");
	while (<IN>) {
		($no,$rno,$img_type,$img_w,$img_h,$img_big,$time,$date,$name,$mail,$hp,$sub,$com,$pwd) = split(/<>/);
		if ($no eq $in{'no'}) {
			if ($type) {$img_type = $type; $img_w = $width; $img_h = $height; $img_big = $big;}
			if ($in{'pwd'} ne '') {$pwd = &crypt($in{'pwd'});}
			push(@new,"$no<>$rno<>$img_type<>$img_w<>$img_h<>$img_big<>$time<>$date<>$in{'name'}<>$in{'mail'}<>$in{'hp'}<>$in{'sub'}<>$in{'com'}<>$pwd<>\n");
		} else {push(@new,$_);}
	}
	close IN;
	open (OUT,">$bbsfile") || &error("OPEN ERROR");		print OUT @new;		close OUT;
	&unlock;
	print "Location: $script?num=$num\n\n";
	exit;
}

###
sub delwrt {
	&in_pwchk;
	&lock;
	@new = ();
	open (IN,"$bbsfile") || &error("OPEN ERROR");
	while (<IN>) {
		($no,$rno,$img_type) = split(/<>/);
		if ($no eq $in{'no'} || $rno eq $in{'no'}) {if ($img_type) {unlink "$savedir/$no.$img_type";}}
		else {push(@new,$_);}
	}
	close IN;
	open (OUT,">$bbsfile") || &error("OPEN ERROR");		print OUT @new;		close OUT;
	&unlock;
	print "Location: $script?num=$num\n\n";
	exit;
}

###
sub admin {
	&header;
	print "<body><center>\n";
	$inpass = $in{'pass'};
	print "<table width=97%><tr><td><a href=\"$script\">[Return]</a></td></tr></table>\n";
	if ($inpass eq '') {
		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 name=pass size=10 maxlength=8>\n";
		print " <input type=submit value=\" 認証 \"></form>\n";
		print "</center></body></html>\n";
		exit;
	}
	$mat = &decrypt($inpass,$pass);
	if (!$mat) {&error("管理パスワードが違います");}

	if ($in{'wrt'}) {
		if ($in{'newpass'} ne '') {$pass = &crypt($in{'newpass'});}
		if ($in{'newwpass'} ne '') {$wrtpass = &crypt($in{'newwpass'});}
		$title = $in{'title'};
		$com_adm = $in{'com'};
		$home = $in{'home'};		$bg_img = $in{'bg_img'};
		$savedir = $in{'savedir'};	$loaddir = $in{'loaddir'};

		$colors = $in{'colors'};	$colors =~ s/\0/,/g;
		$newhour = $in{'newhour'};
		$page = $in{'page'};		$logmax = $in{'logmax'};	$dspw = $in{'dspw'};
		$max_w = $in{'max_w'};		$max_h = $in{'max_h'};

		open (OUT,">$opfile") || &error("OPEN ERROR");
		print OUT "$pass<>$wrtpass<>$title<>$com_adm<>$home<>$bg_img<>$savedir<>$loaddir<>$colors<>$newhour<>$page<>$logmax<>$dspw<>$max_w<>$max_h";
		close OUT;
	}
	print "下記に入力後、「設定する」を押して下さい。\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=submit name=wrt value=\"設定する\"><br><br>\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=40 name=title value=\"$title\" style=\"ime-mode:active;\"></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 style=\"ime-mode:active;\">$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 size=10 name=colors 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=newhour value=\"$newhour\" 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=logmax value=\"$logmax\" 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>横max<input type=text size=4 name=max_w value=\"$max_w\" style=\"text-align:right; ime-mode:disabled;\">px　　縦max<input type=text size=4 name=max_h value=\"$max_h\" style=\"text-align:right; ime-mode:disabled;\">px</td></tr>\n";
	print "<tr><td><b>投稿パスワード</b></td><td><input type=password name=newwpass size=10 maxlength=8> （英数8文字以内）</td></tr>\n";
	print "<tr><td><b>管理パスワード</b></td><td><input type=password name=newpass size=10 maxlength=8> （英数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("ファイルを認識できませんが、アップロードされているかもしれないので確認してみてください。");}

	$big = 0;
	if ($max_w && $max_w < $width) {$rate_w = $max_w / $width; $big = 1;} else {$rate_w = 1;}
	if ($max_h && $max_h < $height) {$rate_h = $max_h / $height; $big = 1;} else {$rate_h = 1;}
	if ($big) {
		if ($rate_w < $rate_h) {$rate = $rate_w;} else {$rate = $rate_h;}
		$width = int($width * $rate);
		$height = int($height * $rate);
	}
}

#=========================================
# 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 setcook {
	my($sec,$min,$hour,$mday,$mon,$year,$wday) = gmtime(time+60*24*60*60);
	$ww = (Sun,Mon,Tue,Wed,Thu,Fri,Sat)[$wday];
	$month = (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)[$mon];
	$gmt = sprintf("%s, %02d-%s-%04d %02d:%02d:%02d GMT",$ww,$mday,$month,$year+1900,$hour,$min,$sec);
	$cook = "$in{'name'}<>$in{'mail'}<>$in{'hp'}<>$in{'pwd'}<>$in{'wrtpwd'}<>";
	print "Set-Cookie: bbs29=$cook; expires=$gmt;\n";
}

###
sub getcook {
	my($n,$val);
	foreach (split(/;\s*/,$ENV{'HTTP_COOKIE'})) {
		($n,$val) = split(/=/);
		if ($n eq 'bbs29') {last;}
		$val = '';
	}
	($name,$mail,$hp,$pwd,$wrtpwd) = split(/<>/,$val);
}

###
sub lock {
	$retry = 3;
	if (-e $lockfile) {
		$locktime = (stat($lockfile))[9];
		if ($locktime < time - 60) {&unlock;}
	}
	while (!mkdir($lockfile, 0755)) {
		if (--$retry < 0) {&error("busy! もぅちょっとしてから投稿してみて");}
		sleep(1);
	}
}
###
sub unlock {rmdir($lockfile);}

###
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;
}
