#!/usr/bin/perl

###############################################
#   view.cgi
#      V1.0 (2009.2.16)
#                     Copyright(C) CGI-design
###############################################

require './cgi-lib.pl';

$script = 'view.cgi';
$base = './viewdata';				#データ格納ディレクトリ
$viewfile = "$base/view.txt";		#記事
$nofile = "$base/no.txt";			#記事番号
$opfile = "$base/option.txt";
$cgi_lib'maxdata = 200000;			#入力最大容量（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<>http://handle-marche.com/top.css<>$base<>$base<>155<>155<>4";
	close OUT;
	chmod(0666,$viewfile);	chmod(0666,$nofile);
}

###　メイン処理　###
&ReadParse;
$mode = $in{'mode'};

open (IN,"$opfile") || &error("OPEN ERROR");
($pass,$style,$savedir,$loaddir,$max_w,$max_h,$cols) = split(/<>/,<IN>);
close IN;

if ($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><link rel=\"stylesheet\" type=\"text/css\" href=\"$style\"></head>\n";
	$head = 1;
}

###
sub main {
	&header;
	print "<body style=\"background-image: url();\"><center>\n";
	&list;
}

###
sub list {
	if ($cols == 0) {$cols = 4;}
	$perw = int(100 / $cols);
	$k = 0;
	print "<table width=100%>\n";
	open (IN,"$viewfile") || &error("OPEN ERROR");
	while (<IN>) {
		($no,$imgt,$imgw,$imgh,$sub,$url) = split(/<>/);
		if (!$k) {print "<tr align=center valign=top>";}
		print "<td width=$perw%>";
		if ($mode eq 'admin') {print "<br><input type=submit name=$no value=\"修正\"><br>\n";}
		print "<a href=\"$url\" target=\"_parent\"><img src=\"$loaddir/$no.$imgt\" width=$imgw height=$imgh border=0 vspace=2></a><br><div class=\"osusumelink\"><a href=\"$url\" target=\"_parent\">$sub</a></div></td>\n";
		$k++;
		if ($k == $cols) {print "</tr>\n"; $k = 0;}
	}
	close IN;

	if ($k) {
		for ($k+1 .. $cols) {print "<td width=$perw%></td>";}
		print "</tr>";
	}
	print "</table>\n";
}

###
sub admin {
	&header;
	print "<body style=\"background-image: url();\"><center>\n";
	$inpass = $in{'pass'};
	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 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 "<table width=95% bgcolor=\"#8c4600\"><tr><td>　<a href=\"$script?mode=admin\"><font color=\"#ffffff\"><b>ログアウト</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 "<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 "<hr width=720>修正、削除する場合は「修正」をクリックして下さい。\n";

	print "<table width=720><tr><td>\n";
	&list;
	print "</td></tr></table></form>\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,"$viewfile") || &error("OPEN ERROR");
		while (<IN>) {
			($no,$imgt,$imgw,$imgh,$sub,$url) = split(/<>/);
			if ($in{$no}) {last;}
		}
		close IN;
		print "<input type=hidden name=no value=\"$no\">\n";
		$sub =~ s/<br>/\r/g;
	} else {
		$sub=$url='';
	}
	print "<table bgcolor=\"#e6e4ce\" cellspacing=10><tr><td><table cellspacing=1 cellpadding=0>\n";
	print "<tr><td>商品名</td><td><textarea cols=30 rows=2 name=sub style=\"ime-mode:active;\">$sub</textarea></td></tr>\n";
	print "<tr><td>リンク先</td><td><input type=text size=70 name=url value=\"$url\" style=\"ime-mode:inactive;\"></td></tr>\n";
	print "<tr><td>画像</td><td><input type=file size=70 name=img></td></tr>\n";
	print "<tr><td></td><td>";
	if ($in{'edt'}) {
		print "<table width=200><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></table></td></tr></table></form>\n";
}

###
sub newwrt {
	$in{'sub'} =~ s/\r\n|\r|\n/<br>/g;
	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');
	open (IN,"$viewfile") || &error("OPEN ERROR");		@new = <IN>;		close IN;
	unshift(@new,"$no<>$type<>$width<>$height<>$in{'sub'}<>$in{'url'}<>\n");
	open (OUT,">$viewfile") || &error("OPEN ERROR");	print OUT @new;		close OUT;
}

###
sub edtwrt {
	$in{'sub'} =~ s/\r\n|\r|\n/<br>/g;
	&img("$savedir/$in{'no'}",'img');

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

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

###
sub setup {
	if ($in{'wrt'}) {
		if ($in{'newpass'} ne '') {$pass = &crypt($in{'newpass'});}
		$style = $in{'style'};
		$savedir = $in{'savedir'};		$loaddir = $in{'loaddir'};
		$max_w = $in{'max_w'};			$max_h = $in{'max_h'};			$cols = $in{'cols'};

		open (OUT,">$opfile") || &error("OPEN ERROR");
		print OUT "$pass<>$style<>$savedir<>$loaddir<>$max_w<>$max_h<>$cols";
		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 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=style value=\"$style\"></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><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　　<input type=text size=2 name=cols value=\"$cols\" style=\"text-align:right; ime-mode:disabled;\">列</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("ファイルを認識できません");}

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