<?php
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	ini_set('log_errors', 1);
	error_reporting(E_ALL);

	// locale-String für die Sortierung von Listen setzen
	$locale = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE'])[0];
	setlocale(LC_ALL, "$locale.utf8");

	// Sprachdatei inkludieren
	$lang = preg_split('/[_-]/', $locale)[0];
	if ($lang !== 'en' && file_exists("lang-$lang.php"))
		include_once "lang-$lang.php";
	else
		include_once "lang-en.php";

?>
<!DOCTYPE html>
<html>
<head>
	<base href="../" />
	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<title>Setup</title>

	<style>
		html {
			--DefaultFgColor: black;
			--DefaultBgColor: white;
		}

		* {
			box-sizing: border-box;
		}

		body {
			_margin: 0;
			color: var(--DefaultFgColor);
			background-color: var(--DefaultBgColor);
			font-family: sans-serif;
			font-size: 1em;
			line-height: 1.5em;
		}

		td[colspan="2"]:not(:has(b)):not(:has(table)) {
			background-color: silver;
		}

		table table {
			border-collapse: collapse;
			width: 100%;
		}

		table table tr:first-child td {
			padding: 0px 5px;
			background-color: #CCCCCC;
		}

		table table td {
			padding: 2px 5px;
			border: 1px solid silver;
		}

		form {
			display: inline-block;
			background-color: #E0E0E0;
			border: 1px solid silver;
		}

		input[type="text"] {
			width: 400px;
		}

		a.info {
			text-decoration: none;
			color: blue;
			font-size: 1.4em;
			line-height: 1em;
			vertical-align: middle;
			text-shadow:
				1px 1px 0px white, -1px 1px 0px white, 1px -1px 0px white, -1px -1px 0px white;
				0px 1px 0px white, 0px -1px 0px white, 1px 0px 0px white, -1px 0px 0px white;
		}
	</style>

	<script>
		"use strict";

		function Init()
		{
		}

		document.addEventListener('DOMContentLoaded', Init);
	</script>
</head>

<?php
	$messages = [];

	// Speichern
	if (!empty($_POST['save']))
	{
/*
echo "<p> BEGIN POST</p>";
echo "<pre>";
var_dump($_POST);
echo "</pre>";
echo "<p> END POST</p>";
*/

		// .htaccess
		InitHtaccess();

		// .htpasswd
		UpdateHtpasswd();

		// CGI-Scripts
		SetCgiFilesExecutable();

		// config.php
		UpdateConfig();
	}

	// Aktuelle Konfiguration ermitteln und anzeigen

	// .htaccess
	$htaccessActive = false;

	if (file_exists('.htaccess'))
	{
		$htaccessActive = true;
	}

	// CGI-Scripts
	$cgiFilenames = [];
	$numCgiTotal = 0;
	$numCgiExecutable = 0;

	GetCgiFiles('cgi-bin', $cgiFilenames, $numCgiTotal, $numCgiExecutable);

	$setCgiExecutable = ($numCgiExecutable === 0 || $numCgiExecutable < $numCgiTotal);

	// config.php
	include 'config.php';

	$stylesheets = [];
	GetStylesheets($stylesheets);

	// Funktionen

	function GetString($name)
	{
		global $LangStrings;
		if (array_key_exists($name, $LangStrings))
			return $LangStrings[$name];
		else
			return 'STRING MISSING';
	}

	function GetVar(&$var)
	{
		return isset($var) ? htmlspecialchars($var) : '';
	}

	function GetFormVar($name)
	{
		return array_key_exists($name, $_POST) ? $_POST[$name] : '';
	}

	function AddMessage($langString, $par1 = null, $par2 = null)
	{
		global $messages;
		array_push($messages, sprintf(GetString($langString), $par1, $par2));
	}

	// .htaccess

	function InitHtaccess()
	{
		$htaccessExists = file_exists('.htaccess');
		
		if (GetFormVar('activate-htaccess') === 'true' && !$htaccessExists)
		{
			if (file_exists('.htaccess.deactivated'))
			{
				if (rename('.htaccess.deactivated', '.htaccess'))
					AddMessage("FileHtaccesHasBeenActivated");
				else
					AddMessage("ErrorFileHtaccesCouldNotBeActivated");
			}
			else if (file_exists('.htaccess.tpl'))
			{
				$htaccess = file_get_contents('.htaccess.tpl');
				if ($htaccess !== false)
				{
					$htaccess = preg_replace('/\bAuthUserFile[^\n]*\n/', sprintf("AuthUserFile %s/.htpasswd\n", dirname(__FILE__)), $htaccess);
					if ($htaccess !== null)
					{
						if (file_put_contents('.htaccess', $htaccess, LOCK_EX) !== false)
							AddMessage("FileHtaccessHasBeenCreated");
						else
							AddMessage("ErrorFileHtaccessCouldNotBeCreated");
					}
					else
						AddMessage("ErrorFileHtaccessTplContainsNoAuthUserFileLine");
				}
				else
					AddMessage("ErrorFileHtaccessTplCouldNotBeRead");
			}
			else
				AddMessage("ErrorFileHtaccessTplWasNotFound");
		}
		else if (GetFormVar('activate-htaccess') === 'false' && $htaccessExists)
		{
			if (rename('.htaccess', '.htaccess.deactivated'))
				AddMessage("FileHtaccesHasBeenDeactivated");
			else
				AddMessage("ErrorFileHtaccesCouldNotBeDeactivated");
		}
	}

	// .htpasswd

	function PrintExistingUsers()
	{
		if (file_exists('.htpasswd'))
		{
			$Lines = file('.htpasswd');
			$userNo = 0;
			foreach($Lines as $line)
			{
				if (strpos($line, ':'))
				{
					$userNo++;
					$parts = explode(':', $line);
					$username = $parts[0];

					echo '<tr>';
					echo "	<td>$username</td>";
					echo '	<td><input type="text" name="username-' . $userNo . '" style="width: 150px;"></td>';
					echo '	<td><input type="text" name="password-' . $userNo . '" style="width: 150px;"></td>';
					echo '	<td><input type="checkbox" name="delete-user-' . $userNo . '"></td>';
					echo '</tr>';
				}
			}
		}
	}

	function UpdateHtpasswd()
	{
		$LinesNew = [];
		$modified = false;

		// Update existing users
		if (file_exists('.htpasswd'))
		{
			$Lines = file('.htpasswd');
			$userNo = 0;
			foreach($Lines as $line)
			{
				if (strpos($line, ':'))
				{
					$userNo++;
					if (empty(GetFormVar("delete-user-$userNo")))
					{
						$parts = explode(':', $line);
						$username = $parts[0];
						$password = $parts[1];

						$usernameNew = GetFormVar("username-$userNo");
						$passwordNew = GetFormVar("password-$userNo");

						if (!empty($usernameNew)) $username = $usernameNew;
						if (!empty($passwordNew)) $password = password_hash($passwordNew, PASSWORD_DEFAULT);

						if (!empty($usernameNew) || !empty($passwordNew))
						{
							$line = "$username:$password" . PHP_EOL;
							$modified = true;
						}
						array_push($LinesNew, $line);
					}
					else
						$modified = true; // user deleted
				}
				else
					array_push($LinesNew, $line);

			}
		}

		// Add new user
		$usernameAdd = GetFormVar("username-add");
		$passwordAdd = GetFormVar("password-add");
		if (!empty($usernameAdd) && !empty($passwordAdd))
		{
			$passwordAdd = password_hash($passwordNew, PASSWORD_DEFAULT);
			$line = "$usernameAdd:$passwordAdd" . PHP_EOL;
			array_push($LinesNew, $line);
			$modified = true;
		}

		if ($modified)
		{
			if (file_put_contents('.htpasswd', $LinesNew, LOCK_EX) !== false)
				AddMessage("FileHtpasswdHasBeenUpdated");
			else
				AddMessage("ErrorFileHtpasswdCouldNotBeUpdated");
		}
	}

	// CGI-Scripts

	function GetCgiFiles($dirname, &$filenames, &$numTotal, &$numExecutable)
	{
		$files = scandir("$dirname/");
		foreach ($files as $filename)
		{
			if (is_dir("$dirname/$filename"))
			{
				if ($filename !== '.' && $filename !== '..')
					GetCgiFiles("$dirname/$filename", $filenames, $numTotal, $numExecutable);
			}
			else if (preg_match('/\.(pl|cgi)$/', $filename))
			{
				array_push($filenames, "$dirname/$filename");
				$numTotal++;
				if (is_executable("$dirname/$filename"))
					$numExecutable++;
			}
		}
	}

	function SetCgiFiles($dirname)
	{
		$files = scandir("$dirname/");
		foreach ($files as $filename)
		{
			if (is_dir("$dirname/$filename"))
			{
				if ($filename !== '.' && $filename !== '..')
					SetCgiFiles("$dirname/$filename");
			}
			else if (preg_match('/\.(pl|cgi)$/', $filename))
			{
				if (!is_executable("$dirname/$filename"))
				{
					if (chmod("$dirname/$filename", 0755))
						AddMessage("File#HasBeenSetToExecutable", "$dirname/$filename");
					else
						AddMessage("ErrorFile#CouldNotBeSetToExecutable", "$dirname/$filename");
				}
			}
		}
	}

	function SetCgiFilesExecutable()
	{
		if (GetFormVar('makeexec-cgifiles') === 'true')
		{
			SetCgiFiles('cgi-bin');
		}
	}

	// config.php

	$Countries = [];
	function PrintLocales(&$lang, &$country)
	{
		$locales = ResourceBundle::getLocales('');
		$localesSortedByDisplay = [];
		foreach ($locales as $locale)
		{
			if (preg_match('/^[^_-]+[_-]+[^_-]+$/', $locale))
			{
				$localeDisplay = locale_get_display_name($locale, $locale);
				$localesSortedByDisplay[$locale] = $localeDisplay;
			}
		}
	//	asort($localesSortedByDisplay, SORT_LOCALE_STRING);
	//	uasort($localesSortedByDisplay, function($a, $b) { return strnatcasecmp($a, $b); });
		uasort($localesSortedByDisplay, function($a, $b) { return strcasecmp($a, $b); });

		$selectedLang = GetVar($lang);
		$selectedCountry = GetVar($country);
		foreach ($localesSortedByDisplay as $locale => $localeDisplay)
		{
			$lang_country = preg_split('/[_-]/', $locale);
			$selected = $lang_country[0] === $selectedLang && $lang_country[1] === $selectedCountry ? 'selected' : '';
			echo "<option value=\"$locale\" $selected>$localeDisplay - $locale</option>";
		}
	}

	function PrintTimezones(&$timezone)
	{
		$selectedValue = GetVar($timezone);
		$timezoneIds = DateTimeZone::listIdentifiers();
		foreach ($timezoneIds as $timezoneId)
		{
			echo "<option " . ($timezoneId === $selectedValue ? 'selected' : '') . ">$timezoneId</option>";
		}
	}

	function GetStylesheets(&$stylesheets)
	{
		$files = scandir(".");
		foreach ($files as $filename)
		{
			if (preg_match('/\.css$/', $filename))
				array_push($stylesheets, $filename);
		}
	}

	function PrintSelectStylesheet($name, &$value)
	{
		global $stylesheets;
		$selectedValue = GetVar($value);
		echo "<select name=\"$name\">";
		if (!in_array($selectedValue, $stylesheets))
			echo "<option selected>$selectedValue</option>";
		foreach ($stylesheets as $filename)
			echo "<option " . ($filename === $selectedValue ? 'selected' : '') . ">$filename</option>";
		echo "</select>";
	}

	function UpdateConfig()
	{
		$formVars = [
			'lang' => preg_split('/[_-]/', GetFormVar('locale'))[0],
			'country' => preg_split('/[_-]/', GetFormVar('locale'))[1],
			'timezone' => GetFormVar('timezone'),
			'DateTimeFormat' => GetFormVar('DateTimeFormat'),
			'baseUrl' => GetFormVar('baseUrl'),
			'websiteName' => GetFormVar('websiteName'),
			'headerTitle' => GetFormVar('headerTitle'),
			'headerSubtitle' => GetFormVar('headerSubtitle'),
			'stylesheet' => GetFormVar('stylesheet'),
			'userStylesheet' => GetFormVar('userStylesheet'),
			'stylesheetPreview' => GetFormVar('stylesheetPreview'),
			'userStylesheetPreview' => GetFormVar('userStylesheetPreview'),
			'privacyLink' => GetFormVar('privacyLink')
		];

		$Lines = file('config.php', FILE_IGNORE_NEW_LINES);
		$LinesNew = $Lines;

		foreach ($formVars as $name => $value)
		{
			$LinesNew = preg_replace("/^([^w#]+)$name(?:[\s]*?)=(?:[\s]*?)'[^']*'/", "$1$name = '$value'", $LinesNew);
		}

		if ($Lines !== $LinesNew)
		{
			if (file_put_contents('config.php', implode(PHP_EOL, $LinesNew), LOCK_EX) !== false)
				AddMessage("FileConfigPhpHasBeenUpdated");
			else
				AddMessage("ErrorFileConfigPhpCouldNotBeUpdated");
		}
	}
?>

<body>
	<?php
		if (count($messages) > 0)
		{
			foreach ($messages as $message)
			{
				echo "<p>$message</p>";
			}
		}
	?>

	<form method="post">
		<table cellspacing="10" cellpadding="0" border="0">
		<tr>
			<td colspan="2" align="center"><b><?php echo GetString('Setup');?></b></td>
		</tr>
		<tr>
			<td colspan="2" align="center"><?php echo GetString('AccessProtection');?></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('Active');?>:</label></td>
			<td>
				<input id="activate-htaccess-false" type="radio" name="activate-htaccess" value="false" <?php echo $htaccessActive ? '' : 'checked' ?>> <label for="activate-htaccess-false"><?php echo GetString('no');?></label>
				<input id="activate-htaccess-true" type="radio" name="activate-htaccess" value="true" <?php echo $htaccessActive ? 'checked' : '' ?>> <label for="activate-htaccess-true"><?php echo GetString('yes');?></label>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<table>
				<tr>
					<td><?php echo GetString('UserName');?></td>
					<td><?php echo GetString('NewUserName');?></td>
					<td><?php echo GetString('NewPassword');?></td>
					<td><?php echo GetString('Delete');?></td>
				</tr>
				<?php PrintExistingUsers(); ?>
				<tr>
					<td><i><?php echo GetString('AddNew');?>:</i></td>
					<td><input type="text" name="username-add" style="width: 150px;"></td>
					<td><input type="text" name="password-add" style="width: 150px;"></td>
					<td></td>
				</tr>
				</table>
			</td>
		</tr>
		<tr>
			<td colspan="2" align="center"><?php echo GetString('CgiScripts');?></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('SetToExecutable');?>:</label></td>
			<td>
				<input id="makeexec-cgifiles-false" type="radio" name="makeexec-cgifiles" value="false" <?php echo $setCgiExecutable ? '' : 'checked' ?>> <label for="makeexec-cgifiles-false"><?php echo GetString('no');?></label>
				<input id="makeexec-cgifiles-true" type="radio" name="makeexec-cgifiles" value="true" <?php echo $setCgiExecutable ? 'checked' : '' ?>> <label for="makeexec-cgifiles-true"><?php echo GetString('yes');?></label> &nbsp; (<?php printf(GetString('#Of#AreExecutable'), $numCgiExecutable, $numCgiTotal);?>)
			</td>
		</tr>
		<tr>
			<td colspan="2" align="center"><?php echo GetString('LanguageAndRegion');?></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('Language') . ' / ' . GetString('Country');?>:</label></td>
			<td><select name="locale"><?php PrintLocales($lang, $country);?></select></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('TimeZone');?>:</label></td>
			<td><select name="timezone"><?php PrintTimezones($timezone);?></select></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('DateFormatForEditor');?>:</label></td>
			<td><input type="text" name="DateTimeFormat" value="<?php echo GetVar($DateTimeFormat);?>" style="width: 150px;"> <a href="https://www.w3schools.com/php/func_date_date_format.asp" target="_blank" rel="noopener" class="info" title="<?php echo GetString('Info');?>">🛈</a></td>
		</tr>
		<tr>
			<td colspan="2" align="center"><?php echo GetString('WebsiteDetails');?></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('WebsiteAddress');?>:</label></td>
			<td><input type="text" name="baseUrl" value="<?php echo GetVar($baseUrl);?>" placeholder="(<?php echo GetString('isDeterminedAutomatically');?>)"></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('WebsiteName');?>:</label></td>
			<td><input type="text" name="websiteName" value="<?php echo GetVar($websiteName);?>"></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('TitleOfPageHeader');?>:</label></td>
			<td><input type="text" name="headerTitle" value="<?php echo GetVar($headerTitle);?>"></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('SubtitleOfPageHeader');?>:</label></td>
			<td><input type="text" name="headerSubtitle" value="<?php echo GetVar($headerSubtitle);?>"></td>
		</tr>
		<tr>
			<td colspan="2" align="center"><?php echo GetString('StylesheetsForLiveMode');?></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('Default');?>:</label></td>
			<td><?php PrintSelectStylesheet('stylesheet', $stylesheet); ?></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('User');?>:</label></td>
			<td><?php PrintSelectStylesheet('userStylesheet', $userStylesheet); ?></td>
		</tr>
		<tr>
			<td colspan="2" align="center"><?php echo GetString('StylesheetsForPreviewMode');?></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('Default');?>:</label></td>
			<td><?php PrintSelectStylesheet('stylesheetPreview', $stylesheetPreview); ?></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('User');?>:</label></td>
			<td><?php PrintSelectStylesheet('userStylesheetPreview', $userStylesheetPreview); ?></td>
		</tr>
		<tr>
			<td colspan="2" align="center"><?php echo GetString('SpecialPages');?></td>
		</tr>
		<tr>
			<td><label><?php echo GetString('PrivacyPolicyLink');?>:</label></td>
			<td><input type="text" name="privacyLink" value="<?php echo GetVar($privacyLink);?>"></td>
		</tr>
		<tr>
			<td colspan="2" align="center">
				<input type="submit" name="save" value="<?php echo GetString('Save');?>" style="margin: 10px;">
			</td>
		</tr>
		</table>
	</form>
</body>
</html>
