<?php
# SonicCampGuard 
# 
# Copyright (c) 2024 Bundeswehr 
# Diese Anwendung wurde von Cedric Prietz entwickelt. 
#
# E-Mail: CedricPrietz@bundeswehr.org 
# App: 90-8303-54618 
# 
# Letzte Änderung: 27.01.2025 

#error_reporting(E_ALL); // Meldet alle Fehler
#ini_set('display_errors', 1); // Zeigt die Fehler im Browser an
#ini_set('display_startup_errors', 1); // Zeigt auch Fehler, die beim Start von PHP auftreten

// Prüfen ob die Installation bereits erfolgt ist
if (file_exists(__DIR__ . '/install.lock')) {
    header('Location: index');
}

// Alle Zeitzonen abrufen
$timezones = timezone_identifiers_list();

// Standardzeitzone des Servers abrufen
$defaultTimezone = date_default_timezone_get();

// Zeichensätze für Datenbank definieren
$charsets = [
    'utf8mb4',
    'utf8',
    'latin1',
    'ascii',
    'ucs2',
    'utf16',
    'utf32',
    'binary',
    'big5',
    'euckr',
    'gb2312',
    'gbk',
    'sjis',
    'tis620',
    'cp1250',
    'cp1251',
    'cp1256',
    'cp1257',
    'geostd8',
    'hebrew',
    'latin2',
    'latin5',
    'latin7',
    'macce',
    'macroman',
    'swe7'
];

// Standard-Zeichensatz
$defaultCharset = 'utf8mb4';

// Werte für Systemanforderungen
$app = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . 'app.json'), true);
$requiredUploadSize = $app['required_upload_size'];
$uploadMaxFilesize = parse_size(ini_get('upload_max_filesize'));
$postMaxSize = parse_size(ini_get('post_max_size'));
$currentMaxExecutionTime = ini_get('max_execution_time');
$currentMaxExecutionTime = is_numeric($currentMaxExecutionTime) ? (int) $currentMaxExecutionTime : 0;
$currentMaxInputTime = ini_get('max_input_time');
$currentMaxInputTime = is_numeric($currentMaxInputTime) ? (int) $currentMaxInputTime : 0;
$currentMemoryLimit = ini_get('memory_limit');
$currentMemoryLimit = is_numeric($currentMemoryLimit) ? (int) $currentMemoryLimit : parse_size($currentMemoryLimit);

// Hilfsfunktion, um z.B. '2G' in Megabyte umzurechnen
function parse_size($size)
{
    $unit = strtolower(substr($size, -1));
    $size = (int) $size;
    switch ($unit) {
        case 'g':
            $size *= 1024;
            break;
        case 'm': /* already in megabytes */
            break;
        case 'k':
            $size /= 1024;
            break;
    }
    return $size;
}

// Hilfsfunktion, um die Größe benutzerfreundlich darzustellen
function format_size($sizeInMB)
{
    if ($sizeInMB >= 1024) {
        return ($sizeInMB / 1024) . " GB";
    }
    return $sizeInMB . " MB";
}

// Installation Starten
if (isset($_POST['startInstallation'])) {
    try {
        $pdo = new PDO(
            "mysql:host={$_POST['mysql_host']};port={$_POST['mysql_port']};dbname={$_POST['mysql_database']};charset={$_POST['mysql_charset']}",
            $_POST['mysql_username'],
            $_POST['mysql_password'],
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]
        );

        // Ist ein Backup gewählt
        if (isset($_FILES['backupFile']) && $_FILES['backupFile']['error'] === UPLOAD_ERR_OK) {
            $tempPath = $_FILES['backupFile']['tmp_name'];
            $targetPath = __DIR__ . '/backups/' . $_FILES['backupFile']['name'];

            // Sicherstellen, dass das Zielverzeichnis existiert
            if (!is_dir(__DIR__ . '/backups/')) {
                mkdir(__DIR__ . '/backups/', 0755, true);
            }

            // Datei in den backups-Ordner verschieben
            if (!move_uploaded_file($tempPath, $targetPath)) {
                die("Die Datei konnte nicht in den backups-Ordner verschoben werden.");
            }

            // Entpacken der Datei
            $zip = new ZipArchive();
            if ($zip->open($targetPath) === true) {
                $zip->extractTo(__DIR__ . '/backups/');
                $zip->close();
            } else {
                die("Fehler beim Entpacken der ZIP-Datei.");
            }

            // Sicherstellen, dass das Zielverzeichnis existiert
            if (!is_dir('./uploads/')) {
                mkdir('./uploads/', 0755, true);
            }

            // 1. ./uploads/ ersetzen
            if (is_dir(__DIR__ . '/backups/uploads/')) {
                // Löschen des aktuellen ./uploads/ Ordners
                $it = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator('./uploads/', RecursiveDirectoryIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::CHILD_FIRST
                );
                foreach ($it as $file) {
                    $file->isDir() ? rmdir($file->getRealPath()) : unlink($file->getRealPath());
                }
                rmdir('./uploads/');

                // Kopieren des neuen ./uploads/ Ordners
                rename(__DIR__ . '/backups/uploads/', './uploads/');
            }

            // 2. Die SQL-Datei ersetzen
            $sqlFiles = glob(__DIR__ . '/backups/*.sql');
            if (!empty($sqlFiles)) {
                $sqlFile = $sqlFiles[0]; // Die erste SQL-Datei verwenden
                $destinationDir = './assets/installer/';
                if (!is_dir($destinationDir)) {
                    mkdir($destinationDir, 0755, true);
                }
                copy($sqlFile, $destinationDir . 'install.sql');
            }

            // Aufräumen
            $it = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator(__DIR__ . '/backups/', RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::CHILD_FIRST
            );
            foreach ($it as $file) {
                $file->isDir() ? rmdir($file->getRealPath()) : unlink($file->getRealPath());
            }
        }

        // Installieren
        // Werte aus dem Formular holen    
        $timezone = $_POST['timezone'];
        $mysql_host = $_POST['mysql_host'];
        $mysql_username = $_POST['mysql_username'];
        $mysql_password = $_POST['mysql_password'];
        $mysql_database = $_POST['mysql_database'];
        $mysql_port = $_POST['mysql_port'];
        $mysql_charset = $_POST['mysql_charset'];
        $ldap_host = $_POST['ldap_host'];
        $ldap_port = $_POST['ldap_port'];
        $ldap_bind_dn = $_POST['ldap_bind_dn'];
        $ldap_bind_pass = $_POST['ldap_bind_pass'];
        $ldap_base_dn = $_POST['ldap_base_dn'];
        $required_group = $_POST['ldap_required_group'];
        $map_position = $_POST['map_position'];
        $map_tile = $_POST['map_tile'];

        // Kopf der config.inc.php
        $config_content = "<?php\n\n";
        $config_content .= "    #\tKonfigurationsdatei für MySQL-Datenbankverbindung und LDAP-Anbindung\n";
        $config_content .= "    #\n";
        $config_content .= "    #\tCopyright (c) 2024 Bundeswehr\n";
        $config_content .= "    #\tDiese Anwendung wurde von Cedric Prietz entwickelt.\n";
        $config_content .= "    #\tE-Mail: CedricPrietz@bundeswehr.org\n";
        $config_content .= "    #\tApp: 90-8303-54618\n";
        $config_content .= "\t#\n";
        $config_content .= "    #\tLetzte Änderung: " . date('d.m.Y') . "\n\n";


        // Konfigurationsarray hinzufügen
        $config_content .= "\$app_config = [\n";
        $config_content .= "    'maintenance_mode' => false,\n";
        $config_content .= "    'timezone' => '$timezone',\n";
        $config_content .= "    'map_tile' => '$map_tile',\n";
        $config_content .= "    'map_position' => '$map_position'\n";
        $config_content .= "];\n\n";


        // MySQL-Konfigurationswerte einfügen
        $config_content .= "    # MySQL-Datenbankkonfiguration\n";
        $config_content .= "    \$mysql_config = [\n";
        $config_content .= "        'host'     => '$mysql_host',      // MySQL Server-Hostname oder IP-Adresse\n";
        $config_content .= "        'username' => '$mysql_username',        // MySQL Benutzername\n";
        $config_content .= "        'password' => '$mysql_password',    // MySQL Passwort\n";
        $config_content .= "        'database' => '$mysql_database',        // Name der MySQL-Datenbank\n";
        $config_content .= "        'port'     => $mysql_port,             // MySQL Port (Standard: 3306)\n";
        $config_content .= "        'charset'  => '$mysql_charset'         // Zeichensatz für die Verbindung (optional)\n";
        $config_content .= "    ];\n\n";

        // LDAP-Konfigurationswerte einfügen
        $config_content .= "    # LDAP-Konfiguration\n";
        $config_content .= "    \$ldap_config = [\n";
        $config_content .= "        'host'       => '$ldap_host', // LDAP Server-Hostname oder IP-Adresse\n";
        $config_content .= "        'port'       => $ldap_port,                // LDAP Port (Standard: 389 für unverschlüsselte Verbindung, 636 für LDAPS)\n";
        $config_content .= "        'bind_dn'    => '$ldap_bind_dn', // Bind-DN für die Authentifizierung\n";
        $config_content .= "        'bind_pass'  => '$ldap_bind_pass',    // Passwort für die Authentifizierung\n";
        $config_content .= "        'base_dn'    => '$ldap_base_dn', // Basis-DN für Suchanfragen\n";
        $config_content .= "        'required_group' => '$required_group'       // Suchfilter für Berechtigte Gruppe\n";
        $config_content .= "    ];\n\n";

        // Schließe PHP-Tag
        $config_content .= "?>";

        // Parameter in die Konfigurationsdatei schreiben (config.inc.php)   
        file_put_contents('config.inc.php', $config_content);

        // Datenbanktabellen einrichten
        try {

            $dsn = "mysql:host=$mysql_host;dbname=$mysql_database;port=$mysql_port;charset=$mysql_charset";
            $pdo = new PDO($dsn, $mysql_username, $mysql_password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // install.sql-Datei einlesen und SQL-Abfragen ausführen
            $sql_file = 'assets/installer/install.sql'; // Pfad zur SQL-Datei
            if (file_exists($sql_file)) {

                // Tabellen in der Datenbank anlegen
                $sql = file_get_contents($sql_file);
                $pdo->exec($sql);

                // Sperrdatei erzeugen
                $file = fopen(__DIR__ . '/install.lock', 'w');
                if ($file) {
                    fwrite($file, "Installation durchgeführt am " . date('Y-m-d H:i:s'));
                    fclose($file);
                }

                // Installationsdateien Löschen
                // Funktion zum rekursiven Löschen von Verzeichnissen und deren Inhalt
                function deleteDirectory($dir)
                {
                    if (!is_dir($dir)) {
                        return false;
                    }
                    $it = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
                        RecursiveIteratorIterator::CHILD_FIRST
                    );
                    foreach ($it as $file) {
                        $file->isDir() ? rmdir($file->getRealPath()) : unlink($file->getRealPath());
                    }
                    return rmdir($dir);
                }

                // Löscht alle Dateien im Ordner ./backups/
                if (is_dir('./backups/')) {
                    $it = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator('./backups/', RecursiveDirectoryIterator::SKIP_DOTS),
                        RecursiveIteratorIterator::CHILD_FIRST
                    );
                    foreach ($it as $file) {
                        unlink($file->getRealPath());
                    }
                    rmdir('./backups/');
                }

                // Löscht den Ordner ./assets/installer/
                deleteDirectory('./assets/installer/');

                // Löscht die Datei ./install.php
                if (file_exists('./install.php')) {
                    unlink('./install.php');
                }
                // Weiterleiten nach Abschluss der Installation
                header("location: index");

            } else {
                $errorMessageDB = '<div class="alert alert-warning" role="alert">
                                <i data-feather="alert-circle"></i>
                                <b>install.sql</b> Datei nicht gefunden.
                            </div>';
            }

        } catch (PDOException $e) {
            $errorMessageDB = '<div class="alert alert-warning" role="alert">
                                <i data-feather="alert-circle"></i>
                                ' . $e->getMessage() . '
                            </div>';
        }


    } catch (PDOException $e) {
        $errorMessageDB = '<div class="alert alert-warning" role="alert">
                                <i data-feather="alert-circle"></i>
                                ' . $e->getMessage() . '
                            </div>';
    }
}
?>
<!DOCTYPE html>
<html lang="de">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="author" content="Cedric Prietz">
    <title>SONICCG - Installation</title>
    <script src="/assets/js/color-modes.js"></script>

    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700;900&amp;display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="/assets/vendors/core/core.css">
    <link rel="stylesheet" href="/assets/vendors/select2/select2.min.css">
    <link rel="stylesheet" href="/assets/vendors/jquery-tags-input/jquery.tagsinput.min.css">
    <link rel="stylesheet" href="/assets/vendors/dropify/dist/dropify.min.css">
    <link rel="stylesheet" href="/assets/vendors/pickr/themes/classic.min.css">
    <link rel="stylesheet" href="/assets/vendors/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/assets/vendors/flatpickr/flatpickr.min.css">
    <link rel="stylesheet" href="/assets/vendors/datatables.net-bs5/dataTables.bootstrap5.css">
    <link rel="stylesheet" href="/assets/vendors/sweetalert2/sweetalert2.min.css">
    <link rel="stylesheet" href="/assets/vendors/easymde/easymde.min.css">
    <link rel="stylesheet" href="/assets/fonts/feather-font/css/iconfont.css">
    <link rel="stylesheet" href="/assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="/assets/css/style.css">

    <link rel="shortcut icon" href="/assets/images/favicon.ico" />

    <noscript>
        <meta http-equiv="refresh" content="0; URL=/javascript-required.php">
    </noscript>
</head>

<body class="navbar-dark">
    <div class="main-wrapper">

        <div class="horizontal-menu">
            <nav class="navbar top-navbar">
                <div class="container">
                    <div class="navbar-content">

                        <a href="" class="navbar-brand d-lg-flex">
                            SONIC<span>CG</span>
                        </a>

                        <!-- navbar toggler for small devices -->
                        <div data-toggle="horizontal-menu-toggle"
                            class="navbar-toggler navbar-toggler-right d-lg-none align-self-center">
                            <span></span>
                            <span></span>
                            <span></span>
                            <span></span>
                        </div>

                    </div>
                </div>
            </nav>
            <nav class="bottom-navbar">
                <div class="container">
                    <div class="pb-5"></div>
                </div>
            </nav>
        </div>

        <div class="page-wrapper">

            <div class="page-content" id="page-content">

                <form action="" method="POST" id="installWizard" enctype="multipart/form-data">

                    <div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
                        <div>
                            <h4 class="mb-md-0">Installation</h4>
                            <span class="text-secondary">Installation und Konfiguration</span>
                        </div>
                        <div class="d-flex align-items-center flex-wrap text-nowrap">

                            <button class="btn btn-primary btn-icon-text" type="submit" name="startInstallation">
                                <i class="btn-icon-prepend mdi mdi-play"></i>
                                Installieren
                            </button>

                        </div>
                    </div>

                    <div class="row">

                        <div class="col-lg-12 col-xl-6 grid-margin">
                            <div class="card">
                                <div class="card-header bg-primary text-white">
                                    <i class="mdi mdi-database me-1" style="line-height: 10px; font-size: 18px;"></i>
                                    Datenbank
                                </div>
                                <div class="card-body">

                                    <?php if ($errorMessageDB) {
                                        echo $errorMessageDB;
                                    } ?>

                                    <div class="row">

                                        <div class="col-lg-12 col-xl-6">

                                            <div class="mb-3">
                                                <label for="mysql_host" class="form-label">Hostname</label>
                                                <input type="text" class="form-control" id="mysql_host"
                                                    name="mysql_host" placeholder="localhost" value="localhost">
                                            </div>
                                            <div class="mb-3">
                                                <label for="mysql_port" class="form-label">Port</label>
                                                <input type="number" class="form-control" id="mysql_port"
                                                    name="mysql_port" placeholder="3306" value="3306">
                                            </div>
                                            <div class="mb-3">
                                                <label for="mysql_database" class="form-label">Datenbank</label>
                                                <input type="text" class="form-control" id="mysql_database"
                                                    name="mysql_database" autofocus>
                                            </div>

                                        </div>

                                        <div class="col-lg-12 col-xl-6">

                                            <div class="mb-3">
                                                <label for="mysql_charset" class="form-label">Zeichensatz</label>
                                                <?php
                                                echo '<select class="js-example-basic-single form-select form-control" name="mysql_charset" data-width="100%">';
                                                foreach ($charsets as $charset) {
                                                    $selected = ($charset === $defaultCharset) ? ' selected' : '';
                                                    echo '<option value="' . htmlspecialchars($charset) . '"' . $selected . '>' . htmlspecialchars($charset) . '</option>';
                                                }
                                                echo '</select>';
                                                ?>
                                            </div>
                                            <div class="mb-3">
                                                <label for="mysql_username" class="form-label">Benutzername</label>
                                                <input type="text" class="form-control" id="mysql_username"
                                                    name="mysql_username">
                                            </div>
                                            <div class="mb-3">
                                                <label for="mysql_password" class="form-label">Passwort</label>
                                                <input type="password" class="form-control" id="mysql_password"
                                                    name="mysql_password">
                                            </div>
                                        </div>

                                    </div>

                                </div>
                            </div>
                        </div>

                        <div class="col-lg-12 col-xl-6 grid-margin">
                            <div class="card">
                                <div class="card-header bg-primary text-white">
                                    <i class="mdi mdi-microsoft-windows me-1"
                                        style="line-height: 10px; font-size: 18px;"></i>
                                    Domäne
                                </div>
                                <div class="card-body">

                                    <div class="row">

                                        <div class="col-lg-12 col-xl-6">

                                            <div class="mb-3">
                                                <label for="ldap_host" class="form-label">Hostname</label>
                                                <input type="text" class="form-control" id="ldap_host" name="ldap_host"
                                                    placeholder="ldap://gefstdlwmcd.de" value="ldap://gefstdlwmcd.de"
                                                    required>
                                            </div>
                                            <div class="mb-3">
                                                <label for="ldap_port" class="form-label">Port</label>
                                                <input type="number" class="form-control" id="ldap_port"
                                                    name="ldap_port" placeholder="389" value="389">
                                            </div>
                                            <div class="mb-3">
                                                <label for="ldap_base_dn" class="form-label">Basis-DN</label>
                                                <input type="text" class="form-control" id="ldap_base_dn"
                                                    name="ldap_base_dn" placeholder="dc=gefstdlwmcd,dc=de"
                                                    value="dc=gefstdlwmcd,dc=de" required>
                                            </div>

                                        </div>

                                        <div class="col-lg-12 col-xl-6">

                                            <div class="mb-3">
                                                <label for="ldap_bind_dn" class="form-label">Bind-DN</label>
                                                <input type="text" class="form-control" id="ldap_bind_dn"
                                                    name="ldap_bind_dn" placeholder="gefstdlwmcd\ldap"
                                                    value="gefstdlwmcd\ldap">
                                            </div>
                                            <div class="mb-3">
                                                <label for="ldap_bind_pass" class="form-label">Bind-Passwort</label>
                                                <input type="password" class="form-control" id="ldap_bind_pass"
                                                    name="ldap_bind_pass">
                                            </div>
                                            <div class="mb-3">
                                                <label for="ldap_required_group"
                                                    class="form-label">Zugangsgruppe</label>
                                                <input type="text" class="form-control" id="ldap_required_group"
                                                    name="ldap_required_group"
                                                    placeholder="CN=GL_CampGuard_Nutzer,OU=FunktionsGruppen,OU=Gruppen,OU=MCD,DC=gefstdlwmcd,DC=de"
                                                    value="CN=GL_CampGuard_Nutzer,OU=FunktionsGruppen,OU=Gruppen,OU=MCD,DC=gefstdlwmcd,DC=de">
                                            </div>

                                        </div>

                                    </div>

                                </div>
                            </div>
                        </div>

                    </div>

                    <div class="row">

                        <div class="col-lg-12 col-xl-8 grid-margin">
                            <div class="card">
                                <div class="card-header bg-warning text-white">
                                    <i class="mdi mdi-check-all me-1" style="line-height: 10px; font-size: 18px;"></i>
                                    Systemanforderungen
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Anforderung</th>
                                                    <th width="15%">SOLL</th>
                                                    <th width="15%">IST</th>
                                                </tr>
                                            </thead>
                                            <tr>
                                                <td>Erforderliche PHP-Version</td>
                                                <td><?php echo $app['required_php_version']; ?></td>
                                                <td>
                                                    <?php if (version_compare(phpversion(), $app['required_php_version'], '>=')) {
                                                        echo "<span class='text-success fw-bold'>" . phpversion() . "</span>";
                                                    } else {
                                                        echo "<span class='text-danger fw-bold'>" . phpversion() . "</span>";
                                                    } ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>upload_max_filesize</td>
                                                <td><?php echo $requiredUploadSize; ?> MB</td>
                                                <td>
                                                    <?php
                                                    if ($uploadMaxFilesize >= $requiredUploadSize) {
                                                        echo "<span class='text-success fw-bold'>" . format_size($uploadMaxFilesize) . "</span>";
                                                    } else {
                                                        echo "<span class='text-danger fw-bold'>" . format_size($uploadMaxFilesize) . "</span>";
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>post_max_size</td>
                                                <td><?php echo $requiredUploadSize; ?> MB</td>
                                                <td>
                                                    <?php
                                                    if ($postMaxSize >= $requiredUploadSize) {
                                                        echo "<span class='text-success fw-bold'>" . format_size($postMaxSize) . "</span>";
                                                    } else {
                                                        echo "<span class='text-danger fw-bold'>" . format_size($postMaxSize) . "</span>";
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>max_execution_time</td>
                                                <td><?php echo $app['required_max_execution_time']; ?></td>
                                                <td>
                                                    <?php
                                                    if ($currentMaxExecutionTime >= $app['required_max_execution_time']) {
                                                        echo "<span class='text-success fw-bold'>" . $currentMaxExecutionTime . "</span>";
                                                    } else {
                                                        echo "<span class='text-danger fw-bold'>" . $currentMaxExecutionTime . "</span>";
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>max_input_time</td>
                                                <td><?php echo $app['required_max_input_time']; ?></td>
                                                <td>
                                                    <?php
                                                    if ($currentMaxInputTime >= $app['required_max_input_time']) {
                                                        echo "<span class='text-success fw-bold'>" . $currentMaxInputTime . "</span>";
                                                    } else {
                                                        echo "<span class='text-danger fw-bold'>" . $currentMaxInputTime . "</span>";
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>memory_limit</td>
                                                <td><?php echo $app['required_memory_limit']; ?> MB</td>
                                                <td>
                                                    <?php
                                                    if ($currentMemoryLimit >= $app['required_memory_limit']) {
                                                        echo "<span class='text-success fw-bold'>" . $currentMemoryLimit . "</span>";
                                                    } else {
                                                        echo "<span class='text-danger fw-bold'>" . $currentMemoryLimit . "</span>";
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>Ordnerberechtigungen <span
                                                        class="badge bg-primary ms-1">/uploads/identities/</span></td>
                                                <td>0755</td>
                                                <td>
                                                    <?php
                                                    echo '<span class="' .
                                                        (substr(sprintf('%o', fileperms('./uploads/identities/')), -4) === '0755'
                                                            ? 'text-success'
                                                            : 'text-danger') .
                                                        ' fw-bold">' . substr(sprintf('%o', fileperms('./uploads/identities/')), -4) .
                                                        '</span>';

                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>Berechtigungen <span class="badge bg-primary ms-1">/backups/</span>
                                                </td>
                                                <td>0755</td>
                                                <td>
                                                    <?php
                                                    echo '<span class="' .
                                                        (substr(sprintf('%o', fileperms('./backups/')), -4) === '0755'
                                                            ? 'text-success'
                                                            : 'text-danger') .
                                                        ' fw-bold">' . substr(sprintf('%o', fileperms('./backups/')), -4) .
                                                        '</span>';

                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>Schreibrechte <span
                                                        class="badge bg-primary ms-1">config.inc.php</span>
                                                </td>
                                                <td>OK</td>
                                                <td>
                                                    <?php
                                                    if (is_writable('./config.inc.php')) {
                                                        echo '<span class="text-success fw-bold">OK</span>';
                                                    } else {
                                                        echo '<span class="text-danger fw-bold">FEHLER</span>';
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>Benutzer- und Gruppenbesitz <span
                                                        class="badge bg-primary ms-1">www-data:www-data</span></td>
                                                <td>OK</td>
                                                <td>
                                                    <?php
                                                    if (
                                                        iterator_count(
                                                            new CallbackFilterIterator(
                                                                new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__, RecursiveDirectoryIterator::SKIP_DOTS)),
                                                                fn($file) => posix_getpwuid(fileowner($file))['name'] !== 'www-data' || posix_getgrgid(filegroup($file))['name'] !== 'www-data'
                                                            )
                                                        ) === 0
                                                    ) {
                                                        echo '<span class="text-success fw-bold">OK</span>';
                                                    } else {
                                                        echo '<span class="text-danger fw-bold">FEHLER</span>';
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>PHP-Modul <span class="badge bg-primary ms-1">LDAP</span></td>
                                                <td>OK</td>
                                                <td>
                                                    <?php
                                                    if (extension_loaded('ldap')) {
                                                        echo '<span class="text-success fw-bold">OK</span>';
                                                    } else {
                                                        echo '<span class="text-danger fw-bold">FEHLT</span>';
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>PHP-Modul <span class="badge bg-primary ms-1">MYSQL</span></td>
                                                <td>OK</td>
                                                <td>
                                                    <?php
                                                    if (extension_loaded('mysqli')) {
                                                        echo '<span class="text-success fw-bold">OK</span>';
                                                    } else {
                                                        echo '<span class="text-danger fw-bold">FEHLT</span>';
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>PHP-Modul <span class="badge bg-primary ms-1">ZIP</span></td>
                                                <td>OK</td>
                                                <td>
                                                    <?php
                                                    if (extension_loaded('zip')) {
                                                        echo '<span class="text-success fw-bold">OK</span>';
                                                    } else {
                                                        echo '<span class="text-danger fw-bold">FEHLT</span>';
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>PHP-Modul <span class="badge bg-primary ms-1">MBSTRING</span></td>
                                                <td>OK</td>
                                                <td>
                                                    <?php
                                                    if (extension_loaded('mbstring')) {
                                                        echo '<span class="text-success fw-bold">OK</span>';
                                                    } else {
                                                        echo '<span class="text-danger fw-bold">FEHLT</span>';
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>PHP-Modul <span class="badge bg-primary ms-1">XML</span></td>
                                                <td>OK</td>
                                                <td>
                                                    <?php
                                                    if (extension_loaded('xml')) {
                                                        echo '<span class="text-success fw-bold">OK</span>';
                                                    } else {
                                                        echo '<span class="text-danger fw-bold">FEHLT</span>';
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-12 col-xl-4 grid-margin">
                            <div class="card grid-margin">
                                <div class="card-header bg-primary text-white">
                                    <i class="mdi mdi-cog me-1" style="line-height: 10px; font-size: 18px;"></i>
                                    Allgemein
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="timezone" class="form-label">Zeitzone</label>
                                        <select class="js-example-basic-single form-select form-control" name="timezone"
                                            data-width="100%">
                                            <?php
                                            foreach ($timezones as $timezone) {
                                                $selected = ($timezone === $defaultTimezone) ? ' selected' : '';
                                                echo '<option value="' . htmlspecialchars($timezone) . '"' . $selected . '>' . htmlspecialchars($timezone) . '</option>';
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="map_tile" class="form-label">Kartenmaterial</label>
                                        <input type="text" class="form-control" id="map_tile" name="map_tile"
                                            value="https://gisportal.geoinfo.svc/basemaps/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}">
                                    </div>
                                    <div class="mb-3">
                                        <label for="map_position" class="form-label">Kartenposition</label>
                                        <input type="text" class="form-control" id="map_position" name="map_position"
                                            value="31.834811982375992, 36.75910669462096">
                                    </div>
                                </div>
                            </div>

                            <div class="card grid-margin">
                                <div class="card-header bg-danger text-white">
                                    <i class="mdi mdi-backup-restore me-1"
                                        style="line-height: 10px; font-size: 18px;"></i>
                                    Wiederherstellung
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-primary" role="alert">
                                        Die Wiederherstellung wird nur ausgeführt, wenn eine gültige Backupdatei
                                        ausgewählt wurde.
                                    </div>
                                    <div class="mb-3">
                                        <label for="backupFile" class="form-label">Datei</label>
                                        <input type="file" name="backupFile" class="form-control" accept=".zip" />
                                    </div>

                                </div>
                            </div>

                        </div>

                    </div>

                </form>
                <!-- End -->

            </div>

            <footer class="footer border-top">
                <div class="container d-flex flex-row align-items-center justify-content-between py-3 small">
                    <p class="text-secondary mb-1 mb-md-0">Cedric Prietz</p>
                    <p class="text-secondary">
                        <?php echo $app['version']; ?>
                    </p>
                </div>
            </footer>

        </div>
    </div>

    <script src="/assets/vendors/core/core.js"></script>
    <script src="/assets/vendors/jquery/jquery.min.js"></script>
    <script src="/assets/vendors/jquery-validation/jquery.validate.min.js"></script>
    <script src="/assets/vendors/bootstrap-maxlength/bootstrap-maxlength.min.js"></script>
    <script src="/assets/vendors/inputmask/jquery.inputmask.min.js"></script>
    <script src="/assets/vendors/select2/select2.min.js"></script>
    <script src="/assets/vendors/typeahead.js/typeahead.bundle.min.js"></script>
    <script src="/assets/vendors/jquery-tags-input/jquery.tagsinput.min.js"></script>
    <script src="/assets/vendors/dropify/dist/dropify.min.js"></script>
    <script src="/assets/vendors/pickr/pickr.min.js"></script>
    <script src="/assets/vendors/moment/moment.min.js"></script>
    <script src="/assets/vendors/flatpickr/flatpickr.min.js"></script>
    <script src="/assets/vendors/feather-icons/feather.min.js"></script>
    <script src="/assets/vendors/datatables.net/dataTables.js"></script>
    <script src="/assets/vendors/datatables.net-bs5/dataTables.bootstrap5.js"></script>
    <script src="/assets/vendors/sweetalert2/sweetalert2.min.js"></script>
    <script src="/assets/vendors/easymde/easymde.min.js"></script>
    <script src="/assets/vendors/tinymce/tinymce.min.js"></script>

    <script src="/assets/js/data-table.js"></script>
    <script src="/assets/js/app.js"></script>
    <script src="/assets/js/form-validation.js"></script>
    <script src="/assets/js/bootstrap-maxlength.js"></script>
    <script src="/assets/js/inputmask.js"></script>
    <script src="/assets/js/select2.js"></script>
    <script src="/assets/js/typeahead.js"></script>
    <script src="/assets/js/tags-input.js"></script>
    <script src="/assets/js/dropify.js"></script>
    <script src="/assets/js/pickr.js"></script>
    <script src="/assets/js/flatpickr.js"></script>
    <script src="/assets/js/easymde.js"></script>
    <script src="/assets/js/tinymce.js"></script>

</body>

</html>