<?php
	echo '<script>var g_noPrettify = true;</script>';
	echo '<link rel="stylesheet" type="text/css" href="lib/captcha.css">';
	echo '<script src="lib/contact.js" type="text/javascript"></script>';
	echo '<script src="lib/captcha.js" type="text/javascript"></script>';

	// User variables
	if (empty($recipientName))
	//	$recipientName = GetServerValue('HTTP_HOST');
		$recipientName = $websiteName;

	// Form data
	$name = htmlspecialchars(GetPostValue('name'));
	$email = htmlspecialchars(GetPostValue('email'));
	$subject = htmlspecialchars(GetPostValue('subject')); if (empty($subject)) $subject = htmlspecialchars(GetGetValue('subject'));
	$message = htmlspecialchars(GetPostValue('message')); if (empty($message)) $message = str_replace('{}', "\n", htmlspecialchars(GetGetValue('message')));

	// Hidden form data
	$captchaQuestion = htmlspecialchars(GetPostValue('captcha-question'));
	$captchaAnswer = htmlspecialchars(GetPostValue('captcha-answer'));
	$session = htmlspecialchars(GetPostValue('session'));
	$destination = htmlspecialchars(GetPostValue('destination'));
	if (empty($destination)) $destination = GetServerValue('HTTP_REFERER');
	if (empty($destination)) $destination = '/';

	// Form strings
	$subtitle = sprintf(isset($infoText) ? $infoText : GetString('subtitle'), $recipientName);
	$classSubtitle = '';
	$displayError = 'none';
	$displayForm = 'none';
	$displayCaptcha = 'none';
	$displayConfirm = 'none';
	$captchaText = '';

	// Error messages
	$ErrorMessages = array();
	$htmlErrorLines = '';

	// Main

	if (!empty(htmlspecialchars(GetPostValue('send'))))
	{
		// Validate form data

		// Recipient e-mail address must exist
		if (empty($recipientEmail))
			AddErrorMessage(GetString('fatal-missing-recipient-email'));

		// Name (Pflichtfeld; maximal 50 Zeichen)
		if (empty($name))
			AddErrorMessage(GetString('error-missing-name'));
		else if (strlen(htmlspecialchars_decode($name)) > 50)
		{
			AddErrorMessage(sprintf(GetString('error-length-name'), 50));
		}

		// E-Mail-Adresse (Pflichtfeld; maximal 50 Zeichen; valide)
		if (empty($email))
			AddErrorMessage(GetString('error-missing-email'));
		else if (strlen(htmlspecialchars_decode($email)) > 50)
			AddErrorMessage(sprintf(GetString('error-length-email'), 50));
		else if (!filter_var($email, FILTER_VALIDATE_EMAIL))
			AddErrorMessage(GetString('error-syntax-email'));

		// Subject (Pflichtfeld; maximal 50 Zeichen)
		if (empty($subject))
			AddErrorMessage(GetString('error-missing-subject'));
		else if (strlen(htmlspecialchars_decode($subject)) > 50)
			AddErrorMessage(sprintf(GetString('error-length-subject'), 50));

		// Text (Pflichtfeld)
		if (empty($message))
			AddErrorMessage(GetString('error-missing-message'));

		// Captcha
		if ($captchaEnabled)
		{
			if (empty($captchaQuestion) || empty($captchaAnswer) || $captchaQuestion !== md5($captchaSecret . $captchaAnswer))
			{
				AddErrorMessage(GetString('error-wrong-captcha-answer'));
				sleep(5); # zur Erschwerung von Brute-Force-Atacken
			}
		}

		if (!HasErrors())
		{
			// Compose e-mail
			$name = EncodeHeaderText(htmlspecialchars_decode($name));

			$mailHeader = <<<EOM
From: $name <$email>
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit

EOM;

			$mailBody = htmlspecialchars_decode($message);

			if ($adminDataEnabled)
			{
				$headingAdminData = GetString('AdministrativeInformation');

				$labelIpAddress = GetString('IpAddress');
				$labelReferrer = GetString('Referrer');
				$labelDestination = GetString('TargetUrl');
				$labelLanguage = GetString('Language');
				$labelBrowser = GetString('Browser');

				$ipAddress = GetServerValue('REMOTE_ADDR');
				$referrer = GetServerValue('HTTP_REFERER');
				$language = GetServerValue('HTTP_ACCEPT_LANGUAGE');
				$userAgent = GetServerValue('HTTP_USER_AGENT');

				$mailBody .= <<<EOM

-- 

---------- $headingAdminData ----------

$labelIpAddress: $ipAddress
$labelReferrer: $referrer
$labelDestination: $destination
$labelLanguage: $language
$labelBrowser: $userAgent

EOM;
			}

			if ($sessionLogEnabled)
			{
				$headingSessionLog = GetString('SessionLog');

				$sessionLog = FormatSessionData($session);
				$mailBody .= <<<EOM

---- $headingSessionLog ----

$sessionLog

EOM;
			}

			# Mail senden

			$recipient = EncodeHeaderText($recipientName) . " <$recipientEmail>";
			$subject = EncodeHeaderText(htmlspecialchars_decode(trim("$subjectPrefix $subject")));

			if (mail($recipient, $subject, $mailBody, $mailHeader))
			{
				$subtitle = sprintf(GetString('subtitle-confirm'), $recipientName);
				$displayConfirm = 'block';
			}
			else
			{
				AddErrorMessage(GetString('error-sending-mail') . error_get_last()['message']);
			}
		}

		if (HasErrors())
		{
			ReportErrors();

			// Display form
			InitCaptcha();
			$displayForm = 'block';
		}
	}
	else
	{
		// Display form
		InitCaptcha();
		$displayForm = 'block';
	}

	// Functions

	function InitCaptcha()
	{
		global $captchaEnabled;
		global $displayCaptcha;
		global $captchaText;
		global $captchaQuestion;
		global $captchaSecret;

		if (!$captchaEnabled) return;
		$displayCaptcha = true;

		$buchstabenWoerter = explode(' ', GetString('captcha-letter-words'));
		$zahlWoerter = explode(' ', GetString('captcha-number-words'));

		$buchstaben = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
		$zahlen = ['1', '2', '3', '4', '5', '6', '7', '8'];

		$h1 = mt_rand(0, 7); $v1 = mt_rand(0, 7);
		$h2 = mt_rand(0, 7); $v2 = mt_rand(0, 7);

		while ("$h1$v1" === "$h2$v2") { $h2 = mt_rand(0, 7); $v2 = mt_rand(0, 7); }

		$captchaText = sprintf(
			GetString('captcha-text'),
			$buchstabenWoerter[$h1] . ' ' . $zahlWoerter[$v1],
			$buchstabenWoerter[$h2] . ' ' . $zahlWoerter[$v2]
		);

		$CaptchaQuestion = [$buchstaben[$h1] . $zahlen[$v1], $buchstaben[$h2] . $zahlen[$v2]];
		sort($CaptchaQuestion);
		$captchaQuestion = md5($captchaSecret . implode(' ', $CaptchaQuestion));
	}

	function AddErrorMessage($text)
	{
		global $ErrorMessages;
		array_push($ErrorMessages, $text);
	}

	function HasErrors()
	{
		global $ErrorMessages;
		return count($ErrorMessages) > 0;
	}


	function ReportErrors($text = '')
	{
		global $subtitle;
		global $classSubtitle;
		global $ErrorMessages;
		global $htmlErrorLines;
		global $displayError;

		if (!empty($text))
			AddErrorMessage($text);

		if (!HasErrors())
			return;

		// Show error heading
		$subtitle = GetString('subtitle-error');
		$classSubtitle = 'error';

		// Show error message
		foreach ($ErrorMessages as $errorMessage)
			$htmlErrorLines .= "<li class=\"error\">$errorMessage</li>";
		$displayError = 'block';
	}

	// Codiert den Mail-Betreff standardkonform
	function EncodeHeaderText($text)
	{
		// Nur codieren, wenn Zeichen mit Wert > 127 enthalten sind
		if (preg_match('/[\x80-\xFF]/', $text))
		{
			# "=" codieren
			$text = preg_replace_callback('/(=)/', 'EncodeByte', $text);

			# "_" und "?" codieren
			$text = preg_replace_callback('/([_?])/', 'EncodeByte', $text);

			// " " durch "_" ersetzen
			$text = str_replace(' ', '_', $text);

			# alle Zeichen mit Wert > 127 codieren
			$text = preg_replace_callback('/([\x80-\xFF])/', 'EncodeByte', $text);

			# "=?utf-8?Q?" voranstellen und "?=" anhängen
			$text = '=?utf-8?Q?' . $text . '?=';
		}

		return $text;
	}

	function EncodeByte($matches)
	{
		return sprintf('=%02X', ord($matches[1]));
	}

	// Bereitet den über das Formular übergebenen String mit den Session-Daten in lesbarer Form auf.
	function FormatSessionData($session)
	{
		$result = '';
		if (!empty($session))
		{
			$msStart = '';
			$msPrev = '';
			$SessionLines = explode('|', $session);
			foreach ($SessionLines as $sessionLine)
			{
				$line = '';
				$pairs = explode('&', $sessionLine);
				foreach ($pairs as $pair)
				{
					list($name, $value) = explode('=', $pair);
					$value = urldecode($value);

					if ($name === 'ms')
					{
						$msDiff = '-';
						if (!empty($value))
						{
							if (empty($msStart))
							{
								$msStart = $value;
								$msDiff = 0;
							}
							else
							{
								$msDiff = $value - $msStart;
							}
							if (!empty($msPrev) && $value - $msPrev > 1000) $line .= "\n";
							$line .= "$value ($msDiff): ";

							$msPrev = $value;
						}
					}
					else
					{
						if ($name === 'data' && !empty($value))
						{
							$value = str_replace('Tag=', '', $value);
							$value = str_replace('; Name=', ' ', $value);
							$value = str_replace('; Value=', '=', $value);
						}
						$line .= "$value ";
					}
				}
				if (!empty($result)) $result .= "\n";
				$result .= $line;
			}
		}
		return $result;
	}

?>

<p class="<?php echo $classSubtitle; ?>"><?php echo $subtitle; ?></p>

<div id="error" style="display: <?php echo $displayError; ?>;">
	<ul>
		<?php echo $htmlErrorLines; ?>
	</ul>
</div>

<div id="form" style="display: <?php echo $displayForm; ?>;">
	<form class="contact" method="post">
		<p><input id="input-name" type="text" placeholder="<?php echo GetString('label-input-from-name');?>" name="name" value="<?php echo $name; ?>" maxlength="50"></p>
		<p><input id="input-email" type="text" placeholder="<?php echo GetString('label-input-from-email');?>" name="email" value="<?php echo $email; ?>" maxlength="50"></p>
		<p><input id="input-subject" type="text" placeholder="<?php echo GetString('label-input-subject');?>" name="subject" value="<?php echo $subject; ?>" maxlength="50"></p>
		<p><textarea cols="50" rows="10" placeholder="<?php echo GetString('label-input-message');?>" name="message"><?php echo $message; ?></textarea></p>
		<div id="captcha" style="display: <?php echo $displayCaptcha; ?>;">
			<p style="text-align: center;"><?php echo $captchaText; ?></p>
			<table id="captcha-game" class="nostyle"></table>
			<input type="hidden" name="captcha-question" value="<?php echo $captchaQuestion; ?>">
			<input type="hidden" id="captcha-answer" name="captcha-answer">
		</div>
		<p style="text-align: center;"><input id="button-send" type="submit" name="send" value="<?php echo GetString('label-button-send');?>"><input id="button-discard" type="button" value="<?php echo GetString('label-button-discard');?>" onclick="window.location.assign('<?php echo $destination; ?>');"></p>
		<input type="hidden" id="session" name="session" value="<?php echo $session; ?>">
		<input type="hidden" name="destination" value="<?php echo $destination; ?>">
	</form>
</div>

<div id="confirm" style="display: <?php echo $displayConfirm; ?>;">
	<p style="text-align: center;"><input id="button-confirm" type="button" value="<?php echo GetString('label-button-confirm');?>" onclick="window.location.assign('<?php echo $destination; ?>');"></p>
</div>
