#!/usr/local/bin/perl5

## Web Protect v3.02
## Copyright (c) KentWeb

# 外部ファイル取り込み
require './init.cgi';

# 基本処理定義
$buf = &decode;
if (!$buf) { &enter; }
if ($in{'gif'} || $in{'jpeg'} || $in{'pdf'} || $in{'excel'}) { &binOut; }
elsif ($page eq 'top') { &pageTop; }
elsif ($mode eq "check") { &check; }
&pwCheck;

#------------#
#  認証処理  #
#------------#
sub pwCheck {
	local($f,$id,$pw,$check,$time);

	# クッキー格納
	if ($mode eq 'enter') {
		$time = time;
		if ($in{'cook'} eq "") { $in{'cook'} = 0; }
		&set_cookie($in{'cook'}, $time);
	}

	# パスファイルを開く
	$f=0;
	open(IN,"$prvdir/$pwdfile") || &error("Open Error: $pwdfile");
	while (<IN>) {
		($id,$pw) = split(/:/);
		if ($in{'id'} eq $id) { $f++; last; }
	}
	close(IN);
	if (!$f) { &error("認証できません"); }

	# 照合処理
	$pw =~ s/\n//;
	$check = &decrypt($in{'pw'}, $pw);
	if ($check != 1) { &error("認証できません"); }

	# 隠しファイル出力
	&fileOpen;

	# 入室記録
	if ($mode eq 'enter') { &record; }
	exit;
}

#------------#
#  認証画面  #
#------------#
sub enter {
	# クッキー取得
	local($cid,$cpw,$cck,$ctm) = &get_cookie();

	local($checked) = 'checked';
	if ($cck eq '0') {
		$cid = $cpw = '';
		$checked = '';
	}

	&header;
	print <<EOM;
<BR><BR><BR>
<div align="center">
<form action="$script" method="POST">
<input type=hidden name=mode value="enter">
<table width=370 border=0 cellspacing=0 cellpadding=6>
<tr>
  <td class="ent1">$titleに接続</td>
</tr>
<tr>
  <td class="ent2">
	<table border=0 cellpadding=0 cellspacing=5 width="100%">
	<tr>
		<td colspan=2>$title</td>
	</tr>
	<tr>
		<td>メンバーズID :</td>
		<td><input type=text name=id size=30 value="$cid"></td>
	</tr>
	<tr>
		<td>パスワード :</td>
		<td><input type=password name=pw size=30 value="$cpw"></td>
	</tr>
	<tr>
		<td></td>
		<td><input type=checkbox name=cook value="1" $checked>
		パスワードを記憶する</td>
	</tr>
	<tr>
		<td colspan=2 align=right height=50 valign=bottom>
		<input type=submit value="&nbsp;&nbsp;&nbsp; OK &nbsp;&nbsp;&nbsp;">
		<input type=reset value="キャンセル"></td>
	</tr>
	</table>
  </td>
</tr>
</table>
</form>
<br><br><br>
<!-- 著作権表\示：削除禁止($ver) -->
<span style="font-size:10px;font-family:Verdana,Helvetica,Arial;">
- <a href="http://www.kent-web.com/" target="_top">WebProtect</a> -
</span></div>
</body>
</html>
EOM
	exit;
}

#--------------#
#  認証後表示  #
#--------------#
sub fileOpen {
	local($target,$temp);

	if ($page eq '') { $target = $secret[0]; }
	else { $target = $secret[$page]; }

	# CGIファイル移動
	if ($secret[$page] =~ m|http://|) {

		# IISサーバ対応
		if ($ENV{'PERLXS'} eq "PerlIS") {
			print "HTTP/1.0 302 Temporary Redirection\r\n";
			print "Content-type: text/html\n";
		}

		print "Location: $target\n\n";
		exit;

	# HTMLファイル移動
	} else {

		open(IN,"$prvdir/$target") || &error("Open Error: $target");
		print "Content-type: text/html\n\n";
		$script =~ /\/(.*)$/; $temp = $1;
		while (<IN>) {

			# リンク部及び画像にID/PASS情報付加
			s/\?page=/\?id=$in{'id'}&pw=$in{'pw'}&page=/g;
			s/\?gif=/\?id=$in{'id'}&pw=$in{'pw'}&gif=/g;
			s/\?jpeg=/\?id=$in{'id'}&pw=$in{'pw'}&jpeg=/g;
			s/\?excel=/\?id=$in{'id'}&pw=$in{'pw'}&excel=/g;
			s/\?pdf=/\?id=$in{'id'}&pw=$in{'pw'}&pdf=/g;
			s/<form([^>]*$temp[^>]*)?>/<form $1>\n<input type=hidden name=id value=\"$in{'id'}\">\n<input type=hidden name=pw value=\"$in{'pw'}\">/ig;

			print;
		}
		close(IN);
	}
}

#------------------#
#  認証トップ戻り  #
#------------------#
sub pageTop {
	local($f,$id,$pw,$check);

	# クッキー取得
	local($cid,$cpw,$cck,$ctm) = &get_cookie();

	# 取得失敗
	if ($cid eq "" || $cpw eq "") { &error("クッキー取得に失敗しました"); }

	# パスファイルを開く
	$f=0;
	open(IN,"$prvdir/$pwdfile") || &error("Open Error: $pwdfile");
	while (<IN>) {
		($id,$pw) = split(/:/);
		if ($cid eq $id) { $f++; last; }
	}
	close(IN);
	if (!$f) { &error("認証できません"); }

	# 照合
	$pw =~ s/\n//;
	$check = &decrypt($cpw, $pw);
	if ($check != 1) { &error("認証できません"); }

	# トップページ表示
	$in{'id'} = $cid;
	$in{'pw'} = $cpw;
	&fileOpen;
	exit;
}

#----------------#
#  バイナリ出力  #
#----------------#
sub binOut {
	local($f,$check,$id,$pw,$file,$head);

	# パスチェック
	$f=0;
	open(IN,"$prvdir/$pwdfile") || &error("Open Error: $pwdfile");
	while (<IN>) {
		($id,$pw) = split(/:/);
		if ($in{'id'} eq $id) { $f++; last; }
	}
	close(IN);
	if (!$f) { die "ID not found"; }

	# 照合
	$pw =~ s/\n//;
	$check = &decrypt($in{'pw'}, $pw);
	if ($check != 1) { die "PASSWORD ERROR"; }

	# ファイル名&出力ヘッダ定義
	if ($in{'gif'}) {
		$in{'gif'} =~ s/\W//g;
		$file = "$in{'gif'}\.gif";
		$head = "image/gif";

	} elsif ($in{'jpeg'}) {
		$in{'jpeg'} =~ s/\W//g;
		$file = "$in{'jpeg'}\.jpg";
		$head = "image/jpeg";

	} elsif ($in{'pdf'}) {
		$in{'pdf'} =~ s/\W//g;
		$file = "$in{'pdf'}\.pdf";
		$head = "application/pdf";

	} elsif ($in{'excel'}) {
		$in{'excel'} =~ s/\W//g;
		$file = "$in{'excel'}\.xls";
		$head = "application/ms-excel";

	} else {
		die "No Data";
	}

	# 画像出力
	open(IN,"$prvdir/$file");
	print "Content-type: $head\n\n";
	binmode(IN);
	binmode(STDOUT);
	print <IN>;
	close(IN);

	exit;
}

#------------#
#  ログ記録  #
#------------#
sub record {
	local($date,$time,@data);

	# 時間&ホスト取得
	$date = &get_time;
	$time = time;
	&get_host;

	# ロック開始
	&lock if ($lockkey);

	# ログファイルの読み込み
	open(IN,"$prvdir/$logfile") || &error("Open Error: $logfile");
	@data = <IN>;
	close(IN);

	# ログ更新
	while ($max <= @data) { pop(@data); }
	unshift(@data,"$in{'id'}<>$date<>$host<>$ENV{'HTTP_USER_AGENT'}<>$time<>\n");
	open(OUT,">$prvdir/$logfile") || &error("Write Error: $logfile");
	print OUT @data;
	close(OUT);

	# ロック解除
	&unlock if ($lockkey);
}

#----------------#
#  クッキー発行  #
#----------------#
sub set_cookie {
	local($job, $time) = @_;
	local($gmt, $cook, @t, @m, @w);

	@t = gmtime(time + 60*24*60*60);
	@m = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	@w = ('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

	# 国際標準時を定義
	$gmt = sprintf("%s, %02d-%s-%04d %02d:%02d:%02d GMT",
			$w[$t[6]], $t[3], $m[$t[4]], $t[5]+1900, $t[2], $t[1], $t[0]);

	# 保存データ
	$cook = "$in{'id'}<>$in{'pw'}<>$job<>$time<>";

	# 格納
	print "Set-Cookie: wprotect=$cook; expires=$gmt\n";
}

#----------------#
#  クッキー取得  #
#----------------#
sub get_cookie {
	local($key, $val, *cook);

	# クッキーを取得
	$cook = $ENV{'HTTP_COOKIE'};

	# 該当IDを取り出す
	foreach ( split(/;/, $cook) ) {
		($key, $val) = split(/=/);
		$key =~ s/\s//g;
		$cook{$key} = $val;
	}

	return ( split(/<>/, $cook{'wprotect'}) );
}

#------------------#
#  チェックモード  #
#------------------#
sub check {
	local($k,$v,%log);

	&header;
	print <<EOM;
<h3>Check Mode</h3>
<ul>
EOM

	%log = (
		'パスファイル', $pwdfile,
		'ログファイル', $logfile,
		'管理ログ', $admfile,
		'会員ファイル', $memfile,
	);

	while ( ($k, $v) = each %log ) {
		if (-e "$prvdir/$v") {
			print "<li>$kのパスOK!\n";
			if (-r "$prvdir/$v" && -w "$prvdir/$v") {
				print "<li>$kのパーミッションOK!\n";
			} else {
				print "<li>$kのパーミッションNG → $v\n";
			}
		} else {
			print "<li>$kのパスNG → $v\n";
		}
	}

	# sendmail
	if (-e $sendmail) {
		print "<li>sendmailパスOK!\n";
	} else {
		print "<li>sendmailパスNG! → $sendmail<br>
		(sendmailを使用しない場合は気にしなくてよい)\n";
	}

	# ロックディレクトリ
	print "<li>ロック形式 → ";
	if ($lockkey == 0) { print "設定なし\n"; }
	else {
		if ($lockkey == 1) { print "symlink\n"; }
		else { print "mkdir\n"; }

		local($lockdir) = $lockfile =~ /(.*)[\\\/].*$/;
		print "<li>ロックディレクトリ → $lockdir\n";

		if (-d $lockdir) {
			print "<li>ロックディレクトリパスOK!\n";
			if (-r $lockdir && -w $lockdir && -x $lockdir) {
				print "<li>ロックディレクトリパーミッションOK!\n";
			} else {
				print "<li>ロックディレクトリパーミッションNG! → $lockdir\n";
			}
		} else {
			print "<li>ロックディレクトリNG! → $lockdir\n";
		}
	}

	# 著作権表示（削除不可）
	print <<EOM;
<li><b>$ver</b> : Copyright (c) <a href="http://www.kent-web.com/">KentWeb</a>
</ul>
</body>
</html>
EOM
	exit;
}


__END__

