<?php
/**
 * PHP Honeypot System 
 * Erkennt und blockiert Bots und Spam-Angriffe
 */

// Konfiguration
$HONEYPOT_FIELD = 'hp_field';
$TIME_FIELD = 'hp_time';
$MIN_SUBMISSION_TIME = 3; // Mindestzeit in Sekunden
$MAX_SUBMISSION_TIME = 3600; // Maximalzeit in Sekunden (1 Stunde)
$LOG_FILE = 'honeypot_log.txt';

/**
 * Generiert versteckte Honeypot-Felder für Formulare
 */
function honeypot_generate_fields($honeypot_field, $time_field) {
    $timestamp = time();
    $html = '';
    
    // Verstecktes Feld für Bots (sollte leer bleiben)
    $html .= '<div style="position: absolute; left: -9999px; top: -9999px;">';
    $html .= '<input type="text" name="' . htmlspecialchars($honeypot_field) . '" value="" tabindex="-1" autocomplete="off">';
    $html .= '</div>';
    
    // Zeitstempel-Feld
    $html .= '<input type="hidden" name="' . htmlspecialchars($time_field) . '" value="' . $timestamp . '">';
    
    return $html;
}

/**
 * Überprüft, ob die Submission ein Bot ist
 */
function honeypot_is_bot($honeypot_field, $time_field, $min_time, $max_time) {
    $reasons = array();
    
    // 1. Honeypot-Feld-Check
    if (!empty($_POST[$honeypot_field])) {
        $reasons[] = 'Honeypot field filled';
    }
    
    // 2. Zeitbasierte Überprüfung
    if (isset($_POST[$time_field])) {
        $submission_time = time() - (int)$_POST[$time_field];
        
        if ($submission_time < $min_time) {
            $reasons[] = 'Submission too fast (' . $submission_time . 's)';
        }
        
        if ($submission_time > $max_time) {
            $reasons[] = 'Submission too slow (' . $submission_time . 's)';
        }
    } else {
        $reasons[] = 'Missing timestamp';
    }
    
    // 3. User-Agent-Check
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $reasons[] = 'Missing User-Agent';
    }
    
    // 4. Referer-Check (optional)
    if (empty($_SERVER['HTTP_REFERER']) && isset($_POST['submit'])) {
        $reasons[] = 'Missing Referer';
    }
    
    // 5. Verdächtige User-Agents
    $suspicious_agents = array('bot', 'crawler', 'spider', 'scraper', 'curl', 'wget');
    $user_agent = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
    
    foreach ($suspicious_agents as $agent) {
        if (strpos($user_agent, $agent) !== false) {
            $reasons[] = 'Suspicious User-Agent: ' . $agent;
            break;
        }
    }
    
    if (!empty($reasons)) {
        honeypot_log_bot($reasons);
        return true;
    }
    
    return false;
}

/**
 * Protokolliert Bot-Versuche
 */
function honeypot_log_bot($reasons) {
    global $LOG_FILE;
    
    $log_entry = array(
        'timestamp' => date('Y-m-d H:i:s'),
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        'reasons' => $reasons,
        'post_data' => $_POST
    );
    
    $log_line = json_encode($log_entry) . "\n";
    file_put_contents($LOG_FILE, $log_line, FILE_APPEND | LOCK_EX);
}

/**
 * Blockiert Bot-Anfragen
 */
function honeypot_block_bot() {
    http_response_code(403);
    die('Access Denied');
}

/**
 * Erweiterte Bot-Erkennung basierend auf Verhalten
 */
function honeypot_advanced_detection() {
    $score = 0;
    
    // JavaScript-Check
    if (!isset($_POST['js_enabled']) || $_POST['js_enabled'] !== '1') {
        $score += 2;
    }
    
    // Formular-Interaktion-Check
    if (!isset($_POST['form_interactions']) || (int)$_POST['form_interactions'] < 1) {
        $score += 1;
    }
    
    // Maus-Bewegung-Check
    if (!isset($_POST['mouse_moved']) || $_POST['mouse_moved'] !== '1') {
        $score += 1;
    }
    
    // Rate Limiting Check
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    $rate_limit_file = 'rate_limit_' . md5($ip) . '.txt';
    
    if (file_exists($rate_limit_file)) {
        $last_submission = (int)file_get_contents($rate_limit_file);
        if (time() - $last_submission < 10) { // 10 Sekunden zwischen Submissions
            $score += 3;
        }
    }
    
    file_put_contents($rate_limit_file, time());
    
    return $score >= 3; // Threshold für Bot-Erkennung
}

/**
 * Validiert alle Honeypot-Checks
 */
function honeypot_validate($honeypot_field, $time_field, $min_time, $max_time) {
    return honeypot_is_bot($honeypot_field, $time_field, $min_time, $max_time) || 
           honeypot_advanced_detection();
}

/**
 * Bereinigt Eingabedaten
 */
function honeypot_sanitize_input($data) {
    return htmlspecialchars(strip_tags(trim($data)));
}

/**
 * Validiert E-Mail-Adresse
 */
function honeypot_validate_email($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

/**
 * Verarbeitet das Formular
 */
function process_form() {
    if (!honeypot_validate_email($_POST['email'])) {
        return "Ungültige E-Mail-Adresse.";
    }
    
    $name = honeypot_sanitize_input($_POST['name']);
    $email = honeypot_sanitize_input($_POST['email']);
    $message = honeypot_sanitize_input($_POST['message']);
    
    // Hier würden Sie normalerweise die Daten speichern oder eine E-Mail senden
    // Beispiel: E-Mail senden, Datenbank-Eintrag, etc.
    
    return "Vielen Dank, $name! Ihre Nachricht wurde erfolgreich versendet.";
}

// Hauptlogik
$form_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (honeypot_validate($HONEYPOT_FIELD, $TIME_FIELD, $MIN_SUBMISSION_TIME, $MAX_SUBMISSION_TIME)) {
        honeypot_block_bot();
    } else {
        $form_message = process_form();
    }
}
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Honeypot-geschütztes Formular (Prozedural)</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        button { background: #007cba; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #005a87; }
        .message { padding: 10px; margin: 20px 0; border-radius: 4px; background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
    </style>
</head>
<body>
    <h1>Kontaktformular</h1>
    
    <?php if ($form_message): ?>
        <div class="message"><?php echo htmlspecialchars($form_message); ?></div>
    <?php endif; ?>
    
    <form method="POST" action="" id="contactForm">
        <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required>
        </div>
        
        <div class="form-group">
            <label for="email">E-Mail:</label>
            <input type="email" id="email" name="email" required>
        </div>
        
        <div class="form-group">
            <label for="message">Nachricht:</label>
            <textarea id="message" name="message" rows="5" required></textarea>
        </div>
        
        <!-- Honeypot-Felder -->
        <?php echo honeypot_generate_fields($HONEYPOT_FIELD, $TIME_FIELD); ?>
        
        <!-- Versteckte Felder für erweiterte Bot-Erkennung -->
        <input type="hidden" name="js_enabled" value="0" id="js_enabled">
        <input type="hidden" name="form_interactions" value="0" id="form_interactions">
        <input type="hidden" name="mouse_moved" value="0" id="mouse_moved">
        
        <button type="submit" name="submit">Absenden</button>
    </form>

    <script>
        // JavaScript für erweiterte Bot-Erkennung
        document.getElementById('js_enabled').value = '1';
        
        let interactions = 0;
        let mouseMoved = false;
        
        // Zähle Formular-Interaktionen
        document.querySelectorAll('input, textarea').forEach(function(field) {
            field.addEventListener('focus', function() {
                interactions++;
                document.getElementById('form_interactions').value = interactions;
            });
        });
        
        // Maus-Bewegung tracken
        document.addEventListener('mousemove', function() {
            if (!mouseMoved) {
                mouseMoved = true;
                document.getElementById('mouse_moved').value = '1';
            }
        });
        
        // Formular-Validierung
        document.getElementById('contactForm').addEventListener('submit', function(e) {
            var name = document.getElementById('name').value.trim();
            var email = document.getElementById('email').value.trim();
            var message = document.getElementById('message').value.trim();
            
            if (!name || !email || !message) {
                e.preventDefault();
                alert('Bitte füllen Sie alle Felder aus.');
            }
        });
    </script>
</body>
</html>

