#!/usr/bin/perl
BEGIN {
	push(@INC,'.');
}
### ============================================================ ###
###		form.cgi (ver1.05: 2004.7)
###			(C) 2004 Ashiya-People.Com
###						(mail: maintenance@ashiya-people.com)
### ------------------------------------------------------------ ###
###		このスクリプトの無断使用、転載等を禁じます。
### ============================================================ ###
### Content-type
#print "Content-type: text/html; charset=Shift_JIS\n";
#print "\n";



### ============================================================ ###
###		以下の設定項目以外の改変を禁じます。
###				(C) 芦屋人 (mail: maintenance@ashiya-people.com)
### ------------------------------------------------------------ ###
###		設定項目 ----- ここから ↓↓↓↓↓ ---
### ------------------------------------------------------------ ###

## 入力フォームを配置するＨＴＭＬ（cgi-bin/からの相対パス）
#local ($baseHTML) =		"/windows/sites/client-sites/rose-shamayim.com/web/form/contact.html";
local ($baseHTML) =		"/home/sites/www.rose-shamayim.com/wwwroot/web/form/contact.html";
## 入力確認を行うＨＴＭＬ（cgi-bin/からの相対パス）
#local ($confirmHTML) =	"/windows/sites/client-sites/rose-shamayim.com/web/form/contact.html";
local ($confirmHTML) =	"/home/sites/www.rose-shamayim.com/wwwroot/web/form/contact.html";

## 以下のタグを有効にする
local (@enableTAG) = (
	'b',
	'span',
	'div'
);
## 以下のスタイルを有効にする
local (@enableSTYLE) = (
	'color',
	'font-weight'
);

## パスワードの長さ
local ($passwdMIN, $passwdMAX) = (6, 12);
## 送信項目
##	word:		[a-zA-Z_0-9\-]の文字列（１行）
##	kword:		全角含む１行の文字列
##	passwd:		パスワード
##	tel:		電話番号
##	mail:		メールアドレス
##	url:		ＵＲＬアドレス
##	textblock:	全角含む複数行の文字列
##	img:		イメージファイル（オプション）
local (%names) = (
#	変数名		タイプ (-:必須でない)(@:タグ使用可)
	name =>					'kword',
	zip =>					'word',
	adrs =>					'kword',
	tel =>					'tel',
	fax =>					'tel:-',
	email =>				'mail',
	byear =>				'word:-',
	bmonth =>				'word:-',
	bday =>					'word:-',
	purpose =>				'kword',
	message =>				'textblock',
	question =>				'textblock:-'
);

### ------------------------------------------------------------ ###
###		設定項目 ----- ここまで ↑↑↑↑↑ ---
### ============================================================ ###










### ============================================================ ###
###		メイン処理
###			以下の内容は変更不可！
### ------------------------------------------------------------ ###

### -------------------------------------------------- ###
###		ライブラリ
### -------------------------------------------------- ###

require 'lib/cgi-lib.pl';
require 'lib/jcode.pl';
require 'lib/mimew.pl';
require 'pourHtml.pl';
require 'ap_mail.pl';



### -------------------------------------------------- ###
###		コンバート
### -------------------------------------------------- ###

# in <- values
&ReadParse(*in);
# Convert to jis
foreach (keys %in) {
	&jcode'convert(*in{$_}, 'jis');
}

### -------------------------------------------------- ###
###		コンバート
### -------------------------------------------------- ###

local (%error_message) = (
server_busy => '大変ご迷惑をお掛けして申し訳ありません。<br>
只今、サーバーが混雑しています。<br>
<br>
しばらくしてからもう一度アクセスしてみて下さい。'
);

### -------------------------------------------------- ###
###		入力値のエラーチェック
### -------------------------------------------------- ###
local (%formVar);

# 入力状態：'ok' or 'ng'
local ($namesSTATUS) = 'ok';

# 入力回数のカウント処理
$names{'inputID'} = 'code';
if ($in{'inputID'}) {
	$formVar{'inputID'}=$in{'inputID'}+1;
} else {
	$formVar{'inputID'}=1;
}

# 入力チェック：'on' or ''
$names{'inputCHK'} = 'code';
$formVar{'inputCHK'}=$in{'inputCHK'};
if ($formVar{'inputCHK'}) {
	foreach $name (keys %names) {
		local ($input,$type,$mode)=($in{$name}, split(':',$names{$name}));

		unless ($input || ($type eq 'passwd')) {
			if ($mode=~/-/) {
				$formVar{$name.'InputStatus'} = null;
			} else {
				$formVar{$name.'InputStatus'} = 'ng';
			}
		} else {
			if ($type eq "word") {
				# 英数文字＋ハイフン ---------------------
				if ($input=~/[^a-z_0-9\-]/i) {
					$formVar{$name.'InputStatus'} = 'bad';
				} else {
					$formVar{$name.'InputStatus'} = 'ok';
				}
				$input=~s/\&/&amp;/g;
				$input=~s/\"/&quot;/g;
				$input=~s/\'/&#39;/g;
				$input=~s/</&lt;/g;
				$input=~s/>/&gt;/g;
				$formVar{$name}=$input;
				# ----------------------------------------
			} elsif ($type eq "kword") {
				# 全角含む１行の文字列 -------------------
				$formVar{$name.'InputStatus'} = 'ok';

				$input=~s/\&/&amp;/g;
				$input=~s/\"/&quot;/g;
				$input=~s/\'/&#39;/g;
				$input=~s/</&lt;/g;
				$input=~s/>/&gt;/g;
				$formVar{$name}=$input;
				# ----------------------------------------
			} elsif ($type eq "passwd") {
				# パスワードチェック ---------------------
				local ($enc) = $in{$name.'ENC'};
				if ($enc) {
					$formVar{$name.'InputStatus'} = 'ok';
					$formVar{$name.'ENC'}=$enc;
					$formVar{$name}=$input;
				} elsif ($input) {
					local ($len) = length($input);
					if ($input=~/[^a-z_0-9\-]/i) {
						$formVar{$name.'InputStatus'} = 'bad';
					} elsif ($len<$passwdMIN) {
						$formVar{$name.'InputStatus'} = 'too_short';
					} elsif ($passwdMAX<$len) {
						$formVar{$name.'InputStatus'} = 'too_long';
					} else {
						$formVar{$name.'InputStatus'} = 'ok';
						# エンコード
						local (@c) = ('0'..'9','_','A'..'Z','-','a'..'z');
						local ($rd0) = time + rand()*10000;
						local ($rd1) = $rd0 + rand()*10000;
						local ($salt) = $c[$rd0%64].$c[$rd1%64];
						$input = crypt($input, $salt);
					}
					$formVar{$name.'ENC'}=$input;
					$formVar{$name}="*"x$len;
				} else {
					if ($mode=~/-/) {
						$formVar{$name.'InputStatus'} = null;
					} else {
						$formVar{$name.'InputStatus'} = 'ng';
					}
				}
				# ----------------------------------------
			} elsif ($type eq "tel") {
				# 電話番号チェック -----------------------
				if ($input=~/[^0-9\-]/i) {
					$formVar{$name.'InputStatus'} = 'bad';
				} else {
					local (@num) = ($input=~/\d/g);
					local ($num) = scalar @num;
					if (($num==10) || ($num==11)) {
						$formVar{$name.'InputStatus'} = 'ok';
					} else {
						$formVar{$name.'InputStatus'} = 'bad';
					}
				}
				$formVar{$name}=$input;
				# ----------------------------------------
			} elsif ($type eq "mail") {
				# メールアドレスチェック -----------------
				if (($input=~/^(\w|-)+\@(\w|-)+\.(\w|-)+/i) && !($input=~/[^a-z_0-9\-\@\.]|\.\.|\.$/i)) {
					$formVar{$name.'InputStatus'} = 'ok';
				} else {
					# メールアドレスが不適切です。
					$formVar{$name.'InputStatus'} = 'bad';
				}
				$formVar{$name}=$input;
				# ----------------------------------------
			} elsif ($type eq "url") {
				# ＵＲＬチェック -------------------------
				$input=~s/^http:\/\///;
				unless ($input) {
					if ($mode=~/-/) {
						$formVar{$name.'InputStatus'} = null;
					} else {
						$formVar{$name.'InputStatus'} = 'ng';
					}
				} else {
					if ($input=~/(\w|-)+\.(\w|-)+\.(\w|-)+/) {
						$formVar{$name.'InputStatus'} = 'ok';
					} else {
						$formVar{$name.'InputStatus'} = 'bad';
					}
				}
				$formVar{$name}=$input;
				# ----------------------------------------
			} elsif ($type eq 'img') {
				# アップロード ---------------------------
				print "アップロード機能\はオプションです。<br>\n";
				print "オプション・プログラムを追加する必要があります。<br>\n";
				# ----------------------------------------
			} elsif ($type eq "textblock") {
				# 全角含む複数行の文字列 -----------------
				if ($mode=~/\@/) {
					# タグ使用可
					$input=~s/<!--(.|\n)*?-->//g;
					$input=~s/<br>/\n/ig;
					local (@tag) = ($input=~/<(\/*[^>]*?)>/g);
					if (@tag) {
						$input=~s/<(\/*[^>]*?)>/$;/g;
						$input=~s/\x0d\x0a/<br>/g;
						$input=~s/\x0d/<br>/g;
						$input=~s/\x0a/<br>/g;

						foreach $tag (@tag) {
							local ($fg);
							foreach $etag (@enableTAG) {
								if ($tag=~s/(\/*)$etag\b//i) {
									local ($term) = $1;
									local ($style) = ($tag=~/style=\"((.|\n)+?);*\"/i);
									$tag="";
									if ($style) {
										local (@style) = split(';', $style);
										foreach $stl (@style) {
											local ($stag,$param) = split(':',$stl);
											foreach $estl (@enableSTYLE) {
												if ($stag eq $estl) {
													$tag .= "$stag:$param;";
													last;
												}
											}
										}
										$tag=" style=\"$tag\"" if ($tag);
									}
									$input=~s/$;/<$term$etag$tag>/;
									$fg=true;
									last;
								}
							}
							$input=~s/$;// unless ($fg);
						}
					}
					$formVar{$name}=$input;
					$input=~s/\&/&amp;/g;
					$input=~s/\"/&quot;/g;
					$input=~s/\'/&#39;/g;
					$input=~s/</&lt;/g;
					$input=~s/>/&gt;/g;
					$formVar{$name.'ESC'}=$input;
					$formVar{$name.'InputStatus'} = 'ok';
				} else {
					# タグ使用不可
					$formVar{$name}=$input;
					$input=~s/\&/&amp;/g;
					$input=~s/\"/&quot;/g;
					$input=~s/\'/&#39;/g;
					$input=~s/\x0d\x0a/<br>/g;
					$input=~s/\x0d/<br>/g;
					$input=~s/\x0a/<br>/g;
					$input=~s/</&lt;/g;
					$input=~s/>/&gt;/g;
					$formVar{$name.'ESC'}=$input;
					$formVar{$name.'InputStatus'} = 'ok';
				}
				# ----------------------------------------
			}
		}

		# 入力エラー状態集計
		local ($status) = $formVar{$name.'InputStatus'};
		if ($status) {
			unless ($status eq 'ok' || ($status eq null)) {
				$namesSTATUS = 'ng';
			}
		} else {
			unless (($type eq 'code') || $mode=~/-/) {
				$namesSTATUS = 'ng';
			}
		}
	}
} else {
	$namesSTATUS = 'ng';
	$formVar{'inputCHK'}='on';
}

### -------------------------------------------------- ###
###		アクション
### -------------------------------------------------- ###

$formVar{'InputStatus'}=$namesSTATUS;
local ($formACTION) = ($namesSTATUS eq 'ok')? $ARGV[0] : 'input';
if ($formACTION eq 'mail') {

	if (defined $AP_MAIL_ENABLE) {
		send_mailFMT(\%formVar);
		print "Location:$mail_thanksURL\n\n";
		exit;
	} else {
		# エラーメッセージ
		local ($errmsg)=<<__MAIL_DISABLE_ERROR__;
現在、メール送信機能\は有効ではありません。<br>
メール送信機能\を有効にするには、<br>
このサイトの管理者にお問い合わせ下さい。<br>
<br>
__MAIL_DISABLE_ERROR__
		print "Content-type: text/html; charset=Shift_JIS\n";
		print "\n";
		server_error($formACTION, $errmsg);
		exit;
	}

} else {

	$formACTION = 'input';
	print "Content-type: text/html; charset=Shift_JIS\n";
	print "\n";

}

### -------------------------------------------------- ###
###		読み込み（ＨＴＭＬページ出力用）
### -------------------------------------------------- ###

local ($outputHTML) = ($namesSTATUS eq 'ok') ? $confirmHTML : $baseHTML;

unless (open(HTML, "<$outputHTML")) {
	server_error($formACTION, $error_message{'server_busy'});
	exit;
}
local (@outputHTML) = <HTML>;
close(HTML);

### -------------------------------------------------- ###
###		ページ出力（入力確認用のページ）
### -------------------------------------------------- ###

for ($i=0; $i<@outputHTML; $i++) {
	local ($line) = $outputHTML[$i];

	### 軽量化のため同一行内での input,textarea,$APコマンド のオーバーラップ不可
	### <input>
	if ($line=~/<\s*input\b/i) {
		local ($j);
		for ($j=100; $j>0; $j--) {
			if ($line=~s/<\s*input\s+((.|\n)+?)>/$;/i) {
				local ($tag);
				local ($param) = $1;
				## <input
				local ($name) = ($param=~/name\s*=\s*\"*(\w+)\"*\b/i);
				if ($names{$name}) {
					local ($value);
					if ($param=~/value\s*=\s*\"/i) {
						$value = $1 if ($param=~s/value\s*=\s*\"(.*?)\"//i);
					} else {
						$value = $1 if ($param=~s/value\s*=\s*.+?(\s|$)//i);
					}
					local ($type) = ($param=~/type\s*=\s*\"*(\w+)\"*\b/i);
					if ("\L$type\E" eq 'radio') {
						# ラジオボタン
						$param .= " value=\"$value\"";
						if ($formVar{$name.'InputStatus'} eq 'ok') {
							$param =~ s/\s+checked//i;
							$param .= " checked" if ($value eq $formVar{$name});
						}
						$tag = "<input $param>";
					} else {
						if ($formVar{$name.'InputStatus'} eq 'ok') {
							$tag = '<input type="hidden" name="'.$name.'" value="$AP_Var('.$name.')">'."\n";
							$tag.= '<input type="hidden" name="'.$name.'ENC" value="$AP_Var('.$name.'ENC)">'."\n" if ($formVar{$name.'ENC'});
							$tag.= $formVar{$name};
						} else {
							if ($formVar{$name.'ENC'}) {
								$param .= " value=\"$formVar{$name.'ENC'}\"";
							} else {
								$param .= " value=\"$formVar{$name}\"";
							}
							$tag = "<input $param>";
						}
					}
				} else {
					$tag = "<input $param>";
				}
				## >
				$line=~s/$;/$tag/;
				last;
			}
			$line .= $outputHTML[++$i];
		}
	}
	### </input>

	### <textarea>
	if ($line=~/<\s*textarea\b/i) {
		local ($j);
		for ($j=100; $j>0; $j--) {
			if ($line=~s/(<\s*textarea[^>]*?>)([^<]*)<\/textarea>/$;/i) {
				local ($text_tag, $text_str) = ($1);
				## <textarea
				local ($name) = ($text_tag=~/name\s*=\s*\"*(\w+)\"*\b/i);
				if ($formVar{$name.'InputStatus'} eq 'ok') {
					$text_str = ($formVar{$name.'ESC'})? $formVar{$name.'ESC'} : $formVar{$name};
					$text_str =~ s/&lt;br&gt;/<br>/ig;
					$text_str = '<input type="hidden" name="'.$name.'" value="$AP_Var('.$name.'ESC)">'."\n".$text_str;
				} else {
					if ($names{$name}) {
						if ($formVar{$name.'ESC'}) {
							$text_str = $formVar{$name.'ESC'};
						} else {
							$text_str = $formVar{$name};
						}
					}
					$text_str = "$text_tag$text_str<\/textarea>";
				}
				## >
				$line=~s/$;/$text_str/;
				last;
			}
			$line .= $outputHTML[++$i];
		}
	}
	### </textarea>

	### <select>
	if ($line=~/<\s*select\b/i) {
		local ($j);
		for ($j=100; $j>0; $j--) {
			if ($line=~s/(<\s*select[^>]*?>)((.|\n)+)<\/select>/$;/i) {
				local ($sel_tag, $opt_tags, $sel_str) = ($1, $2);
				## <select
				local ($name) = ($sel_tag=~/name\s*=\s*\"*(\w+)\"*\b/i);
				if ($formVar{$name.'InputStatus'} eq 'ok') {
					$opt_tags =~ s/\s+selected//i;
					$opt_tags =~ s/(value\s*=\s*\"?$formVar{$name}\"?)/$1 selected/i;
				}
				$sel_str = "$sel_tag$opt_tags<\/select>";
				## >
				$line=~s/$;/$sel_str/;
				last;
			}
			$line .= $outputHTML[++$i];
		}
	}
	### </select>

	### $AP_Case
	if ($line=~/\$AP_Case/) {
		local ($j);
		for ($j=100; $j>0; $j--) {
			last if (&pourCase(\$line, \%formVar));
			$line .= $outputHTML[++$i];
		}
	}
	### $AP_Var
	if ($line=~/\$AP_Var/) {
		local ($j);
		for ($j=100; $j>0; $j--) {
			last if (&pourVar(\$line, \%formVar));
			$line .= $outputHTML[++$i];
		}
	}
	### $AP_Cgi
	if ($line=~/\$AP_Cgi/) {
		local ($j);
		for ($j=100; $j>0; $j--) {
			last if (&pourCgi(\$line, \%formVar));
			$line .= $outputHTML[++$i];
		}
	}

	print $line;
}

### ------------------------------------------------------------ ###
###		メイン処理
### ============================================================ ###





### ============================================================ ###
###		サブルーチン
### ------------------------------------------------------------ ###

### ------------------------------------------------------------ ###
###		サーバーエラー（ＨＴＭＬ表示）
### ------------------------------------------------------------ ###

sub server_error {
	local ($action, $comment) = @_;
print<<__SERVER_ERROR__;
<table cellpadding="0" cellspacing="0"
	style="position:absolute;top:40;left:80;width:360;
	font-size:14;font-weight:bold;color:#606060">
	<tr><td width="30"/><td/></tr>
	<tr><td colspan="2"><hr></td></tr>
	<tr><td colspan="2" style="font-size:18;color:#306030">
		サーバーエラー
		</td><tr>
	<tr><td colspan="2" align="right" style="font-size:13">
		form.cgi: ( action = $action )
		</td></tr>
	<tr><td colspan="2"><hr></td></tr>
	<tr><td height="20"/></tr>
	<tr><td/><td>
		$comment
		</td></tr>
	<tr><td height="20"/></tr>
	<tr><td colspan="2"><hr></td></tr>
</table>
__SERVER_ERROR__
}

### ------------------------------------------------------------ ###
###		サブルーチン
### ============================================================ ###
