#!/usr/bin/perl
use CGI;
use Jcode;
# perl 5.8.1以降のみ(エラーになる場合は、コピー関連処理をなくす)
use File::Copy;
use CGI::Cookie;
require './fmail.admin/commons/conf.cgi';
require './fmail.lib.cgi';
require './fmail.admin/commons/mimew.pl';
require './fmail.admin/commons/registry.cgi';
#モバイルでのアクセスの場合の切り分けフラグ。登録されているモバイルブラウザの数だけループ
$flag_mua = 0;
for($mua=0;@MOBILE_USER_AGENT>$mua;$mua++){
	if($ENV{'HTTP_USER_AGENT'} =~ /$MOBILE_USER_AGENT[$mua]/){
		#モバイルの機種に合致したので、フラグON
		$flag_mua = 1;
	}
}
#添付ファイルの可否(有り=1 無し=0)
if($reg{'attached_method'} && $flag_mua == 0){
	$enctype = ' enctype="multipart/form-data"';
}
else {
	$enctype = '';
}
$attached_files_dir = './fmail.admin/datas/attached_files/';
$sessions_files_dir = './fmail.admin/datas/sessions_files/';
&GET;
*getSes = GetCookie($ENV{'HTTP_COOKIE'});
if($_GET{'ses'} ne $null){
	$session = $_GET{'ses'};
}
elsif($getSes{'session'} eq $null || index($getSes{'session'},'/') > -1){
	$session = &createId;
}
else {
	$session = $getSes{'session'};
}
if(&device){
	$sesQuery = "&ses=${session}";
}
$send_token = $sessions_files_dir . $session . '_token.cgi';
@mailform_env = &loadfile('./fmail.admin/datas/modules/mailform_env/mailform_env.dat');
$mailform_env = join("\n",@mailform_env);
($mailform_flag,$expires_start,$expires_end,$limit,$serials,$thanks_page,$sendmail_path,$logsave,$cart_in_element,$cart_logsave,$send_mode,$attached_mode,$display_mode,$logdata_path,$cart_logdata_path,$mailform_sender_address_name,$mailform_sender_address,$mail_method,$thanks_message,$title_mailform,$title_confirm,$title_error,$title_thanks,$spamcheck,$mail_dustclear,$mail_dustclear_zero,$client_info,$site_url,$table_style,$th_style,$td_style,$separate_before,$separate_after,$flag_afiri,$afiri_tag,$flag_smartphone_tpl,$flag_futurephone_tpl,$setlang) = split(/\n/,$mailform_env);
@elements = &loadfile('./fmail.admin/datas/modules/elements/elements.dat');
@must = &loadfile('./fmail.admin/datas/modules/must_conditional/must_conditional.dat');
#スマートフォンでのアクセスの場合の切り分けフラグ。登録されているブラウザの数だけループ
$flag_smartphone = 0;
if($flag_smartphone_tpl == 1){
	for($smartphone=0;@SMARTPHONE_USER_AGENT>$smartphone;$smartphone++){
		if($ENV{'HTTP_USER_AGENT'} =~ /$SMARTPHONE_USER_AGENT[$smartphone]/){
			#スマートフォンの機種に合致したので、フラグON
			$flag_smartphone = 1;
		}
	}
}
#フューチャーフォンでのアクセスの場合の切り分けフラグ。登録されているブラウザの数だけループ
$flag_futurephone = 0;
if($flag_futurephone_tpl == 1){
	for($futurephone=0;@MOBILE_USER_AGENT>$futurephone;$futurephone++){
		if($ENV{'HTTP_USER_AGENT'} =~ /$MOBILE_USER_AGENT[$futurephone]/){
			#スマートフォンの機種に合致したので、フラグON
			$flag_futurephone = 1;
		}
	}
}
if($flag_smartphone) {
	# スマフォ
	$tpl = './fmail_smartphone.tpl';
} elsif($flag_futurephone) {
	# スマフォ
	$tpl = './fmail_mobile.tpl';
} else {
	# スマフォ以外
	$tpl = './fmail.tpl';
}
$tpl_symbol_title = '';
$tpl_symbol_title_body = '';
$tpl_symbol_body = '';
$tpl_symbol_error = '';
$tpl_symbol_ver = '';
if(-f $tpl){
	@html = &loadfile($tpl);
	$html = join("\n",@html);
}
if($_GET{'mode'} eq "send" && -f $send_token){
	unlink "${sessions_files_dir}${session}\.cgi";
	unlink $send_token;
	$return_mail_set = &mfp_LoadFile('./fmail.admin/datas/modules/return_mail/return_mail.dat');
	($return_mail_flag,$return_mail_from,$return_mail_sender,$return_mail_subject,$return_mail_serials,$return_mail_email_field,$return_mail_body) = split(/\n/,$return_mail_set);
	$return_mail_body =~ s/
/\n/g;
	# 通し番号
	&serials();
	@csv_fields = ($stmp,$session,$serial_number);
	@logdata = split(/\n/,$logdata);
	$q = new CGI;
	$return_values = "";
	%getElementById = ();
	if($mail_method eq "html"){
		$return_mail_body =~ s/"/\"/g;
		$return_mail_body =~ s/\<//g;
		$return_mail_body =~ s/
/
/g;
	}
	
	##joinエレメントを抽出
	@join_elements = grep(/\tjoin\t/,@elements);
	%join_elements = ();
	%join_values = ();
	for($cnt=0;$cnt<@join_elements;$cnt++){
		($elements_id,$num,$name,$type_of_element,$html_size,$html_rows,$html_cols,$html_id,$element_type,$check_type,$on_event,$on_focus,$text_min,$text_max,$enable_filetypes,$filesize_min,$filesize_max,$checked_min,$checked_max,$element_valus,$element_text,$html_example,$note) = split(/\t/,$join_elements[$cnt]);
		$elementname = "en${elements_id}";
		@values = $q->param($elementname);
		$values = join("\n",@values);
		$safe = 100;
		while($safe > 0 && $type_of_element =~ /<join id\=\"(.*?)\" name=\"(.*?)\" \/>/){
			$join_id = $1;
			$joinelementname = "en${join_id}";
			@values = $q->param($joinelementname);
			$values = join("\n",@values);
			$join_elements{$join_id} = 1;
			$type_of_element =~ s/<join id\=\"$join_id\" name=\"$2\" \/>/$values/g;
			$safe--;
		}
		$type_of_element =~ s/
/\n/g;
		$join_values{$elements_id} = $type_of_element;
		
		#件名置換
		$return_mail_subject =~ s/<${elements_id}>/$join_values{$elements_id}/g;
	}
	
#	&serials();
	for($cnt=0;$cnt<@elements;$cnt++){
		($elements_id,$num,$name,$type_of_element,$html_size,$html_rows,$html_cols,$html_id,$element_type,$check_type,$on_event,$on_focus,$text_min,$text_max,$enable_filetypes,$filesize_min,$filesize_max,$checked_min,$checked_max,$element_valus,$element_text,$html_example,$note) = split(/\t/,$elements[$cnt]);
		
		#項目名の改行処理
		$name =~ s/<-br->//g;
		
		if($element_type ne "spacer"){
			$elementname = "en${elements_id}";
			@values = $q->param($elementname);
			$values = join("\n",@values);
			push @csv_fields,$values;
			$getElementById{$elements_id} = $values;
			if($join_values{$elements_id}){
				$values = $join_values{$elements_id};
			}
			$crr = "";
			if(index($values,"\n") > 1){
				$crr = "\n";
			}
			if($element_type eq "file" && $values ne $null){
				$save_file_name = "${attached_files_dir}${session}_${elementname}\.cgi";
				if(-f $save_file_name){
					$binary = &mfp_LoadFile($save_file_name);
					# ファイル名の通し番号置き換え
					# 添え字に-1を指定すると下番地(逆順)から取得してくれる
					#$values;
					@filename_extension = split(/\./,$values);
					$values = "$serial\.$filename_extension[-1]";
					
					push @file_paths,$values;
					push @file_datas,$binary;
					push @unlinkpath,$save_file_name;
				}
			}
			if(!$join_elements{$elements_id}){
				#未入力項目の除外処理 $mail_dustclear=1 「0」除外 $mail_dustclear_zero=1
				#各パターンが入っているので分岐は多い目
				#除外処理が入っていない
				if(!($mail_dustclear) && !($mail_dustclear_zero)){
					if($mail_method eq "html"){
						$return_values .= "
| ${name} | ${values} | 
";
					} else {
						$return_values .= "\n$separate_before${name}$separate_after${crr}${values}${crr}";
					}
				}else{
					#未入力項目の除外処理 $mail_dustclear=1
					if($mail_dustclear && !($mail_dustclear_zero) && $values ne $null){
						if($mail_method eq "html"){
							$return_values .= "| ${name} | ${values} | 
";
						} else {
							$return_values .= "\n$separate_before${name}$separate_after${crr}${values}${crr}";
						}
						
					#「0」または、「0個」除外 $mail_dustclear_zero=1
					}elsif(!($mail_dustclear) && $mail_dustclear_zero && $values ne '0' && $values ne '0個'){
						if($mail_method eq "html"){
							$return_values .= "| ${name} | ${values} | 
";
						} else {
							$return_values .= "\n$separate_before${name}$separate_after${crr}${values}${crr}";
						}
						
					#未入力項目の除外処理 $mail_dustclear=1 「0」または、「0個」除外 $mail_dustclear_zero=1
					}elsif($mail_dustclear && $mail_dustclear_zero && $values ne $null && $values ne '0' && $values ne '0個'){
						if($mail_method eq "html"){
							$return_values .= "| ${name} | ${values} | 
";
						} else {
							$return_values .= "\n$separate_before${name}$separate_after${crr}${values}${crr}";
						}
					}
				}
				
#				if(!($mail_dustclear) || (($mail_dustclear) && $values ne $null)){
#					if($mail_method eq "html"){
#						$return_values .= "| ${name} | ${values} | 
";
#					}
#					else {
#						$return_values .= "\n\[ ${name} \] ${crr}${values}${crr}";
#					}
#				}
			}
			if($mail_method eq "html"){
				$return_mail_body =~ s/<${elements_id}>/$values/g;
			}
			else {
				$return_mail_body =~ s/<${elements_id}>/$values/g;
			}
			if($return_mail_email_field eq $elements_id){
				$return_mail_email_address = $values[0];
			}
		}
		#件名置換
		$return_mail_subject =~ s/<${elements_id}>/$getElementById{$elements_id}/g;
	}
	
#	&serials();
	## ENV proccess
	my($user_agent) = $ENV{'HTTP_USER_AGENT'};
	$user_agent =~ s/\t/ /g;
	$user_agent =~ s/\n/ /g;
	$hostname = &gethostname;
	@env_fields = ($hostname,$ENV{'REMOTE_ADDR'},$user_agent,$ENV{'HTTP_REFERER'});
	push @csv_fields,@env_fields;
	
	## to admin send proccess
	if($mail_method eq "html"){
		$admin_mail_body = "";
		$env_data = $admin_mail_body;
		#$stmp . "\n" . $return_values . $admin_mail_body;
	}
	else {
		$admin_mail_body = "\n\n$separate_beforeホスト名$separate_after" . $hostname . "\n";
		$admin_mail_body .= "$separate_before"."IPアドレス$separate_after" . $ENV{'REMOTE_ADDR'} . "\n";
		$admin_mail_body .= "$separate_beforeブラウザ\/OS$separate_after" . $ENV{'HTTP_USER_AGENT'} . "\n";
		#追加
		$admin_mail_body .= "$separate_before送信元アドレス$separate_after" . $ENV{'HTTP_REFERER'} . "\n";
		$admin_mail_body .= "$separate_beforeバージョン$separate_after" . $reg{'version'} . "\n";
		$env_data = $admin_mail_body;
		#$stmp . "\n" . $return_values . $admin_mail_body;
	}
	
	## send proccess
	if($mail_method eq "html"){
		$return_values = "";
	}
	
	#本文反映用アフィリタグの設定
	$timestamp = $stmp;
	$timestamp =~ s/-//g;
	$timestamp =~ s/://g;
	$timestamp =~ s/ //g;
	$afiri_uniq_id = "$timestamp$serial";
	
	if(($return_mail_flag) && $return_mail_email_address ne $null){
		## return mail proccess
		if($mail_method eq "html"){
			$return_mail_body =~ s//$serial/g;
			$return_mail_body =~ s//$return_values/g;
			$return_mail_body =~ s//$stmp/g;
			$return_mail_body =~ s//$env_data/g;
			#追加
			$return_mail_body =~ s//$site_url/g;
			$client_info =~ s/
/
/g;
			$return_mail_body =~ s//$client_info/g;
			$return_mail_body =~ s//$afiri_uniq_id/g;
		}
		else {
			$return_mail_body =~ s/<serial>/$serial/g;
			$return_mail_body =~ s/<resbody>/$return_values/g;
			$return_mail_body =~ s/<stmp>/$stmp/g;
			$return_mail_body =~ s/<env>/$env_data/g;
			#追加
			$return_mail_body =~ s/<site_url>/$site_url/g;
			$client_info =~ s/
/\n/g;
			$return_mail_body =~ s/<client_info>/$client_info/g;
			$return_mail_body =~ s/<afiri_uniq_id>/$afiri_uniq_id/g;
		}
		# 機種依存文字サニタイズ
		$return_mail_subject = &sanitizing_str($return_mail_subject);
		$return_mail_subject = &sanitizing_str2($return_mail_subject);
		$return_mail_sender = &sanitizing_str($return_mail_sender);
		$return_mail_sender = &sanitizing_str2($return_mail_sender);
		$return_mail_body = &sanitizing_str($return_mail_body);
		$return_mail_body = &sanitizing_str2($return_mail_body);
		
		# 多言語対応
		use MIME::Base64;
		#$setlang = ja or utf8;
		# 言語設定
		$charset = $setlang;
		
		# 多言語対応
		if($charset ne 'utf8'){
			# 多言語対応でない
			$return_mail_body = &encodeJIS($return_mail_body);
			$return_mail_subject = &encodeJIS($return_mail_subject);
			$return_mail_sender = &encodeJIS($return_mail_sender);
			$return_mail_sender = "${return_mail_sender} <${return_mail_from}>";
			$return_mail_sender = Jcode->new($return_mail_sender)->mime_encode;
			$return_mail_subject = Jcode->new($return_mail_subject)->mime_encode;
		}else{
			# 多言語対応
			$return_mail_subject = "=?UTF-8?B?" . encode_base64($return_mail_subject) . '?=';
			$return_mail_subject =~ s/\n//ig;
			$return_mail_sender = "=?UTF-8?B?" . encode_base64(${return_mail_sender}) . '?=' . "<${return_mail_from}>";
			$return_mail_sender =~ s/\n//ig;
		}
		
		&sendmail($return_mail_email_address,$null,$null,$return_mail_from,$return_mail_sender,$return_mail_subject,$return_mail_body);
	}
	
	if(!($send_mode)){
		$admin_mail_body = $stmp . "メールフォームよりメールが届きました\n\n<message>\n\n";
	}
	@send_conditional = &loadfile('./fmail.admin/datas/modules/send_conditional/send_conditional.dat');
	for($cnt=0;$cnt<@send_conditional;$cnt++){
		$send_mail_body = $admin_mail_body;
		($send_conditional_id,$send_conditional_type,$send_conditional_name,$send_conditional_element,$send_conditional_value,$send_mailaddress,$send_subject,$send_body,$send_note,$cc,$bcc) = split(/\t/,$send_conditional[$cnt]);
		if($send_conditional_type){
			#HTMLメール
			if($mail_method eq "html"){
				$send_body =~ s/"/\"/g;
				$send_body =~ s/\<//g;
				$send_body =~ s/
/
/g;
				$send_body =~ s//$serial/g;
				$send_body =~ s//$return_values/g;
				$send_body =~ s//$stmp/g;
				$send_body =~ s//$env_data/g;
				#追加
				$send_body =~ s//$site_url/g;
				$client_info =~ s/
/
/g;
				$send_body =~ s//$client_info/g;
				$send_body =~ s//$afiri_uniq_id/g;
				for($cnt=0;$cnt<@elements;$cnt++){
					($elements_id,$num,$name,$type_of_element,$html_size,$html_rows,$html_cols,$html_id,$element_type,$check_type,$on_event,$on_focus,$text_min,$text_max,$enable_filetypes,$filesize_min,$filesize_max,$checked_min,$checked_max,$element_valus,$element_text,$html_example,$note) = split(/\t/,$elements[$cnt]);
					if($join_values{$elements_id}){
						$send_body =~ s/<${elements_id}>/$join_values{$elements_id}/g;
						#件名置換
						$send_subject =~ s/<${elements_id}>/$join_values{$elements_id}/g;
						#クライアント宛の送信元の置換(セキュア上良くないので、基本は使わない)
						$mailform_sender_address =~ s/<${elements_id}>/$join_values{$elements_id}/g;
						$mailform_sender_address_name =~ s/<${elements_id}>/$join_values{$elements_id} 様/g;
					}
					else {
						$send_body =~ s/<${elements_id}>/$getElementById{$elements_id}/g;
						#件名置換
						$send_subject =~ s/<${elements_id}>/$getElementById{$elements_id}/g;
						#クライアント宛の送信元の置換(セキュア上良くないので、基本は使わない)
						$mailform_sender_address =~ s/<${elements_id}>/$getElementById{$elements_id}/g;
						$mailform_sender_address_name =~ s/<${elements_id}>/$getElementById{$elements_id} 様/g;
					}
					# 入力値を反映させる
					if($send_mailaddress =~ /$elements_id/){
						$send_mailaddress_work = "";
						@send_mailaddress_arr = split(/,/,$send_mailaddress);
						for($send_mailaddress_cnt=0; $send_mailaddress_cnt<@send_mailaddress_arr; $send_mailaddress_cnt++){
							if($send_mailaddress_arr[$send_mailaddress_cnt] =~ /$elements_id/){
								$send_mailaddress_arr[$send_mailaddress_cnt] =~ s/$send_mailaddress_arr[$send_mailaddress_cnt]/$getElementById{$elements_id}/g;
								$send_mailaddress_work .= "$send_mailaddress_arr[$send_mailaddress_cnt],";
							}else{
								$send_mailaddress_work .= "$send_mailaddress_arr[$send_mailaddress_cnt],";
							}
						}
						$send_mailaddress = $send_mailaddress_work;
					}
					# 入力値を反映させる
					if($cc =~ /$elements_id/){
						$cc_work = "";
						@cc_arr = split(/,/,$cc);
						for($cc_cnt=0; $cc_cnt<@cc_arr; $cc_cnt++){
							if($cc_arr[$cc_cnt] =~ /$elements_id/){
								$cc_arr[$cc_cnt] =~ s/$cc_arr[$cc_cnt]/$getElementById{$elements_id}/g;
								$cc_work .= "$cc_arr[$cc_cnt],";
							}else{
								$cc_work .= "$cc_arr[$cc_cnt],";
							}
						}
						$cc = $cc_work;
					}
					# 入力値を反映させる
					if($bcc =~ /$elements_id/){
						$bcc_work = "";
						@bcc_arr = split(/,/,$bcc);
						for($bcc_cnt=0; $bcc_cnt<@bcc_arr; $bcc_cnt++){
							if($bcc_arr[$bcc_cnt] =~ /$elements_id/){
								$bcc_arr[$bcc_cnt] =~ s/$bcc_arr[$bcc_cnt]/$getElementById{$elements_id}/g;
								$bcc_work .= "$bcc_arr[$bcc_cnt],";
							}else{
								$bcc_work .= "$bcc_arr[$bcc_cnt],";
							}
						}
						$bcc = $bcc_work;
					}
				}
			}
			else {
				#テキストメール
				$send_body =~ s/
/\n/g;
				$send_body =~ s/<serial>/$serial/g;
				$send_body =~ s/<resbody>/$return_values/g;
				$send_body =~ s/<stmp>/$stmp/g;
				$send_body =~ s/<env>/$env_data/g;
				#追加
				$send_body =~ s/<site_url>/$site_url/g;
				$client_info =~ s/
/\n/g;
				$send_body =~ s/<client_info>/$client_info/g;
				$send_body =~ s/<afiri_uniq_id>/$afiri_uniq_id/g;
				for($cnt=0;$cnt<@elements;$cnt++){
					($elements_id,$num,$name,$type_of_element,$html_size,$html_rows,$html_cols,$html_id,$element_type,$check_type,$on_event,$on_focus,$text_min,$text_max,$enable_filetypes,$filesize_min,$filesize_max,$checked_min,$checked_max,$element_valus,$element_text,$html_example,$note) = split(/\t/,$elements[$cnt]);
					if($join_values{$elements_id}){
						$send_body =~ s/<${elements_id}>/$join_values{$elements_id}/g;
						#件名置換
						$send_subject =~ s/<${elements_id}>/$join_values{$elements_id}/g;
						#クライアント宛の送信元の置換(セキュア上良くないので、基本は使わない)
						$mailform_sender_address =~ s/<${elements_id}>/$join_values{$elements_id}/g;
						$mailform_sender_address_name =~ s/<${elements_id}>/$join_values{$elements_id} 様/g;
					}
					else {
						$send_body =~ s/<${elements_id}>/$getElementById{$elements_id}/g;
						#件名置換
						$send_subject =~ s/<${elements_id}>/$getElementById{$elements_id}/g;
						#クライアント宛の送信元の置換(セキュア上良くないので、基本は使わない)
						$mailform_sender_address =~ s/<${elements_id}>/$getElementById{$elements_id}/g;
						$mailform_sender_address_name =~ s/<${elements_id}>/$getElementById{$elements_id} 様/g;
					}
					# 入力値を反映させる
					if($send_mailaddress =~ /$elements_id/){
						$send_mailaddress_work = "";
						@send_mailaddress_arr = split(/,/,$send_mailaddress);
						for($send_mailaddress_cnt=0; $send_mailaddress_cnt<@send_mailaddress_arr; $send_mailaddress_cnt++){
							if($send_mailaddress_arr[$send_mailaddress_cnt] =~ /$elements_id/){
								$send_mailaddress_arr[$send_mailaddress_cnt] =~ s/$send_mailaddress_arr[$send_mailaddress_cnt]/$getElementById{$elements_id}/g;
								$send_mailaddress_work .= "$send_mailaddress_arr[$send_mailaddress_cnt],";
							}else{
								$send_mailaddress_work .= "$send_mailaddress_arr[$send_mailaddress_cnt],";
							}
						}
						$send_mailaddress = $send_mailaddress_work;
					}
					# 入力値を反映させる
					if($cc =~ /$elements_id/){
						$cc_work = "";
						@cc_arr = split(/,/,$cc);
						for($cc_cnt=0; $cc_cnt<@cc_arr; $cc_cnt++){
							if($cc_arr[$cc_cnt] =~ /$elements_id/){
								$cc_arr[$cc_cnt] =~ s/$cc_arr[$cc_cnt]/$getElementById{$elements_id}/g;
								$cc_work .= "$cc_arr[$cc_cnt],";
							}else{
								$cc_work .= "$cc_arr[$cc_cnt],";
							}
						}
						$cc = $cc_work;
					}
					# 入力値を反映させる
					if($bcc =~ /$elements_id/){
						$bcc_work = "";
						@bcc_arr = split(/,/,$bcc);
						for($bcc_cnt=0; $bcc_cnt<@bcc_arr; $bcc_cnt++){
							if($bcc_arr[$bcc_cnt] =~ /$elements_id/){
								$bcc_arr[$bcc_cnt] =~ s/$bcc_arr[$bcc_cnt]/$getElementById{$elements_id}/g;
								$bcc_work .= "$bcc_arr[$bcc_cnt],";
							}else{
								$bcc_work .= "$bcc_arr[$bcc_cnt],";
							}
						}
						$bcc = $bcc_work;
					}
				}
			}
			
			#汚染チェック 件名
			$send_subject =~ s/\@/@/g;
			$send_subject =~ s/\././g;
			$send_subject =~ s/\+/+/g;
			$send_subject =~ s/\-/-/g;
			$send_subject =~ s/\:/:/g;
			$send_subject =~ s/\;/;/g;
			$send_subject =~ s/\|/|/g;
			$send_subject =~ s/\n//g;
			$send_subject =~ s/\r//g;
			
			#汚染チェック 送信元
			$mailform_sender_address =~ s/\;/;/g;
			$mailform_sender_address =~ s/\n//g;
			$mailform_sender_address =~ s/\r//g;
			
			#汚染チェック 送信元
			$mailform_sender_address_name =~ s/\;/;/g;
			$mailform_sender_address_name =~ s/\n//g;
			$mailform_sender_address_name =~ s/\r//g;
			
			# 機種依存文字サニタイズ
			$send_subject = &sanitizing_str($send_subject);
			$send_subject = &sanitizing_str2($send_subject);
			$mailform_sender_address_name = &sanitizing_str($mailform_sender_address_name);
			$mailform_sender_address_name = &sanitizing_str2($mailform_sender_address_name);
			$send_body = &sanitizing_str($send_body);
			$send_body = &sanitizing_str2($send_body);
			
			
			# 多言語対応
			if($charset ne 'utf8'){
				# 多言語対応しない
				$mailform_sender_address_from = "$mailform_sender_address_name <$mailform_sender_address>";
				#一端utf8からsjisに変換し、その後にjisに変換しないと、utf8からjisの場合、一部文字化ける
				Jcode::convert(\$mailform_sender_address_from,"sjis","utf8");
				$mailform_sender_address_from = &encodeJIS($mailform_sender_address_from);
				$mailform_sender_address_from = Jcode->new($mailform_sender_address_from)->mime_encode;
			}else{
				# 多言語対応
				$mailform_sender_address_from = "=?UTF-8?B?" . encode_base64(${mailform_sender_address_name}) . '?=' . "<$mailform_sender_address>";
				$mailform_sender_address_from =~ s/\n//ig;
			}
			
			
			# 多言語対応
			if($charset ne 'utf8'){
				# 多言語対応でない
				$send_mail_body = &encodeJIS($send_body);
			}else{
				# 多言語対応
				$send_mail_body = $send_body;
			}
			
#			#一端utf8からsjisに変換し、その後にjisに変換しないと、utf8からjisの場合、一部文字化ける
#			Jcode::convert(\$send_subject,"sjis","utf8");
			# 多言語対応
			if($charset ne 'utf8'){
				# 多言語対応でない
				$send_subject = &encodeJIS($admin_subject_serial . $send_subject);
				$send_subject = Jcode->new($send_subject)->mime_encode;
			}else{
				# 多言語対応
				$send_subject = "=?UTF-8?B?" . encode_base64($admin_subject_serial . $send_subject) . '?=';
				$send_subject =~ s/\n//ig;
			}
			
			if(@file_paths > 0 && !($attached_mode)){
				sendAttachMail($mailform_sender_address_from,$send_mailaddress,$cc,$bcc, $send_subject, $send_mail_body, @file_datas, @file_paths);
			}
			else {
				&sendmail($send_mailaddress,$cc,$bcc,$mailform_sender_address,$mailform_sender_address_from,$send_subject,$send_mail_body);
			}
		}
		else {
			# 条件で送信
			@values = split(/\n/,$getElementById{$send_conditional_element});
			if(1 == grep(/^${send_conditional_value}$/,@values)){
				$send_body =~ s/
/\n/g;
				$send_body =~ s/<serial>/$serial/g;
				$send_body =~ s/<resbody>/$return_values/g;
				$send_body =~ s/<stmp>/$stmp/g;
				$send_body =~ s/<env>/$env_data/g;
				#追加
				$send_body =~ s/<site_url>/$site_url/g;
				$client_info =~ s/
/\n/g;
				$send_body =~ s/<client_info>/$client_info/g;
				$send_body =~ s/<afiri_uniq_id>/$afiri_uniq_id/g;
				for($cnt2=0;$cnt2<@elements;$cnt2++){
					($elements_id,$num,$name,$type_of_element,$html_size,$html_rows,$html_cols,$html_id,$element_type,$check_type,$on_event,$on_focus,$text_min,$text_max,$enable_filetypes,$filesize_min,$filesize_max,$checked_min,$checked_max,$element_valus,$element_text,$html_example,$note) = split(/\t/,$elements[$cnt2]);
					if($join_values{$elements_id}){
						$send_body =~ s/<${elements_id}>/$join_values{$elements_id}/g;
						#件名置換
						$send_subject =~ s/<${elements_id}>/$join_values{$elements_id}/g;
						#クライアント宛の送信元の置換(セキュア上良くないので、基本は使わない)
						$mailform_sender_address =~ s/<${elements_id}>/$join_values{$elements_id}/g;
						$mailform_sender_address_name =~ s/<${elements_id}>/$join_values{$elements_id} 様/g;
					}
					else {
						$send_body =~ s/<${elements_id}>/$getElementById{$elements_id}/g;
						#件名置換
						$send_subject =~ s/<${elements_id}>/$getElementById{$elements_id}/g;
						#クライアント宛の送信元の置換(セキュア上良くないので、基本は使わない)
						$mailform_sender_address =~ s/<${elements_id}>/$getElementById{$elements_id}/g;
						$mailform_sender_address_name =~ s/<${elements_id}>/$getElementById{$elements_id} 様/g;
					}
					# 入力値を反映させる
					if($send_mailaddress =~ /$elements_id/){
						$send_mailaddress_work = "";
						@send_mailaddress_arr = split(/,/,$send_mailaddress);
						for($send_mailaddress_cnt=0; $send_mailaddress_cnt<@send_mailaddress_arr; $send_mailaddress_cnt++){
							if($send_mailaddress_arr[$send_mailaddress_cnt] =~ /$elements_id/){
								$send_mailaddress_arr[$send_mailaddress_cnt] =~ s/$send_mailaddress_arr[$send_mailaddress_cnt]/$getElementById{$elements_id}/g;
								$send_mailaddress_work .= "$send_mailaddress_arr[$send_mailaddress_cnt],";
							}else{
								$send_mailaddress_work .= "$send_mailaddress_arr[$send_mailaddress_cnt],";
							}
						}
						$send_mailaddress = $send_mailaddress_work;
					}
					# 入力値を反映させる
					if($cc =~ /$elements_id/){
						$cc_work = "";
						@cc_arr = split(/,/,$cc);
						for($cc_cnt=0; $cc_cnt<@cc_arr; $cc_cnt++){
							if($cc_arr[$cc_cnt] =~ /$elements_id/){
								$cc_arr[$cc_cnt] =~ s/$cc_arr[$cc_cnt]/$getElementById{$elements_id}/g;
								$cc_work .= "$cc_arr[$cc_cnt],";
							}else{
								$cc_work .= "$cc_arr[$cc_cnt],";
							}
						}
						$cc = $cc_work;
					}
					# 入力値を反映させる
					if($bcc =~ /$elements_id/){
						$bcc_work = "";
						@bcc_arr = split(/,/,$bcc);
						for($bcc_cnt=0; $bcc_cnt<@bcc_arr; $bcc_cnt++){
							if($bcc_arr[$bcc_cnt] =~ /$elements_id/){
								$bcc_arr[$bcc_cnt] =~ s/$bcc_arr[$bcc_cnt]/$getElementById{$elements_id}/g;
								$bcc_work .= "$bcc_arr[$bcc_cnt],";
							}else{
								$bcc_work .= "$bcc_arr[$bcc_cnt],";
							}
						}
						$bcc = $bcc_work;
					}
				}
				
				#汚染チェック 件名
				$send_subject =~ s/\@/@/g;
				$send_subject =~ s/\././g;
				$send_subject =~ s/\+/+/g;
				$send_subject =~ s/\-/-/g;
				$send_subject =~ s/\:/:/g;
				$send_subject =~ s/\;/;/g;
				$send_subject =~ s/\|/|/g;
				$send_subject =~ s/\n//g;
				$send_subject =~ s/\r//g;
				
				#汚染チェック 送信元
				$mailform_sender_address =~ s/\;/;/g;
				$mailform_sender_address =~ s/\n//g;
				$mailform_sender_address =~ s/\r//g;
				
				#汚染チェック 送信元
				$mailform_sender_address_name =~ s/\;/;/g;
				$mailform_sender_address_name =~ s/\n//g;
				$mailform_sender_address_name =~ s/\r//g;
				
				# 機種依存文字サニタイズ
				$mailform_sender_address_name = &sanitizing_str($mailform_sender_address_name);
				$mailform_sender_address_name = &sanitizing_str2($mailform_sender_address_name);
				$send_subject = &sanitizing_str($send_subject);
				$send_subject = &sanitizing_str2($send_subject);
				$send_body = &sanitizing_str($send_body);
				$send_body = &sanitizing_str2($send_body);
			
				# 多言語対応
				if($charset ne 'utf8'){
					# 多言語対応でない
					$mailform_sender_address_from = "$mailform_sender_address_name <$mailform_sender_address>";
					#一端utf8からsjisに変換し、その後にjisに変換しないと、utf8からjisの場合、一部文字化ける
					Jcode::convert(\$mailform_sender_address_from,"sjis","utf8");
					$mailform_sender_address_from = &encodeJIS($mailform_sender_address_from);
					$mailform_sender_address_from = Jcode->new($mailform_sender_address_from)->mime_encode;
				}else{
					# 多言語対応
					$mailform_sender_address_from = "=?UTF-8?B?" . encode_base64($mailform_sender_address_name) . '?=' . "<$mailform_sender_address>";
					$mailform_sender_address_from =~ s/\n//ig;
				}
				
				#$send_mail_body =~ s/<message>/$send_body/g;
				$send_mail_body = $send_body;
				
				
				# 多言語対応
				if($charset ne 'utf8'){
					# 多言語対応でない
					$send_mail_body = &encodeJIS($send_mail_body);
				}
				
#				#一端utf8からsjisに変換し、その後にjisに変換しないと、utf8からjisの場合、一部文字化ける
#				Jcode::convert(\$send_subject,"sjis","utf8");
				# 多言語対応
				if($charset ne 'utf8'){
					# 多言語対応でない
					$send_subject = &encodeJIS($admin_subject_serial . $send_subject);
					$send_subject = Jcode->new($send_subject)->mime_encode;
				}else{
					# 多言語対応
					$send_subject = "=?UTF-8?B?" . encode_base64($admin_subject_serial . $send_subject) . '?=';
					$send_subject =~ s/\n//ig;
				}
				if(@file_paths > 0 && !($attached_mode)){
					sendAttachMail($mailform_sender_address_from,$send_mailaddress,$cc,$bcc, $send_subject, $send_mail_body, @file_datas, @file_paths);
				}
				else {
					&sendmail($send_mailaddress,$cc,$bcc,$mailform_sender_address,$mailform_sender_address_from,$send_subject,$send_mail_body);
				}
			}
		}
	}
	
	
	
	# ----------------------------------------------------------------
	## mail log save proccess
	# ----------------------------------------------------------------
	if($logsave){
		# 本番ログデータ
		$cartstmp = sprintf("%04d-%02d",$year,$mon);
		
		if($logdata_path eq $null){
			$logdata_path = './fmail.admin/datas/maillog/mail_logdata' . '-' . $cartstmp . '.cgi';
		} else {
			$logdata_path = $logdata_path . 'mail_logdata' . '-' . $cartstmp . '.cgi';
		}
		# バックアップデータ
		$logdata_bu_path = $logdata_path . '.backup';
		
		# save判定用フラグ初期化
		$flag_savelog = 1;
		
		# 書き込みデータの精査
		$csv_fields = join("\t",@csv_fields);
		$csv_fields =~ s/\r\n/
/g;
		$csv_fields =~ s/\n/
/g;
		$csv_fields =~ s/\r//g;
		
		while($flag_savelog == 1){
			# 保存前容量のチェック
			# 本番ファイル
			$logdata_capacity = -s $logdata_path;
			# BUファイル
			$logdata_bu_capacity = -s $logdata_bu_path;
			
			# 本番とBUファイル容量比較
			if($logdata_capacity < $logdata_bu_capacity){
				# 本番ファイルが壊れている可能性あり
				copy($logdata_bu_path, $logdata_path);
			}elsif($logdata_capacity > $logdata_bu_capacity){
				# BUファイルが壊れている可能性あり
				copy($logdata_path, $logdata_bu_path);
			}
			# ここまでで、本番=BUとなっている
			
			
			# 保存前容量のチェック
			# 本番ファイル
			$logdata_capacity = -s $logdata_path;
			
			# 本番ファイル保存
			&mfp_SaveAddLine($logdata_path,$csv_fields);
			
			# 本番ファイル保存後容量のチェック
			$logdata_after_capacity = -s $logdata_path;
			
			# 本番ファイル保存前と保存後の容量を比較
			if($logdata_capacity < $logdata_after_capacity){
				# 保存後の方が容量大。正常保存と判断。バックアップデータを作成。
				copy($logdata_path, $logdata_bu_path);
				# 正常保存なので、ループエンドさせる為、フラグを折る
				$flag_savelog = 9;
			}else{
				# 保存後の方が容量小。保存失敗と判断。バックアップデータから復旧。
				copy($logdata_bu_path, $logdata_path);
			}
		}
		chmod 0600, "$logdata_bu_path";
	}
	
	
	
	# ----------------------------------------------------------------
	## cart log save proccess
	# ----------------------------------------------------------------
	# Cartitems Temporary Data
	$temp_file_cartitems = './cart/cart.admin/datas/cart.items/';
	
	# セッションチェック
		
	#-- Get the whole Cookie --#
	my %cookies = fetch CGI::Cookie;
	#-- Gets the value of the Cookie --#
	if(exists $cookies{'socket'}){
		$cookies_value = $cookies{'socket'}->value; #値
		$cookies_expires = $cookies{'socket'}->expires; #賞味期限
		$cookies_domain  = $cookies{'socket'}->domain;  #有効なドメイン
		$cookies_path = $cookies{'socket'}->path; #有効なパス
	}
	
	$cartitems_file = $temp_file_cartitems . $cookies_value . '.cgi';
	
	if($cart_logsave){
		# 本番ログデータ
		$cartstmp = sprintf("%04d-%02d",$year,$mon);
		
		if($cart_logdata_path eq $null){
			$cart_logdata_path = './fmail.admin/datas/cartlog/cart_logdata' . '-' . $cartstmp . '.cgi';
		} else {
			$cart_logdata_path = $cart_logdata_path . 'cart_logdata' . '-' . $cartstmp . '.cgi';
		}
		
		# バックアップデータ
		$logdata_bu_path = $cart_logdata_path . '.backup';
		
		
		open(CART,"<$cartitems_file");
			while($cart_table = ) {
				# カート内データの整形
				$cart_table =~ s/\r//g;
				$cart_table =~ s/\n//g;
				@cart_table_arr = split(/,/,$cart_table);
				
				# save判定用フラグ初期化
				$flag_savelog = 1;
				
				# 書き込みデータの精査
				$csv_fields = "$cookies_value\t";
				$csv_fields .= join("\t",@cart_table_arr);
				$csv_fields .= "\t";
				$csv_fields .= join("\t",@csv_fields);
				$csv_fields =~ s/\r\n/
/g;
				$csv_fields =~ s/\n/
/g;
				$csv_fields =~ s/\r//g;
				
				while($flag_savelog == 1){
					# 保存前容量のチェック
					# 本番ファイル
					$logdata_capacity = -s $cart_logdata_path;
					# BUファイル
					$logdata_bu_capacity = -s $logdata_bu_path;
					
					# 本番とBUファイル容量比較
					if($logdata_capacity < $logdata_bu_capacity){
						# 本番ファイルが壊れている可能性あり
						copy($logdata_bu_path, $cart_logdata_path);
					}elsif($logdata_capacity > $logdata_bu_capacity){
						# BUファイルが壊れている可能性あり
						copy($cart_logdata_path, $logdata_bu_path);
					}
					# ここまでで、本番=BUとなっている
					
					
					# 保存前容量のチェック
					# 本番ファイル
					$logdata_capacity = -s $cart_logdata_path;
					
					# 本番ファイル保存
					&mfp_SaveAddLine($cart_logdata_path,$csv_fields);
					
					# 本番ファイル保存後容量のチェック
					$logdata_after_capacity = -s $cart_logdata_path;
					
					# 本番ファイル保存前と保存後の容量を比較
					if($logdata_capacity < $logdata_after_capacity){
						# 保存後の方が容量大。正常保存と判断。バックアップデータを作成。
						copy($cart_logdata_path, $logdata_bu_path);
						# 正常保存なので、ループエンドさせる為、フラグを折る
						$flag_savelog = 9;
					}else{
						# 保存後の方が容量小。保存失敗と判断。バックアップデータから復旧。
						copy($logdata_bu_path, $cart_logdata_path);
					}
				}
				chmod 0600, "$logdata_bu_path";
			}
		close(CART);
	}
	
	
	
	
	## att delete prrocess
	if(!$attached_mode){
		for($cnt=0;$cnt<@unlinkpath;$cnt++){
			unlink $unlinkpath[$cnt];
		}
	}
	
	if($thanks_page ne $null){
		$redirect = $thanks_page;
	}
	else {
		# カートデータの削除
		&cart_del;
		
		# 完了ページへのリダイレクト
		$redirect = 'fmail.cgi?mode=thanks' . $sesQuery;
	}
	$session = "";
}
elsif($_GET{'mode'} eq "thanks"){
	#送信完了画面
	$title = $title_thanks;
	$title_body = '' . $title_thanks . '';
	$contents = "${thanks_message}
";
		#HTML装飾を許可にしている。不要ならコメントアウト
		$contents =~ s/<//g;
	#トップへ戻るボタン追加
	if($site_url){
		$contents .= "\n\nトップページへ
\n\n";
	}
	#アフィリエイトタグ追加
	if($flag_afiri){
		$afiri_tag =~ s/<//g;;
		$contents .= "$afiri_tag\n";
	}
}
elsif($_GET{'mode'} eq "confirm"){
	#確認画面
	unlink $send_token;
	##create session
	$q = new CGI;
	@session_data = ();
	%judge_value = ();
	%filetype_error = ();
	%filetype_name = ();
	$file_error_flag = 0;
	
	%sanitizing_error = ();
	$sanitizing_error_flag = 0;
	%sanitizing_value = ();
	
	##match pref
	@match_elements = ();
	%match_elements_vals = ();
	@names = $q->param;
	for($cnt=0;$cnt<@names;$cnt++){
		$name = $names[$cnt];
		if(index($name,'_match') > -1){
			push @match_elements,$name;
			$match_elements_vals{$name} = $q->param($names[$cnt]);
			push @session_data,"${name}=$match_elements_vals{$name}";
			$matchObj .= "";
		}
	}
	$spam_flag = 1;
	$link_spam_flag = 0;
	for($cnt=0;$cnt<@elements;$cnt++){
		($elements_id,$num,$name,$type_of_element,$html_size,$html_rows,$html_cols,$html_id,$element_type,$check_type,$on_event,$on_focus,$text_min,$text_max,$enable_filetypes,$filesize_min,$filesize_max,$checked_min,$checked_max,$element_valus,$element_text,$html_example,$note) = split(/\t/,$elements[$cnt]);
		$elementname = "en${elements_id}";
		
		if($element_type ne "file"){
			@values = $q->param($elementname);
			$judge_value{$elements_id} = join('<-sp->',@values);
			for($i=0;$i<@values;$i++){
				## sanitizing
				if($element_type eq "text" || $element_type eq "textarea"){
					# 住所のみ正規化を外す
					if($check_type ne "addr"){
						$values[$i] = &sanitizing_str($values[$i]);
					}
					if(!($values[$i] !~ /[\x80-\xff]/)){
						$spam_flag = 0;
					}
					if($values[$i] =~ /\[\/url\]/si){
						$link_spam_flag = 1;
					}
					if($values[$i] =~ /\[\/link\]/si){
						$link_spam_flag = 1;
					}
					if($check_type ne "none" && $values[$i] ne $null){
						if($check_type eq "digit" && $values[$i] =~ /[^0-9.\-]/){
							$sanitizing_error{$elements_id} = "数字以外の文字が含まれています。
";
							push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
							$sanitizing_error_flag = 1;
						}
						if($check_type eq "demilit" && $values[$i] =~ /[^0-9.,\-]/){
							$sanitizing_error{$elements_id} = "数字以外の文字が含まれています。
";
							push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
							$sanitizing_error_flag = 1;
						}
						if($check_type eq "alphabet" && $values[$i] =~ /[^a-zA-Z]/){
							$sanitizing_error{$elements_id} = "半角英字以外の文字が含まれています。
";
							push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
							$sanitizing_error_flag = 1;
						}
						if($check_type eq "digitandalphabet" && $values[$i] =~ /[^a-zA-Z0-9]/){
							$sanitizing_error{$elements_id} = "半角英数字以外の文字が含まれています。
";
							push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
							$sanitizing_error_flag = 1;
						}
						if($check_type eq "mobilephone"){
							$tmp = $values[$i];
							$tmp =~ s/\-//g;
							$c = length($tmp);
							if($tmp =~ /[^0-9]/){
								$sanitizing_error{$elements_id} = "数字以外の文字が含まれています。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
							elsif($c != 11){
								$sanitizing_error{$elements_id} = "電話番号の桁数に誤りがあります。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
							else {
								$mobilephone[0] = substr($tmp, 0, 3);
								$mobilephone[1] = substr($tmp, 3, 4);
								$mobilephone[2] = substr($tmp, 7, 4);
								$values[$i] = join('-',@mobilephone);
							}
						}
						if($check_type eq "postcode"){
							$tmp = $values[$i];
							$tmp =~ s/\-//g;
							$c = length($tmp);
							if($tmp =~ /[^0-9]/){
								$sanitizing_error{$elements_id} = "数字以外の文字が含まれています。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
							elsif($c > 7){
								$sanitizing_error{$elements_id} = "郵便番号の桁数に誤りがあります。7桁以内で入力してください。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
							else {
								@mobilephone =();
								$mobilephone[0] = substr($tmp, 0, 3);
								if($c > 3){
									$mobilephone[1] = substr($tmp, 3, 4);
									$values[$i] = join('-',@mobilephone);
								}
							}
						}
						if($check_type eq "telephone"){
							$tmp = $values[$i];
							$tmp =~ s/\-//g;
							$tmp =~ s/\+//g;
							$c = length($tmp);
							if($tmp =~ /[^0-9]/){
								$sanitizing_error{$elements_id} = "数字以外の文字が含まれています。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
							elsif($c != 11 && $c != 10){
								# 固定電話だけでなく、携帯電話の入力も踏まえて、10桁と11桁を許可する
								$sanitizing_error{$elements_id} = "電話番号の桁数に誤りがあります。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
#							elsif(split(/\-/,$values[$i]) != 3){
#								$sanitizing_error{$elements_id} = "電話番号はハイフンで区切って入力してください。
";
#								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
#								$sanitizing_error_flag = 1;
#							}
						}
						#追加
						if($check_type eq "fax"){
							$tmp = $values[$i];
							$tmp =~ s/\-//g;
							$tmp =~ s/\+//g;
							$c = length($tmp);
							if($tmp =~ /[^0-9]/){
								$sanitizing_error{$elements_id} = "数字以外の文字が含まれています。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
							elsif($c != 10){
								$sanitizing_error{$elements_id} = "FAX番号の桁数に誤りがあります。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
#							elsif(split(/\-/,$values[$i]) != 3){
#								$sanitizing_error{$elements_id} = "FAX番号はハイフンで区切って入力してください。
";
#								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
#								$sanitizing_error_flag = 1;
#							}
						}
						if($check_type eq "mail"){
							if($values[$i] =~ /[^a-zA-Z0-9\.\@\-\_\+]/){
								$sanitizing_error{$elements_id} = "メールアドレスで使えない文字が含まれています。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
							elsif(split(/\@/,$values[$i]) != 2){
								$sanitizing_error{$elements_id} = "メールアドレスに誤りがあります。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
							elsif(!($values[$i] =~ /^([a-zA-Z0-9\.\-\/_]{1,})@([a-zA-Z0-9\.\-\/_]{1,})\.([a-zA-Z0-9\.\-\/_]{1,})$/)){
								$sanitizing_error{$elements_id} = "メールアドレスに誤りがあります。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
						}
						if($check_type eq "url"){
							$tmp = $values[$i];
							$c = length($tmp);
							if($tmp !~ /^http:\/\/.+/ && $tmp !~ /^https:\/\/.+/ ){
								$sanitizing_error{$elements_id} = "URLに誤りがあります。
";
								push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
								$sanitizing_error_flag = 1;
							}
						}
						if($check_type eq "addr" && $values[$i] =~ /[a-zA-Z0-9|-]/){
							$sanitizing_error{$elements_id} = "全て全角で入力してください。
";
							push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
							$sanitizing_error_flag = 1;
						}
					}
					$c = $values[$i];
					$c =~ s/[\r\n\s]//g; 
					$textsize = length($c);
					if(($text_min > $textsize && $text_min ne $null) || ($textsize > $text_max && $text_max ne $null)){
						$sanitizing_error{$elements_id} = "文字数は${text_min}文字から${text_max}文字の範囲で入力してください。
";
						push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
						$sanitizing_error_flag = 1;
					}
					
					## matching proccess
					$match_hash = $elementname . '_match';
					if(1 == grep(/^${match_hash}$/ig,@match_elements)){
						if($match_elements_vals{$match_hash} ne $values[$i]){
							$sanitizing_error{$elements_id} = "入力内容が確認用の内容と異なっています。
";
							push @session_data,"en${elements_id}_error=" . $sanitizing_error{$elements_id};
							push @session_data,"en${elements_id}_match=" . $match_elements_vals{$match_hash};
							$sanitizing_error_flag = 1;
						}
					}
					
					$sanitizing_value{$elements_id} = $values[$i];
				}
				$values[$i] =~ s/\=//g;
				$values[$i] =~ s/\&//g;
				$values[$i] =~ s/\n/<-br->/g;
				push @session_data,"en${elements_id}=${values[$i]}";
			}
		}
		else {
			if($q->param($elementname) ne $null){
				@enabled_filetypes = split(/\,/,$enable_filetypes);
				my $fH = $q->upload($elementname);
				@filenames = split(/\\/,$fH);
				$filename = $filenames[-1];
				@filetypes = split /\./,$filename;
				$filetype = $filetypes[-1];
				$save_file_name = "${attached_files_dir}${session}_${elementname}\.cgi";
				$file_bytes = 0;
				open (OUT, ">$save_file_name");
				binmode (OUT);
				while(read($fH, $buffer, 1024)){
					print OUT $buffer;
					$file_bytes += 1024;
				}
				close (OUT);
				close ($fH) if ($CGI::OS ne 'UNIX');
				chmod 0600, $save_file_name;
				$file_bytes = $file_bytes / 1024;
				if(1 == grep(/^${filetype}$/ig,@enabled_filetypes)){
					if(($filesize_min > $file_bytes && $filesize_min ne $null) || ($file_bytes > $filesize_max && $filesize_max ne $null)){
						unlink $save_file_name;
						$filetype_error{$elements_id} = "ファイルサイズは${filesize_min}KBから${filesize_max}KBの範囲で選択してください。
";
						push @session_data,"en${elements_id}_error=" . $filetype_error{$elements_id};
						$file_error_flag = 1;
					}
					else {
						$judge_value{$elements_id} = $fH;
						push @session_data,"en${elements_id}=${filename}";
						$filetype_name{$elementname} = $filename;
					}
				}
				else {
					unlink $save_file_name;
					$filetype_error{$elements_id} = "対応していないファイルが選択されています。
";
					push @session_data,"en${elements_id}_error=" . $filetype_error{$elements_id};
					$file_error_flag = 1;
				}
			}
		}
		## text format check
	}
	
	##must check
	$send_flag = 0;
	$error_code = "";
	@errorCounters = ();
	$flag_case_result = 0;
	for($cnt=0;$cnt<@must;$cnt++){
#		($conditional_id,$must_name,$error_message,$must_elements,$note) = split(/\t/,$must[$cnt]);
		($conditional_id,$must_name,$error_message,$must_elements,$note,$flag_case,$case_elements_id,$case_value) = split(/\t/,$must[$cnt]);
		@must_elements = split(/\&/,$must_elements);
		$must_flag = 1;
		$errorCounter = 0;
		# 条件による必須の変更
		# n個の条件指定を確認し、未合致の場合、すべて送信が適用される。
		# 条件指定に一度でも合致したら、他の条件はスルーさせる
		if($flag_case_result == 0){
			if($flag_case == 0){
				# 条件指定
				# 条件指定した値と、合致している時に適用
				if($case_value eq $judge_value{$case_elements_id}){
					for($i=0;$i<@must_elements;$i++){
						($elements_id,$elements_value) = split(/\=/,$must_elements[$i]);
						if($elements_value ne $null){
							# 条件指定の値と当該項目の値を比較
							if($elements_value eq "1" && $judge_value{$elements_id} eq $null){
								$must_flag = 0;
								$error_code = $conditional_id;
								$errorCounter++;
							}
							elsif($elements_value eq "1" && $judge_value{$elements_id} ne $null){
								
							}
							elsif($judge_value{$elements_id} ne $null) {
								@values = split(/<-sp->/,$judge_value{$elements_id});
								if(1 != grep(/^${elements_value}$/,@values)){
									$must_flag = 0;
									$error_code = $conditional_id;
									$errorCounter++;
								}
							}
							else {
								$must_flag = 0;
								$error_code = $conditional_id;
								$errorCounter++;
							}
						}
					}
					push @errorCounters,"${conditional_id}\t${errorCounter}";
					if($must_flag){
						$send_flag++;
					}
					# 条件指定で一致しているので、以降の処理は無視する為のフラグ
					$flag_case_result = 1;
				}
			}else{
				# すべて送信
				for($i=0;$i<@must_elements;$i++){
					($elements_id,$elements_value) = split(/\=/,$must_elements[$i]);
					if($elements_value ne $null){
						if($elements_value eq "1" && $judge_value{$elements_id} eq $null){
							$must_flag = 0;
							$error_code = $conditional_id;
							$errorCounter++;
						}
						elsif($elements_value eq "1" && $judge_value{$elements_id} ne $null){
							
						}
						elsif($judge_value{$elements_id} ne $null) {
							@values = split(/<-sp->/,$judge_value{$elements_id});
							if(1 != grep(/^${elements_value}$/,@values)){
								$must_flag = 0;
								$error_code = $conditional_id;
								$errorCounter++;
							}
						}
						else {
							$must_flag = 0;
							$error_code = $conditional_id;
							$errorCounter++;
						}
					}
				}
				push @errorCounters,"${conditional_id}\t${errorCounter}";
				if($must_flag){
					$send_flag++;
				}
			}
		}
	}
	
	## file error & format error
	if($file_error_flag){
		$send_flag = 0;
		$error_code = "";
	}
	if($sanitizing_error_flag){
		$send_flag = 0;
		$error_code = "";
	}
	
	## spam check
	if($spamcheck){
		if($spam_flag){
			$send_flag = 0;
			push @session_data,"spam_error=すべての入力項目が英数で入力されています。";
		}
		elsif($link_spam_flag){
			$send_flag = 0;
			push @session_data,"spam_error=スパム対策のため\[\/link\]や\[\/url\]が含まれる送信はできません。";
		}
	}
	
	if($send_flag > 0){
		$title = $title_confirm;
		$title_body = '' . $title_confirm . '';
		#モバイル判定
		if(!$flag_mua && !$flag_smartphone){
			$contents = "\n\n";
		$contents .= "\n";
			$contents .= "\n";
			
			# 戻るボタン
			$contents .= "\n";
			
		# スマートフォンアクセス時 --------------
		}elsif($flag_smartphone == 1){
			# 送信ボタン
			$contents .= "\n";
			
			# 戻るボタン
			$contents .= "\n";
			
		# PCアクセス時 --------------
		}else{
			# 戻るボタン
			$contents .= "\n";
			
			# 送信ボタン
			$contents .= "\n";
		}
		
		$contents .= "\n";
		&WppSaveLine("${sessions_files_dir}${session}_token\.cgi",$null);
	}
	else {
		@errorCounters = sort { (split(/\t/,$a))[1] <=> (split(/\t/,$b))[1]} @errorCounters;
		($error_code,$errorCounter) = split(/\t/,$errorCounters[0]);
		if($file_error_flag){
			$error_code = "";
		}
		else {
			push @session_data,"code=" . $error_code;
		}
		$session_data = join('&',@session_data);
		&WppSaveLine("${sessions_files_dir}${session}\.cgi",$session_data);
		$redirect = 'fmail.cgi?mode=error' . $sesQuery;
	}
}
else {
	#エラー出力処理
	unlink $send_token;
	$scriptObj = "\n\n";
	if($contents =~ /\$JsOperationFlag/){
		$contents =~ s/\n";
			$contents .= "\n";
			$contents .= "\n";
		}else{
			#JS利用不可能の場合
			$contents .= "\n";
		}
	#スマートフォンアクセスの場合
	}elsif($flag_smartphone == 1){
		if($flag_js){
			#JS利用可能の場合
			$contents .= "\n";
			$contents .= "\n";
			$contents .= "
\n";
			$contents .= "\n";
		}else{
			#JS利用不可能の場合
			$contents .= "\n";
		}
	#talbe定義の場合
	}elsif($display_mode eq "table"){
		$contents .= "\n";
		$contents .= "\n";
		$contents .= "\n";
		$contents .= "\n";
		$contents .= "
\n";
		$contents .= "\n";
	}#dl定義の場合
	else {
		$contents .= "\n";
		$contents .= "-  
 \n";
		$contents .= "- \n";
		$contents .= "\n";
		$contents .= "\n";
		$contents .= "\n";
		$contents .= "
 \n";
		$contents .= "
\n";
	}
	$contents .= "\n";
	$scriptObj .= "-->\n\n";
#	$scriptObj .= "\n\n";
	$contents .= $scriptObj;
}
## ケース1
#$cookie_path = $ENV{'SCRIPT_NAME'};
#@cookie_path = split(/\//,$cookie_path);
#$cookie_path[-1] = "";
#$cookie_path = join('/',@cookie_path);
## ケース2
#my $q = CGI->new();
#$cookie_path = $q->url();
##Preview-Server or not
##iCLUSTAの別サーバーのみ環境変数 HTTP_X_FUJITSUBO_PROXY が用意されており、別サーバーのFQDNがセットされている
#if ($ENV{'HTTP_X_FUJITSUBO_PROXY'}) {
#	$cookie_path =~ s/^http[s]?\:\/\///i;
#} else {
#	$cookie_path =~ s/^http[s]?\:\/\/.*?\///i;
#}
#$cookie_path = '/' . $cookie_path;
# ケース3
my $q = CGI->new();
$cookie_path = $q->self_url();
#Preview-Server or not
#iCLUSTAの別サーバーのみ環境変数 HTTP_X_FUJITSUBO_PROXY が用意されており、別サーバーのFQDNがセットされている
if ($ENV{'HTTP_X_FUJITSUBO_PROXY'}) {
	$cookie_path =~ s/^http[s]?\:\/\///i;
} else {
	$cookie_path =~ s/^http[s]?\:\/\/.*?\///i;
}
$cookie_path = '/' . $cookie_path;
#仕上げにファイル名を削除
$cookie_path =~ s/^([^\?]+\/).*$/$1/i;
if($redirect){
	print "Location: ${redirect}\n";
	print "Set-Cookie: session=${session}; path=${cookie_path}; \n\n";
}
else {
	$html =~ s/$tpl_symbol_title/$title/ig;
	$html =~ s/$tpl_symbol_title_body/$title_body/ig;
	$html =~ s/$tpl_symbol_body/$contents/ig;
	$html =~ s/$tpl_symbol_error/$error/ig;
	$html =~ s/$tpl_symbol_ver/$reg{'version'}/ig;
	print "Pragma: no-cache\n";
	print "Cache-Control: no-cache\n";
	print "Content-type: text/html; charset=UTF-8\n";
	print "Set-Cookie: session=${session}; path=${cookie_path}; \n\n";
	
	#追加プログラム---------------------------------------------------------------------
	#入力・確認・完了 各画面での表示非表示部分の切り分け処理(テンプレ依存)
	
	#エラー画面での処理部分----------------------------------
	if($_GET{'mode'} eq 'error'){
		$invisible = 0;
		$invisible_confirm = 0;
		$invisible_thanks = 0;
		
		$html_work = $html;
		@html_work2 = split(/\n/,$html_work);
		for($i=0;@html_work2>$i;$i++){
			#入力画面以降表示させない部分----------------------------------
			if($html_work2[$i] =~ //){
				#見えない箇所開始
				$invisible = 1;
			}
			if($html_work2[$i] =~ //){
				#見えない箇所終了
				$invisible = 9;
			}
			
			#確認画面で非表示させる部分----------------------------------
			#確認画面用
			if($html_work2[$i] =~ //){
				#見えない箇所開始
				$invisible_confirm = 1;
			}
			if($html_work2[$i] =~ //){
				#見えない箇所終了
				$invisible_confirm = 9;
			}
			#送信完了用
			if($html_work2[$i] =~ //){
				#見えない箇所開始
				$invisible_thanks = 1;
			}
			if($html_work2[$i] =~ //){
				#見えない箇所終了
				$invisible_thanks = 9;
			}
			
			if($invisible ne '1' && $invisible_confirm ne '1' && $invisible_thanks ne '1'){
					print "$html_work2[$i]\n";
			}
		}
		
	#確認画面での処理部分----------------------------------
	}elsif($_GET{'mode'} eq 'confirm'){
		$invisible = 0;
		$invisible_error = 0;
		$invisible_thanks = 0;
		
		$html_work = $html;
		@html_work2 = split(/\n/,$html_work);
		for($i=0;@html_work2>$i;$i++){
			#入力画面以降表示させない部分----------------------------------
			if($html_work2[$i] =~ //){
				#見えない箇所開始
				$invisible = 1;
			}
			if($html_work2[$i] =~ //){
				#見えない箇所終了
				$invisible = 9;
			}
			
			#確認画面で非表示させる部分----------------------------------
			#エラー表示用
			if($html_work2[$i] =~ //){
				#見えない箇所開始
				$invisible_error = 1;
			}
			if($html_work2[$i] =~ //){
				#見えない箇所終了
				$invisible_error = 9;
			}
			#送信完了用
			if($html_work2[$i] =~ //){
				#見えない箇所開始
				$invisible_thanks = 1;
			}
			if($html_work2[$i] =~ //){
				#見えない箇所終了
				$invisible_thanks = 9;
			}
			
			if($invisible ne '1' && $invisible_error ne '1' && $invisible_thanks ne '1'){
					print "$html_work2[$i]\n";
			}
		}
		
	#送信完了画面での処理----------------------------------
	}elsif($_GET{'mode'} eq 'thanks'){
		$invisible = 0;
		$invisible_error = 0;
		$invisible_confirm = 0;
		
		$html_work = $html;
		@html_work2 = split(/\n/,$html_work);
		
		&serials_read;
		
		for($i=0;@html_work2>$i;$i++){
			#入力画面以降表示させない部分----------------------------------
			if($html_work2[$i] =~ //){
				#見えない箇所開始
				$invisible = 1;
			}
			if($html_work2[$i] =~ //){
				#見えない箇所終了
				$invisible = 9;
			}
			
			#送信完了画面で表示させる部分----------------------------------
			#エラー画面用
			if($html_work2[$i] =~ //){
				#見える箇所開始
				$invisible_error = 1;
			}
			if($html_work2[$i] =~ //){
				#見える箇所終了
				$invisible_error = 9;
			}
			#確認画面用
			if($html_work2[$i] =~ //){
				#見える箇所開始
				$invisible_confirm = 1;
			}
			if($html_work2[$i] =~ //){
				#見える箇所終了
				$invisible_confirm = 9;
			}
			
			if($invisible ne '1' && $invisible_error ne '1' && $invisible_confirm ne '1'){
				#完了画面で出すアフィリエイトタグ対応のスタンパーの置換
				$timestamp = $stmp;
				$timestamp =~ s/-//g;
				$timestamp =~ s/://g;
				$timestamp =~ s/ //g;
				$afiri_uniq_id = "$timestamp$serial";
				$html_work2[$i] =~ s//$afiri_uniq_id/g;
				
				print "$html_work2[$i]\n";
			}
		}
		
	}else{
		
		#入力画面で非表示にする部分----------------------------------
		#エラー表示用
		$invisible_error = 0;
		#確認画面用
		$invisible_confirm = 0;
		#送信完了画面用
		$invisible_thanks = 0;
		
		$html_work = $html;
		@html_work2 = split(/\n/,$html_work);
		for($i=0;@html_work2>$i;$i++){
			#エラー画面
			if($html_work2[$i] =~ //){
				#見えない箇所開始
				$invisible_error = 1;
			}
			if($html_work2[$i] =~ //){
				#見える箇所終了
				$invisible_error = 9;
			}
			
			#確認画面
			if($html_work2[$i] =~ //){
				#見えない箇所開始
				$invisible_confirm = 1;
			}
			if($html_work2[$i] =~ //){
				#見える箇所終了
				$invisible_confirm = 9;
			}
			
			#送信完了画面
			if($html_work2[$i] =~ //){
				#見えない箇所開始
				$invisible_thanks = 1;
			}
			if($html_work2[$i] =~ //){
				#見える箇所終了
				$invisible_thanks = 9;
			}
			
			if($invisible_error ne '1' && $invisible_confirm ne '1' && $invisible_thanks ne '1'){
				print "$html_work2[$i]\n";
			}
		}
		
		#送信完了画面で表示させる部分----------------------------------
		
	}
	#追加プログラム---------------------------------------------------------------------
	#元のソース
	#print $html;
}
exit;
sub GET {
	$buffer = $ENV{'QUERY_STRING'};
	@pairs = split(/&/, $buffer);
	foreach $pair (@pairs) {
		($name, $value) = split(/=/, $pair);
		$name =~ tr/+/ /;
		$name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		$value =~ tr/+/ /;
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		$_GET{$name} = $value;
	}
}
sub escape {
	my($str) = @_;
	$str =~ s/\&/"/g;
	$str =~ s/\</g;
	$str =~ s/>/\>/g;
	$str =~ s/\n/
/g;
	return $str;
}
sub syslog {
	my($str) = @_;
	&WppSaveAddLine('debug.txt',$str);
}