<?php
include_once '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'constants.php';
header('Content-Type: text/html; charset=' . \CodingOperations::getInternalEncoding());
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Verzeichnisschutz</title>
</head>
<body>
<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */



 error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);

$path = GetAbsolutePath();
$basepath = $path;
if (StringOperations::substr($basepath, -1) === DIRECTORY_SEPARATOR) {
  $basepath = \StringOperations::substr($basepath, 0, \StringOperations::strlen($basepath) - 1);
}
$paths = array(array($basepath, false));
$hasKwResources = false;
if (file_exists(implode(DIRECTORY_SEPARATOR, array($basepath, '..', '..', '..', 'kw-resources')))) {
  $hasKwResources = true;
}

$paths[] = array(implode(DIRECTORY_SEPARATOR, array($basepath, '..', '..', 'kufertools', 'settings', 'user', 'layout', 'wss')), true);
$paths[] = array(implode(DIRECTORY_SEPARATOR, array($basepath, '..', '..', 'kufertools', 'settings', 'user', 'layout', 'template')), true);

if ($hasKwResources) {
  $paths[] = array(implode(DIRECTORY_SEPARATOR, array($basepath, '..', '..', '..', 'kw-resources', 'core')), false);
  $paths[] = array(implode(DIRECTORY_SEPARATOR, array($basepath, '..', '..', '..', 'kw-resources', 'kuferweb', 'layout', 'settings')), false);
} else {
  $paths[] = array(implode(DIRECTORY_SEPARATOR, array($basepath, '..', '..', 'webbasys', 'layout', 'settings')), false);
}

if (PostOperations::getVarValue('username') == '' && PostOperations::getVarValue('userinput', false) == true) {
  echo "<p style='color: red'>Bitte einen Login-Namen angeben. Es wurde keine .htaccess-Datei angelegt.</p>";
}

if (PostOperations::getVarValue('username') != '') {
  $falscheZeichen = !preg_match('#^[a-zA-Z0-9]+$#', PostOperations::getVarValue('username'));
}
if (PostOperations::getVarValue('userinput', false) == 'true'
   && !$falscheZeichen
   && PostOperations::getVarValue('username') != '') {
  $password = $_POST['password'];
  if ($password != '') {
    $errors = WriteAccessFiles(PostOperations::getVarValue('server'), $paths, PostOperations::getVarValue('username'), $password);
    echo '<p><b>Login:</b> ' . CleanOperations::cleanStringForHtml(PostOperations::getVarValue('username')) . '</p>';
    echo '<p><b>Passwort:</b> ' . CleanOperations::cleanStringForHtml($password) . '</p>';
    if (empty($errors)) {
      echo '<p>Einstellungen gespeichert!</p>';
    } else {
      echo "<p style='color: red'>Einstellungen konnten nicht gespeichert werden!<br />"
        . 'Wahrscheinlich fehlen Ihnen Schreibrechte in das config-Verzeichnis!</p>';
    }
    if (PostOperations::getVarValue('logcopy', '') == '1') {
      if (copyToLog()) {
        echo '<p>.htaccess Datei ins Log-Verzeichnis kopiert!</p>';
      } else {
        echo "<p style='color: red'>.htaccess Datei konnte nicht kopiert werden!<br />"
            . 'Wahrscheinlich fehlen Ihnen Schreibrechte in das log-Verzeichnis!</p>';
      }
    }
    echo '<p><a href="webeinstell.php" title="Zurück">Zurück</a></p>';
  } else {
    echo "<p style='color: red'>Einstellungen konnten nicht gespeichert werden!<br />"
        . 'Wahrscheinlich fehlen Ihnen Schreibrechte in das config-Verzeichnis!</p>';
  }
} else {
  try {
    $unixChecked = !\System::isWindows() ? 'checked="checked"' : '';
    $windowsChecked = \System::isWindows() ? 'checked="checked"' : '';
  } catch (\Exception $ex) {
    $unixChecked = 'checked="checked"';
    $windowsChecked = '';
  } catch (\Error $ex) {
    $unixChecked = 'checked="checked"';
    $windowsChecked = '';
  }
  ?>
      <div>
        <form action="" method="post">
          <?php if ($falscheZeichen) {
            echo "<p style='color: red'>Bitte nur korrekte Zeichen beim Login eingeben. Es wurde keine .htaccess-Datei angelegt.</p>";
          } ?>
          <label style="width: 10em; float: left;">Servertyp:</label>
          <input type="radio" name="server" value="unix" <?php echo $unixChecked; ?> />UNIX (und Derivate)
          <input type="radio" name="server" value="win" <?php echo $windowsChecked; ?> />Windows (nur Apache Web-Server,
          bei IIS bitte über die Konfigurationsoberfläche 
          <a href="http://support.microsoft.com/?kbid=324064" title="IIS .htaccess Alternative">absichern</a>)
          <br /><br />
          <label style="width: 10em; float: left;">Absoluter Serverpfad:</label>
          <?php echo CleanOperations::cleanStringForHtml($path) ?>
          <br /><br />
          <label style="width: 10em; float: left;">Login (frei wählbar mit a-z, A-Z und 0-9):</label>
          <input type='text' name='username' size='20' />
          <br /><br /> <br \>       
          <label style="width: 10em; float: left;">Passwort:</label>
          <?php  
                $passwort = generierePasswort();
  echo "<input type='hidden' name='password' size='20' value='" . CleanOperations::cleanStringForHtml($passwort) . "'/>";

  echo CleanOperations::cleanStringForHtml($passwort);
  echo '<br><a href="">anderes Passwort generieren</a>'; ?>
          <br /><br />
          <label style="width: 10em; float: left;">.htaccess Datei auch ins Log-Verzeichnis kopieren:</label>
          <input type='checkbox' name='logcopy' value='1' checked='checked' />
          <br /><br />
          <br /><br />
          <input type="submit" value="Speichern" />
          <input type='hidden' value='true' name='userinput' />
        </form>
      </div>
      <p>
      <a href="../wizards/checksecurity/index.php">Schutz testen</a>
      </p>
    <?php
}

function generierePasswort()
{
  $passwort = '';
  $pool = 'qwertzupasdfghkyxcvbnm23456789';
  $pool .= '23456789';
  $pool .= 'WERTZUPLKJHGFDSAYXCVBNM';
  srand((double)microtime() * 1000000);
  for ($n = 0; $n < 8; $n++) { 
    $passwort .= StringOperations::substr($pool, (rand() % (StringOperations::strlen($pool))), 1);
  }

  return $passwort;
}

function GetAbsolutePath()
{
  return dirname(__FILE__);
}

function WriteAccessFiles($ptyp, $paths, $puser, $ppassword)
{
  $pwFile = $paths[0][0] . DIRECTORY_SEPARATOR . '.htpasswd';
  $file = fopen($pwFile, 'w');
  if ($file === false) {
    echo '<p style="color: red">Konnte Passwort-Datei nicht erstellen!</p>';

    return array();
  }

  switch ($ptyp) {
    case 'win': $pwd = $ppassword;
      break;
    case 'unix': $pwd = crypt($ppassword, StringOperations::substr($ppassword, 0, 2));
      break;
  }

  fwrite($file, $puser . ':' . $pwd);
  fclose($file);

  $err = array();
  foreach ($paths as $path) {
    list($path, $createDir) = $path;
    if ($createDir && !is_dir($path)) {
      @mkdir($path, true);
    }

    if (!WriteAccessFile($path, $pwFile, $puser)) {
      echo '<p style="color: red">' . \CleanOperations::cleanStringForHtml($path) . '</p>';
      $err[] = $path;
    }
  }

  return $err;
}

function WriteAccessFile($ppath, $pwFile, $puser)
{
  if (StringOperations::substr($ppath, -1) != DIRECTORY_SEPARATOR) {
    $ppath = $ppath . DIRECTORY_SEPARATOR;
  }

  $file = @fopen($ppath . '.htaccess', 'w');
  if (!$file) {
    return false;
  }

  fwrite($file, 'AuthType Basic' . \StringOperations::chr_windows1252(13) . \StringOperations::chr_windows1252(10));
  fwrite($file, 'AuthName "Administration"' . \StringOperations::chr_windows1252(13) . \StringOperations::chr_windows1252(10));

  fwrite($file, 'AuthUserFile ' . $pwFile . \StringOperations::chr_windows1252(13) . \StringOperations::chr_windows1252(10));
  fwrite($file, 'Require user ' . $puser . \StringOperations::chr_windows1252(13) . \StringOperations::chr_windows1252(10));
  fwrite($file, 'Order Deny,Allow' . \StringOperations::chr_windows1252(13) . \StringOperations::chr_windows1252(10));
  fwrite($file, 'Require valid-user' . \StringOperations::chr_windows1252(13) . \StringOperations::chr_windows1252(10));
  fwrite($file, 'Satisfy All' . \StringOperations::chr_windows1252(13) . \StringOperations::chr_windows1252(10));
  fclose($file);

  return true;
}

function copyToLog()
{
  return copy('.htaccess', '..' . DIRECTORY_SEPARATOR . '..'
      . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . '.htaccess');
}
?>
</body>
</html>