<?php
/*----------------------------------------------------------------------------------------------------
// mailform - index.php
// version 2.0
// 2008/06/12
// Copyright (c) 2008 FOURDIGIT Inc.
//--------------------------------------------------------------------------------------------------*/
require_once("include.php");
require_once($_path['classes']."htmlfit.php");
$startSecond = getMicrotime4();



//----------------------------------------------------------------------------------------------------
/// init
//----------------------------------------------------------------------------------------------------
$outputArr = array();
$postArr = array();
$getArr = array();

foreach($_POST as $key=>$value) (is_array($value) ? $_POST[$key."[]"] = $value : "");

foreach($_GET as $key=>$value) $getArr[$key] = html_entity_decode(stripslashes((is_array($value) ? implode($_merge_multi, $value) : $value)), ENT_QUOTES);
foreach($_POST as $key=>$value) $postArr[$key] = html_entity_decode(stripslashes((is_array($value) ? implode($_merge_multi, $value) : $value)), ENT_QUOTES);
$mode = "";
(isset($getArr['formmode']) ? $mode = $getArr['formmode'] : "");
(isset($postArr['formmode']) ? $mode = $postArr['formmode'] : "");

$_tpl = array();
$_tpl['input']			= $_path['tpl']."tpl_input.html";
$_tpl['confirm']		= $_path['tpl']."tpl_confirm.html";
$_tpl['complete']		= $_path['tpl']."tpl_complete.html";
$_tpl['toAdminHead']	= $_path['tpl_mail']."mail_admin_header.txt";
$_tpl['toUserHead']		= $_path['tpl_mail']."mail_user_header.txt";
$_tpl['toAdminBody']	= $_path['tpl_mail']."mail_admin_body.txt";
$_tpl['toUserBody']		= $_path['tpl_mail']."mail_user_body.txt";

$htmlpage = new htmlfit();
$_loops = array();
foreach($_extlist as $key=>$value) $_loops[$key] = loadList($key, $value);

@header('Pragma: no-cache');
@header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
@header('Content-Type: text/html; '.STR_CHARSET);
//----------------------------------------------------------------------------------------------------
/// main
//----------------------------------------------------------------------------------------------------
$outputArr = processInput($postArr);
foreach($_global as $key=>$value) $outputArr["global_".$key] = $value;

if($mode != "confirm" && $mode != "complete"){
	$htmlpage->opentemplate($_tpl['input']);
}else{
	if(count($errArr = checkInput($outputArr)) > 0){
		$outputArr['err'] = TRUE;
		$outputArr = array_merge($outputArr, $errArr);
		$htmlpage->opentemplate($_tpl['input']);
	}else{
		if($mode == "confirm"){
			$htmlpage->opentemplate($_tpl['confirm']);
		}elseif($mode == "complete"){
			//get count if needed
			if($_count['flag']) $outputArr['global_count'] = getCount($_count['file']);

			//reset email if mailtype is on
			setAdminEmail($outputArr);
			//mail to admin if needed
			if($_mail['mailToAdmin']){
				$toStr = makeMbMailUser($_mail['adminEmail']);
				$subject = convertToB64($_mail['titleToAdmin']);
				$outputArr['fromstr'] = makeMbMailUser($_mail['emailToAdmin'], $_mail['nameToAdmin']);
				sendMessage($toStr, $subject, $outputArr, $_tpl['toAdminHead'], $_tpl['toAdminBody']);
			}
			//mail to user if needed
			if($_mail['mailToUser']){
				$toStr = makeMbMailUser($outputArr['mail']);
				$subject = convertToB64($_mail['titleToUser']);
				$outputArr['fromstr'] = makeMbMailUser($_mail['emailToUser'], $_mail['nameToUser']);
				sendMessage($toStr, $subject, $outputArr, $_tpl['toUserHead'], $_tpl['toUserBody']);
			}
			//writeToCsv if needed
			if($_csv['flag']) writeToCsv($_csv['file'], $outputArr);
			$htmlpage->opentemplate($_tpl['complete']);
		}
	}
}

$outputArr = formatKeys($outputArr);
foreach($_loops as $key=>$loop){
	foreach($loop as $num=>$loopKeys) $_loops[$key][$num] = formatKeys($loopKeys);
}

if(function_exists(outputCustom)) $outputArr = outputCustom($outputArr);
foreach($outputArr as $key=>$value) $htmlpage->setkey($key, $value);
foreach($_loops as $key=>$value) $htmlpage->setloop($key, processList($key, $value, $outputArr));
$htmlpage->replaceall();
if($_displayKeys) print_r($outputArr);
if($_displayKeys) print("\n".(getMicrotime4()-$startSecond));
$htmlpage->htmloutput();



//----------------------------------------------------------------------------------------------------
/// functions
//----------------------------------------------------------------------------------------------------
function processInput($inputArr){
	global $_merge;
	if(function_exists(processCustom)) $inputArr = processCustom($inputArr);
	$outputArr = array();
	$grpArr = array();
	foreach ($inputArr as $key => $val){
		$splited = explode("-", $key);
		if($inputArr[$splited[0].'detail%'.$val]) $val = $inputArr[$splited[0].'detail%'.$val];
		if(isset($splited[1]) && strpos($splited[1], "detail") === FALSE && $val != ""){
			$key = $splited[0];
			(!is_array($grpArr[$key]) ? $grpArr[$key] = array($val) : $grpArr[$key][] = $val);
		}
	}
	foreach($grpArr as $key=>$val){
		$sep = (array_key_exists($key, $_merge) ? $_merge[$key] : "/");
		$inputArr[$key] = implode($sep, $val);
	}
	foreach($inputArr as $key=>$value){
		$outputArr[$key] = $value;
		if($value !== FALSE && $value != ""){
			list($grp, $sub) = explode("-", $key);
			$outputArr["sel_".$grp."_%".$value] = TRUE;
		}
	}
	//j.suzuki edit 2017/12/13 start
	$outputArr = str_replace("&", "＆", $outputArr); 
	$outputArr = str_replace("<", "＜", $outputArr); 
	$outputArr = str_replace(">", "＞", $outputArr);
	//end

	return $outputArr;
}

function checkInput($inputArr){
	global $_check;
	$errArr = array();
	if(function_exists(checkCustom)) $errArr = checkCustom($inputArr);
	foreach($_check as $key=>$list){
		if($list == "") continue;
		$funcArr = explode(",", $list);
		foreach($funcArr as $num=>$funcName){
			$funcName = trim($funcName);
			$splited = explode("%", $funcName);
			$funcName = $splited[0];
			$param = (isset($splited[1]) ? $splited[1] : FALSE);
			$ret = FALSE;
			eval("\$ret = check_".$funcName."(\$inputArr, \$key, \$param);");
			if($ret){
				$errArr["err_".$key."_".$funcName] = TRUE;
				break;
			}
		}
	}
	return $errArr;
}

//rename name, inRowArr, inColArr, etc...
function loadList($name, $file){
	global $_check;
	$rowArr = array();
	$inRowArr = @file($file);
	if(!$inRowArr) return FALSE;
	foreach($inRowArr as $num=>$value){
		if(substr($value, 0, 2) != "//" && $value != ""){
			$inColArr = explode(",", trim($value));
			$colArr = array();
			$colArr['loopnum'] = $num;
			$colArr['loopname'] = $name."-".$num;
			$colArr['loopinitvalue'] = $inColArr[0];
			$colArr['loopcaption'] = $inColArr[1];
			$colArr['loophasdetail'] = ($inColArr[2] == "1" ? TRUE : FALSE);
			if($colArr['loophasdetail']){
				$colArr['loopdetailname'] = $name."detail%".$colArr['loopinitvalue'];
				$colArr['loopdetail'] = "";
			}
			$colArr['loop'] = "";
			$colArr['sel_loop'] = FALSE;
			if(isset($inColArr[3]) && $inColArr[3] != ""){
				$inColArr[3] .= "%".$colArr['loopinitvalue'];
				$_check[$name] = (isset($_check[$name]) ? $_check[$name].",".$inColArr[3] : $inColArr[3]);
			}
			$rowArr[] = formatKeys($colArr);
		}
	}
	return $rowArr;
}

//rename listArr,
function processList($name, $listArr, $inputArr){//inputArr to global?
	global $_check;
	if(!$listArr) return $listArr;
	foreach($listArr as $num=>$row){
		$listArr[$num]['loop'] = $inputArr[$row['loopname']];
		if($row['loophasdetail']) $listArr[$num]['loopdetail'] = $inputArr[$row['loopdetailname']];
		$listArr[$num]['sel_loop'] = ($inputArr[$row['loopname']] != "" || $inputArr[$name] == $row['loopinitvalue']);
		$listArr[$num] = formatKeys($listArr[$num]);
	}
	return $listArr;
}

//set adminEmail
function setAdminEmail($inputArr){
	global $_mail, $_mailtype;
	$field = $_mailtype['field'];
	if(isset($field) && is_string($field) && isset($inputArr[$field])) $_mail['adminEmail'] = $_mailtype['addrs'][$inputArr[$field]];
}



//----------------------------------------------------------------------------------------------------
/// tool functions
//----------------------------------------------------------------------------------------------------
function getCount($file){
	global $_count;
	$num = 0;
	if(file_exists($file)){
		$filenum = intval(implode("", @file($file)));
		if(is_int($filenum)) $num = $filenum;
	}
	$fp = @fopen($file,"w");
	@flock($fp,LOCK_EX);
	@fwrite($fp, ($num+1));
	@flock($fp,LOCK_UN);
	@fclose($fp);
	@chmod($file, 0777);
	return $num;
}

function writeToCsv($file, $inputArr){
	global $_csv, $_name;

	$isFirst = !file_exists($file);
	$rowArr = array();
	$headArr = array();
	foreach($_csv['cols'] as $key=>$value){
		$rowArr[$value] = "";
		if(isset($_name[$value])) {
			$headArr[$value] =  $_name[$value];
		}else{
			$splitArr = explode("-", $value);
			if(count($splitArr) > 1 && isset($_name[$splitArr[0]])) {
				$headArr[$value] = $_name[$splitArr[0]].$splitArr[1];
			} else {
				$headArr[$value] = $value;
			}
		}
	}
	foreach($inputArr as $key => $val){
		if(in_array($key, $_csv['cols'])){
			$fromArr = array("\r\n", "\r", "\n", "\"");//"
			$toArr = array(" ", " ", " ", "\"\"");
			$inputArr[$key] = str_replace($fromArr, $toArr, $inputArr[$key]);
			$rowArr[$key] = "\"".$inputArr[$key]."\"";
		}
	}
	$rowStr = implode(",", $rowArr)."\r\n";
	$headStr = implode(",", $headArr)."\r\n";
	$rowStr = mb_convert_encoding($rowStr, "SJIS", mb_internal_encoding());
	$headStr = mb_convert_encoding($headStr, "SJIS", mb_internal_encoding());
	$fp = @fopen($file,"a");
	@flock($fp,LOCK_EX);
	if($isFirst) @fwrite($fp, $headStr);
	@fwrite($fp, $rowStr);
	@flock($fp,LOCK_UN);
	@fclose($fp);
	@chmod($file, 0777);
	return TRUE;
}

function sendMessage($toStr, $subject, $outputArr, $tplHeader, $tplBody){
	$header = new htmlfit();
	$header->opentemplate($tplHeader);
	foreach($outputArr as $key=>$value) $header->setkey($key, $value);
	$header->replaceall();

	$body = new htmlfit();
	$body->opentemplate($tplBody);
	foreach($outputArr as $key=>$value) $body->setkey($key, $value);
	$body->replaceall();

	$body->output = mb_convert_encoding($body->output, "ISO-2022-JP", mb_internal_encoding());
	$header->output = mb_convert_encoding($header->output, "ISO-2022-JP", mb_internal_encoding());
	return (mail($toStr, $subject, $body->output, $header->output));
}

function makeMbMailUser($emails, $names = ""){
	if(!is_array($emails)){
		$email = $emails;
		$emails = array($email);
	}
	if(!is_array($names)){
		$name = $names;
		$names = array($name);
	}
	foreach($names as $num=>$value) $names[$num] = convertToB64($value);

	$mailArr = array();
	foreach($emails as $num=>$value){
		$mailArr[] = ($names[$num] != "" ? $names[$num]." <".$value.">" : $value);
	}
	return implode(", ", $mailArr);
}

function convertToB64($str){
	if(mb_detect_encoding($str) != "ASCII" && $str != ""){
		$str = mb_convert_encoding($str, "ISO-2022-JP", mb_detect_encoding($str));
		$str = "=?ISO-2022-JP?B?".base64_encode($str)."?=";
	}
	return $str;
}

?>
