<?php
/*
 * メールフォーム処理ブロック 2024/08/17
 */
$template = <<<END
<section class="block_form3">
<!--{def item/mode_form}-->
<!-- block_form3:フォーム3項目 -->
<a id="form"></a>
<style>.ta1 {table-layout:auto;}</style>
<h2>{val item/title}</h2>
<form name="form1" enctype="multipart/form-data" method="post" action="{val item/form_url}#form">
<input type="hidden" name="mode" value="form" />
<table class="ta1 mb1em">
<!-- 入力／確認 -->
<tr>
<th width="150">Name<span class="color-check">※</span></th>
<td>
<input name="item1" value="{val item/form/item1}" type="text" size="40" maxlength="500" class="ws" />
<!--{def item/msg/item1}--><div style="color:red">{val item/msg/item1}</div><!--{/def}-->
</tr>
<tr>
<th width="150">E-mail<span class="color-check">※</span></th>
<td>
<input name="item2" value="{val item/form/item2}" type="text" size="40" maxlength="500" class="ws" />
<!--{def item/msg/item2}--><div style="color:red">{val item/msg/item2}</div><!--{/def}-->
</tr>
<tr>
<th>Content<span class="color-check">※</span></th>
<td>
<textarea name="item3" cols="40" rows="10" class="wl">{val item/form/item3}</textarea>
<!--{def item/msg/item3}--><div style="color:red">{val item/msg/item3}</div><!--{/def}-->
</tr>

</table>
<div class="c">
<input type="submit" value="Confirm input" class="btn" />
&nbsp;&nbsp;
<input type="reset" value="Reset" class="btn" />
</div>
</form>
<!-- フォームの情報はここまでです -->
<!--{/def}-->
<!--{def item/mode_confirm}-->
<!-- フォームの情報はここからです -->
<a id="form"></a>
<h2>{val item/title}</h2>
<style>.ta1 {table-layout:auto;}</style>
<form name="form1" method="post" action="{val item/form_url}#form">
<input type="hidden" name="mode" value="confirm" />
<table class="ta1 mb1em">
<tr><td colspan="2" class="auto"><strong>以下の内容で良ければ、送信してください。</strong></td></tr>
<!-- 入力／確認 -->
<tr><th class="tamidashi" colspan="2">{val item/title}</th></tr>
<tr>
<th width="150">Name<span class="color-check">※</span></th>
<td>
<input type="hidden" name="item1" value="{rval item/form/item1}">
{val item/form/item1}</td>
</tr>
<tr>
<th width="150">E-mail<span class="color-check">※</span></th>
<td>
<input type="hidden" name="item2" value="{rval item/form/item2}">
{val item/form/item2}</td>
</tr>
<tr>
<th>Content<span class="color-check">※</span></th>
<td>
<input type="hidden" name="item3" value="{rval item/form/item3}">
{val item/form/item3}</td>
</tr>
</table>
<div class="c">
<input type="submit" value="Send" class="btn" />
&nbsp;&nbsp;
<input type="button" value="Back to input" onClick="document.form1.mode.value='reinput';document.form1.submit()" class="btn" />
</div>
</form>
<!-- フォームの情報はここまでです -->
<!--{/def}-->
<!--{def item/mode_finish}-->
<!-- フォームの情報はここからです -->
<a id="form"></a>
<style>.ta1 {table-layout:auto;}</style>
<h2>{val item/title}</h2>
<form name="form1" enctype="multipart/form-data" method="post" action="{val item/form_url}#form">
<input type="hidden" name="mode" value="finish" />
<!-- 処理終了 -->
<p>Thank you for contacting us.</p>
</form>
<!-- フォームの情報はここまでです -->
<!--{/def}-->
</section>
END;

$block_form3 = array(						// ブロック
	"title" => "お問い合わせフォーム(英語版3項目)",	// ブロックの名称
	"name" => "block_form3",				// 名称、重複すると正しく動作しません
	"template" => $template,		// ブロックのテンプレート
	"input" => array(				// ブロックの入力定義
		"help" => array(
			"title" => "使い方",
			"type" => "comment",
			"link" => DOCUMENT1 . "/?act=block_form3",
			"class" => "notice",
		),
		"title" => array(
			"title" => "フォームタイトル",
			"type" => "text",
			"info" => "",
		),
		"mail_sys" => array(
			"title" => "管理者のメールアドレス",
			"type" => "text",
			"info" => "お問い合わせがあった場合に通知されるメールアドレス",
		),
		"from_name" => array(
			"title" => "メール送信者の表示",
			"type" => "text",
			"info" => "メールの送信者として表示される名称",
			"placeholder" => "例：〇×サイト管理者",
		),
		"from_mail" => array(
			"title" => "返信先メールアドレス",
			"type" => "text",
			"info" => "お問い合わせの返信先のメールアドレス",
		),
		"mail_subject" => array(
			"title" => "件名",
			"type" => "text",
			"info" => "お問い合わせをした人へのメール件名",
			"placeholder" => "例：お問い合わせありがとうございます",
		),
		"mail_body" => array(
			"title" => "メール本文",
			"type" => "textarea2",
			"info" => "お問い合わせをした人へのメール本文",
			"placeholder" => "例：次の内容でお問い合わせを受け付けました。",
		),
		"subject_sys" => array(
			"title" => "管理者向件名",
			"type" => "text",
			"info" => "管理者へのメールの件名",
			"placeholder" => "例：お問い合わせがありました",
		),
		"body_sys" => array(
			"title" => "管理者向本文",
			"type" => "textarea2",
			"info" => "管理者へのメールの本文",
			"placeholder" => "例：次のお問い合わせへの対応をお願いします。",
		),
		"mail_footer" => array(
			"title" => "署名",
			"type" => "textarea2",
			"info" => "メールの最後に追加される署名",
		),
	),
	"func" => "func_block_form3",
);

block_add($block_form3);

//------------------------------------------------
// 入力設定
$form_input = array(
	"item1" => array("title" => "Name", "name" => "item1", "func" => "2", "require" => "1", "check" => "1",),
	"item2" => array("title" => "E-Mail", "name" => "item2", "func" => "2", "require" => "1", "check" => "3",),
	"item3" => array("title" => "Content", "name" => "item3", "func" => "7", "require" => "1", "check" => "1",),

);
//------------------------------------------------
define("SCRIPT_ENCODING", "UTF-8");
define("MAIL_ENCODING", "JIS");

function func_block_form3($def, $info)
{
	global $form_input;

	$user_mail = "item2";	// 利用者にメールを送る場合のメールアドレス項目
	$title = "お問い合わせ";

	// セッションを使用します（セッションが有効で無いとキャプチャは動作しません）
	session_start();

	// 入力値の取得
	$msg = array();
	$mail = array();
	$mail_field = array();
	foreach ($form_input as $val) {
		$value = 0;
		if ($val["func"] == 6) {
			if (is_array($_REQUEST[$val["name"]])) {
				foreach ($_REQUEST[$val["name"]] as $k => $v) {
					$form[$val["name"]][$k] = htmlspecialchars($v);
					if ($v) {
						$value = 1;
					}
				}
			} else {
				$form[$val["name"]] = htmlspecialchars($_REQUEST[$val["name"]]);
				if ($form[$val["name"]]) {
					foreach ($form[$val["name"]] as $v) {
						if ($v != "") {
							$value = 1;
						}
					}
				}
			}
		} else if ($val["func"] == 10) {
			$form[$val["name"] . "_pref"] = htmlspecialchars($_REQUEST[$val["name"] . "_pref"]);
			$form[$val["name"] . "_address"] = htmlspecialchars($_REQUEST[$val["name"] . "_address"]);
			if ($form[$val["name"] . "_pref"] && $form[$val["name"] . "_address"]) {
				$value = 1;
			}
		} else if ($val["func"] == 11) {
			$form[$val["name"] . "_year"] = htmlspecialchars($_REQUEST[$val["name"] . "_year"]);
			$form[$val["name"] . "_month"] = htmlspecialchars($_REQUEST[$val["name"] . "_month"]);
			$form[$val["name"] . "_day"] = htmlspecialchars($_REQUEST[$val["name"] . "_day"]);
			if ($form[$val["name"] . "_year"] && $form[$val["name"] . "_month"] && $form[$val["name"] . "_day"]) {
				$value = 1;
			}
		} else if ($val["func"] == 12) {
			$form[$val["name"] . "_month"] = htmlspecialchars($_REQUEST[$val["name"] . "_month"]);
			$form[$val["name"] . "_day"] = htmlspecialchars($_REQUEST[$val["name"] . "_day"]);
			if ($form[$val["name"] . "_month"] && $form[$val["name"] . "_day"]) {
				$value = 1;
			}
		} else if ($val["func"] == 13) {	// File
			if ($_FILES[$val["name"]]["name"]) {
				// 添付ファイルへの処理をします。
				$handle = fopen($_FILES[$val["name"]]["tmp_name"], 'r');
				$attachFile = fread($handle, filesize($_FILES[$val["name"]]["tmp_name"]));
				fclose($handle);
				$attachEncode = base64_encode($attachFile);
				$form[$val["name"] . "_value"] = $attachEncode;
				$form[$val["name"] . "_file"] = $_FILES[$val["name"]]["name"];
				$form[$val["name"] . "_type"] = $_FILES[$val["name"]]["type"];
				$value = 1;
			} else if ($_REQUEST[$val["name"] . "_value"]) {
				$form[$val["name"] . "_value"] = $_REQUEST[$val["name"] . "_value"];
				$form[$val["name"] . "_file"] = $_REQUEST[$val["name"] . "_file"];
				$form[$val["name"] . "_type"] = $_REQUEST[$val["name"] . "_type"];
				$value = 1;
			}
		} else {
			if (is_array($_REQUEST[$val["name"]])) {
				foreach ($_REQUEST[$val["name"]] as $k => $v) {
					$form[$val["name"]][$k] = htmlspecialchars($v);
					if ($v) {
						$value = 1;
					}
				}
			} else {
				$form[$val["name"]] = htmlspecialchars($_REQUEST[$val["name"]]);
				if ($form[$val["name"]]) {
					$value = 1;
				}
			}
		}
		// 入力のチェック
		if ($_REQUEST["mode"] == "form") {
			if ($val["require"] && ($value == 0)) {
				$msg[$val["name"]] = $val["title"] . " required";
			}
			if ($val["check"] && $value) {
				if ($val["check"] == 2) {	// 電話
					if (!preg_match("/^[0-9\-]+$/", $form[$val["name"]])) {
						$msg[$val["name"]] = $val["title"] . " is incorrect";
					}
				}
				if (($val["check"] == 3)||($val["check"] == 4)) {	// メール
					if (!preg_match("/^[0-9a-zA-Z_\.\-]+@[0-9a-zA-Z_\.\-]+$/", $form[$val["name"]])) {
						$msg[$val["name"]] = $val["title"] . " is incorrect";
					} else {
						$mail_value[] = $form[$val["name"]];
						$mail_field[] = $val["name"];
						$mail_title[] = $val["title"];
					}
				}
				if ($val["check"] == 5) {	// URL
					if (!preg_match("/^(http|https):\/\/[0-9a-zA-Z_\.\-\/]+$/", $form[$val["name"]])) {
						$msg[$val["name"]] = $val["title"] . " is incorrect";
					}
				}
				if ($val["check"] == 6) {	// キャプチャ
					if ($form[$val["name"]] != $_SESSION["captcha"]) {
						$msg[$val["name"]] = $val["title"] . " do not match";
						$form[$val["name"]] = "";
					}
				}
			}
		}
	}
	// メール一致
	if (x_count($mail_value) == 2) {
		if ($mail_value[0] != $mail_value[1]) {
			$msg[$mail_field[0]] = $mail_title[0] . " do not match";
			$msg[$mail_field[1]] = $mail_title[0] . " do not match";
		}
	}
	if (!$_REQUEST["mode"]) {
		$mode = "form";
		$info["mode_form"] = "1";
	} else if ($_REQUEST["mode"] == "reinput") {
		$mode = "form";
		$info["mode_form"] = "1";
	} else if ($_REQUEST["mode"] != "confirm") {
		if ($msg) {
			$mode = "form";
			$info["mode_form"] = "1";
		} else {
			$mode = "confirm";
			$info["mode_confirm"] = "1";
		}
	} else {
		// メールの送信
		// 本文へ入力値の設定
		foreach ($form_input as $key => $val) {
			if ($val["func"] == 13) {	// File
				$mail_body .= "◆" . $val["title"] . "：" . $form[$val["name"] . "_file"] . "\n";
			} else if ($val["func"] == 10) {
				$mail_body .= "◆" . $val["title"] . "：" . $pref_list[$form[$val["name"] . "_pref"]] . $form[$val["name"] . "_address"] . "\n";
			} else if ($val["func"] == 11) {
				$mail_body .= "◆" . $val["title"] . "：" . $form[$val["name"] . "_year"] . "年" . 
					$form[$val["name"] . "_month"] . "月" . $form[$val["name"] . "_day"] . "日\n";
			} else if ($val["func"] == 12) {
				$mail_body .= "◆" . $val["title"] . "：" . $form[$val["name"] . "_month"] . "月" . $form[$val["name"] . "_day"] . "日\n";
			} else if ($val["func"] == 3) {	// 単一選択（ラジオボタン）
				$mail_body .= "◆" . $val["title"] . "：" . $form_input[$val["name"]]["list"][$form[$val["name"]]] . "\n";
			} else if ($val["func"] == 4) {	// 複数選択（チェックボックス）
				if ($form[$val["name"]]) {
					$ary = array();
					foreach ($form[$val["name"]] as $val2) {
						$ary[] = $form_input[$val["name"]]["list"][$val2];
					}
					$mail_body .= "◆" . $val["title"] . "：" . implode("、", $ary) . "\n";
				}
			} else if ($val["func"] == 5) {	// 選択（プルダウン）
				$mail_body .= "◆" . $val["title"] . "：" . $form_input[$val["name"]]["list"][$form[$val["name"]]] . "\n";
			} else if ($val["func"] == 6) {	// 複数個1行テキスト入力
				$mail_body .= "◆" . $val["title"] . "：\n";
				foreach ($form_input[$val["name"]]["list"] as $key => $val2) {
					$mail_body .= "　" . $val2 . "：" . $form[$val["name"]][$key] . "\n";
				}
			} else if ($val["func"] == 14) {	// キャプチャ
				// キャプチャが存在する場合、そのチェックが通らないとメールの送信はしない
				if (($form[$val["name"]] == "")||($_SESSION["captcha"] == "")) {
					exit;
				}
				if ($_SESSION["captcha"] != $form[$val["name"]]) {
					exit;
				}
			} else {
				$mail_body .= "◆" . $val["title"] . "：" . $form[$val["name"]] . "\n";
			}
		}
		unset($_SESSION["captcha"]);
		$mail_body .= $info["mail_footer"];
		$attach = array();
		foreach ($form_input as $val) {
			if ($val["func"] == 13) {	// File
				if ($_REQUEST[$val["name"] . "_value"]) {	// 添付ファイルあり
					$attach[] = array(
						"filebody" => $_REQUEST[$val["name"] . "_value"],
						"filename" => $_REQUEST[$val["name"] . "_file"],
						"filetype" => $_REQUEST[$val["name"] . "_type"]);
				}
			}
		}
		if ($info["mail_sys"]) {
			// 管理者向け
			sendmail($info["from_mail"], $info["mail_sys"], $info["subject_sys"], $info["body_sys"] . $mail_body, $attach, $info["from_name"]);
		}
		//
		if (isset($user_mail) && $_REQUEST[$user_mail]) {
			// 利用者向け
			sendmail($info["from_mail"], $_REQUEST[$user_mail], $info["mail_subject"], $info["mail_body"] . $mail_body, $attach, $info["from_name"]);
		}
		//
		$mode = "finish";
		$info["mode_finish"] = "1";
	}
	//
	$info["msg"] = $msg;
	$info["form"] = $form;
	$info["form_url"] = $_SERVER["REQUEST_URI"];
	return $info;
}

/*
 * メール送信処理、本文を変数から
 *
 * 差し込み処理、長いサブジェクトに対応
 */
function sendmail($mail_from, $mail_to, $mail_subject, $body, $attach, $from_name=null)
{
	$mail_from = trim($mail_from);
	$mail_to = trim($mail_to);
	$mail_subject = trim($mail_subject);
	$body = html_entity_decode(trim($body));
	$reply = trim($reply);
	$from_name = trim($from_name);
	// 送信元情報の作成
	if ($from_name) {
		$header = "From: ";
		if (MAIL_ENCODING == "UTF8") {
			$header .= '=?utf-8?B?';
		} else {
			$header .= '=?iso-2022-jp?B?';
		}
		$header .= base64_encode(mb_convert_encoding($from_name, MAIL_ENCODING, SCRIPT_ENCODING)) .
			 '?= <' . $mail_from . ">";
	} else {
		$header = "From: " . $mail_from;
	}
	if ($attach) {	// ファイル添付
		$uniq_id = uniqid('boundary');
		$header .= "\r\nMIME-Version: 1.0";
		$header .= "\r\nContent-Type: multipart/mixed; boundary=\"" . $uniq_id . "\"\r\n";
		// 本文の加工
		$mailMessage = $body;
		$body  = "--" . $uniq_id . "\r\n";
		if (MAIL_ENCODING == "UTF8") {
			$body .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";
		} else {
			$body .= "Content-Type: text/plain; charset=\"ISO-2022-JP\"\r\n";
		}
		$body .= "\r\n";
		$body .= $mailMessage . "\r\n";

		foreach ($attach as $val) {
			$filename = $val["filename"];
			$filebody = $val["filebody"];
			$filetype = $val["filetype"];

			if (MAIL_ENCODING == "UTF8") {
				$fname = '=?utf-8?B?' . base64_encode(mb_convert_encoding($filename, MAIL_ENCODING, SCRIPT_ENCODING)) . '?=';
			} else {
				$fname = '=?iso-2022-jp?B?' . base64_encode(mb_convert_encoding($filename, MAIL_ENCODING, SCRIPT_ENCODING)) . '?=';
			}

			$body .= "--" . $uniq_id . "\r\n";

			$body .= "Content-Type: $filetype; name=\"$filename\"\r\n";
			$body .= "Content-Transfer-Encoding: base64\r\n";
			$body .= "Content-Disposition: attachment; filename=\"$fname\"\r\n";
			$body .= "\r\n";
			$body .= chunk_split($filebody) . "\r\n";
		}
		$body .= "--" . $uniq_id . "--\r\n";
	} else {
		// 漢字コードの指定
		if (MAIL_ENCODING == "UTF8") {
			$header .= "\r\nContent-Type: text/plain;\r\n\tformat=flowed;\r\n\tcharset=\"utf-8\";\r\n\treply-type=original";
		} else {
			$header .= "\r\nContent-Type: text/plain;\r\n\tcharset=\"iso-2022-jp\"\r\nContent-Transfer-Encoding: 7bit";
		}
	}
	// 返信先指定
	if ($reply) {
		$header .= "\r\nReply-to: <" . $reply . ">";
	}
	// 件名の変換
	$subject_str = '';
	while ($mail_subject) {
		if ($subject_str) {
			$subject_str .= "\r\n\t";
		}
		if (mb_strlen($mail_subject, SCRIPT_ENCODING) < 20) {
			if (MAIL_ENCODING == "UTF8") {
				$subject_str .= '=?utf-8?B?';
			} else {
				$subject_str .= '=?iso-2022-jp?B?';
			}
			$subject_str .= base64_encode(mb_convert_encoding($mail_subject, MAIL_ENCODING, SCRIPT_ENCODING)) . '?=';
			$mail_subject = '';
		} else {
			if (MAIL_ENCODING == "UTF8") {
				$subject_str .= '=?utf-8?B?';
			} else {
				$subject_str .= '=?iso-2022-jp?B?';
			}
			$subject_str .= base64_encode(mb_convert_encoding(mb_substr($mail_subject, 0, 20, SCRIPT_ENCODING), MAIL_ENCODING, SCRIPT_ENCODING)) . '?=';
			$mail_subject = mb_substr($mail_subject, 20, mb_strlen($mail_subject, SCRIPT_ENCODING) - 20, SCRIPT_ENCODING);
		}
	}
	$body = str_replace("\r", "", $body);
	$header = str_replace("\r", "", $header);
	// 送信処理
	return @mail($mail_to, $subject_str, mb_convert_encoding($body, MAIL_ENCODING, SCRIPT_ENCODING), $header);
}
//
if (!function_exists("safeStripSlashes")) {
function safeStripSlashes($var) {
  if (is_array($var)) {
    return array_map('safeStripSlashes', $var);
  } else {
    return $var;
  }
}
}
//
function value($key)
{
	if (is_array($_REQUEST[$key])) {
		return join(",", $_REQUEST[$key]);
	}
	return $_REQUEST[$key];
}
/*
if (!function_exists("x_count")) {
function x_count($item)
{
	if (is_array($item)) {
		return count($item);
	}
	return 0;
}
}
*/
// 1文字画像化
function imgch($ch)
{
	$im = imagecreate(20, 20);
	// 文字黒、背景白
	$bg = imagecolorallocate($im, 255, 255, 255);
	$textcolor = imagecolorallocate($im, 0, 0, 0);

	// 文字を描画
	imagestring($im, 10, 3, 3, $ch, $textcolor);

	// 傾き
	$r = mt_rand(-45, 45);
	$im2 = imagerotate($im, $r, 0);

	imagedestroy($im);
	return $im2;
}
// CAPTCHA画像作成
function captcha()
{
	session_start();

	// 出力する4文字を決定
	$ch1 = chr(mt_rand(65, 65 + 25));
	$ch2 = chr(mt_rand(65, 65 + 25));
	$ch3 = chr(mt_rand(65, 65 + 25));
	$ch4 = chr(mt_rand(65, 65 + 25));

	// 確認用にセッションへ保存
	$_SESSION["captcha"] = $ch1 . $ch2 . $ch3 . $ch4;

	$imgCh[] = $ch1;
	$imgCh[] = $ch2;
	$imgCh[] = $ch3;
	$imgCh[] = $ch4;

	$img = imagecreatetruecolor(104, 30);
	imagefill($img, 0, 0, imagecolorallocate($img, 255, 255, 255));

	// 4文字合成
	$px = 3;	// 合成位置
	foreach ($imgCh as $ch) {
 		$img2 = imgch($ch);

 		// 画像のサイズを取得
		$sx = imagesx($img2);
		$sy = imagesy($img2);
		if ($sx < $sy) {
			$sx = $sy;
		} else {
			$sy = $sx;
		}
		imagecopy($img, $img2, $px, 2, 0, 0, $sx - 1, $sy); // 合成する
		$px += $sx;

		imagedestroy($img2);
	}
	$sx = imagesx($img);
	$sy = imagesy($img);

	// 横線を引く
	$color = imagecolorallocate($img, 0, 0, 0);
	imageline($img, 0, 10, $sx - 1, 10, $color);
	imageline($img, 0, 18, $sx - 1, 18, $color);

	// 2倍に拡大
	$img2 = imagecreatetruecolor($sx * 2, $sy * 2);
	imagecopyresized($img2, $img, 0, 0, 0, 0, $sx * 2, $sy * 2, $sx, $sy);

	// 画像出力
	header("Content-type: image/png");
	imagepng($img2);
	//
	imagedestroy($img);
	imagedestroy($img2);
	exit;
}
