<?php
/**
 * WP Multi – Modul: Anti-Spam Honeypot
 *
 * Automatisch aus wp-multi.php ausgelagert. Wird über den Loader in
 * wp-multi.php eingebunden (nur wenn das WP Multi Toolkit aktiv ist).
 */

if (!defined('ABSPATH')) { exit; }

/*
* Anti Spam Honey 
*/


// Standardwerte setzen
function wp_multi_set_default_options() {
    add_option('wp_multi_honeypot_field', 'iwlxja5187');
    add_option('wp_multi_honeypot_error', 'Spamming or your Javascript is disabled !!');
    add_option('wp_multi_honeypot_widget', 0);
    add_option('wp_multi_max_links', 3);
    add_option('wp_multi_blocked_keywords', 'viagra,casino,bitcoin');
    add_option('wp_multi_blocked_ips', '');
    add_option('wp_multi_blocked_comments', 0); // Zähler für blockierte Kommentare
    add_option('wp_multi_honeypot_hits', 0); // Zähler für Honeypot-Aktivierungen
    add_option('wp_multi_spammer_ips', []); // Liste der blockierten Spammer-IP-Adressen
    add_option('wp_multi_spam_submissions', []); // Liste der Spam-Einreichungen
}
register_activation_hook(WP_MULTI_FILE, 'wp_multi_set_default_options');

// Die Sicherheits-Menüpunkte werden zentral in wp_multi_register_admin_menus() registriert.

// Einstellungsseite mit CSS & JS für Generator
function wp_multi_security_settings_page() {
    wpmt_admin_page_open(
        __('Sicherheit', 'wp-multi'),
        __('Anti-Spam, Honeypot und Kommentarfilter konfigurieren', 'wp-multi')
    );

    wpmt_admin_card_open();
    ?>
    <form method="post" action="options.php">
        <?php
        settings_fields('wp_multi_security_settings');
        do_settings_sections('wp-multi-security');
        submit_button();
        ?>
    </form>
    <script>
        function generateHoneypotName() {
            let field = document.getElementById('wp_multi_honeypot_field');
            let randomString = Math.random().toString(36).substring(2, 12);
            field.value = randomString;
        }
    </script>
    <?php
    wpmt_admin_card_close();

    wpmt_admin_page_close();
}

// Statistikseite im Dashboard
function wp_multi_statistics_page() {
    $blocked_comments = get_option('wp_multi_blocked_comments', 0);
    $honeypot_hits = get_option('wp_multi_honeypot_hits', 0);
    $spammer_ips = get_option('wp_multi_spammer_ips', []);
    $spam_submissions = get_option('wp_multi_spam_submissions', []);

    wpmt_admin_page_open(
        __('Anti-Spam Statistik', 'wp-multi'),
        __('Blockierte Kommentare, Honeypot-Treffer und erfasste Spammer-IPs', 'wp-multi')
    );

    echo '<div class="wpm-stats">';
    wpmt_admin_stat_card(__('Blockierte Kommentare', 'wp-multi'), number_format_i18n($blocked_comments), 'dashicons-dismiss');
    wpmt_admin_stat_card(__('Honeypot-Treffer', 'wp-multi'), number_format_i18n($honeypot_hits), 'dashicons-shield');
    wpmt_admin_stat_card(__('Spammer-IPs', 'wp-multi'), number_format_i18n(count($spammer_ips)), 'dashicons-admin-site-alt3');
    wpmt_admin_stat_card(__('Spam-Einreichungen', 'wp-multi'), number_format_i18n(count($spam_submissions)), 'dashicons-email-alt');
    echo '</div>';

    wpmt_admin_card_open(__('Spammer-IP-Adressen', 'wp-multi'));
    if (!empty($spammer_ips)) {
        ?>
        <div class="wpm-table-wrap">
            <table class="wpm-table">
                <thead>
                    <tr><th><?php esc_html_e('IP-Adresse', 'wp-multi'); ?></th></tr>
                </thead>
                <tbody>
                    <?php foreach ($spammer_ips as $ip) : ?>
                        <tr><td><?php echo esc_html($ip); ?></td></tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php
    } else {
        wpmt_admin_notice('info', __('Keine Spammer-IP-Adressen gefunden.', 'wp-multi'));
    }
    wpmt_admin_card_close();

    wpmt_admin_page_close();
}


// Einstellungen registrieren
function wp_multi_register_security_settings() {
    register_setting('wp_multi_security_settings', 'wp_multi_honeypot_field');
    register_setting('wp_multi_security_settings', 'wp_multi_honeypot_error');
    register_setting('wp_multi_security_settings', 'wp_multi_honeypot_widget');
    register_setting('wp_multi_security_settings', 'wp_multi_max_links');
    register_setting('wp_multi_security_settings', 'wp_multi_blocked_keywords');
    register_setting('wp_multi_security_settings', 'wp_multi_blocked_ips');

    add_settings_section('wp_multi_honeypot_section', 'Honeypot Einstellungen', null, 'wp-multi-security');

    add_settings_field('wp_multi_honeypot_field', 'Honey Pot Field Name', 'wp_multi_honeypot_field_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
    add_settings_field('wp_multi_honeypot_error', 'Honey Pot Error Message', 'wp_multi_honeypot_error_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
    add_settings_field('wp_multi_honeypot_widget', 'Disable Honeypot Test Widget', 'wp_multi_honeypot_widget_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
    add_settings_field('wp_multi_max_links', 'Maximale Links im Kommentar', 'wp_multi_max_links_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
    add_settings_field('wp_multi_blocked_keywords', 'Blockierte Schlüsselwörter', 'wp_multi_blocked_keywords_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
    add_settings_field('wp_multi_blocked_ips', 'Blockierte IP-Adressen', 'wp_multi_blocked_ips_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
}

add_action('admin_init', 'wp_multi_register_security_settings');

function wp_multi_honeypot_field_callback() {
    ?>
    <div class="wp-multi-honeypot-group">
        <input type="text" id="wp_multi_honeypot_field" name="wp_multi_honeypot_field" value="<?php echo esc_attr(get_option('wp_multi_honeypot_field')); ?>">
        <button type="button" onclick="generateHoneypotName()">Generieren</button>
    </div>
    <small>Verwenden Sie ein zufälliges Zeichenfolgen für das Honeypot-Feld.</small>
    <?php
}

function wp_multi_honeypot_error_callback() {
    ?>
    <input type="text" name="wp_multi_honeypot_error" value="<?php echo esc_attr(get_option('wp_multi_honeypot_error')); ?>">
    <small>Die Nachricht, die angezeigt wird, wenn ein Honeypot ausgelöst wird.</small>
    <?php
}

function wp_multi_honeypot_widget_callback() {
    ?>
    <input type="checkbox" name="wp_multi_honeypot_widget" value="1" <?php checked(1, get_option('wp_multi_honeypot_widget'), true); ?>>
    <small>Deaktivieren Sie das Honeypot-Test-Widget im Frontend.</small>
    <?php
}

function wp_multi_max_links_callback() {
    ?>
    <input type="number" name="wp_multi_max_links" value="<?php echo esc_attr(get_option('wp_multi_max_links')); ?>">
    <small>Maximale Anzahl von Links, die in einem Kommentar erlaubt sind.</small>
    <?php
}

function wp_multi_blocked_keywords_callback() {
    ?>
    <input type="text" name="wp_multi_blocked_keywords" value="<?php echo esc_attr(get_option('wp_multi_blocked_keywords')); ?>">
    <small>Schlüsselwörter, die blockiert werden sollen (durch Kommas getrennt).</small>
    <?php
}

function wp_multi_blocked_ips_callback() {
    ?>
    <textarea name="wp_multi_blocked_ips" rows="5"><?php echo esc_textarea(get_option('wp_multi_blocked_ips')); ?></textarea>
    <small>Blockierte IP-Adressen (jede Adresse in einer neuen Zeile).</small>
    <?php
}

// Honeypot-Feld (unsichtbar für Menschen) im Kommentarformular ausgeben
function wp_multi_render_honeypot_field() {
    $field_name = get_option('wp_multi_honeypot_field', 'iwlxja5187');
    ?>
    <p class="wp-multi-honeypot" style="position:absolute !important; left:-9999px !important; top:-9999px !important;" aria-hidden="true">
        <label for="<?php echo esc_attr($field_name); ?>"><?php esc_html_e('Website (bitte leer lassen)', 'wp-multi'); ?></label>
        <input type="text" name="<?php echo esc_attr($field_name); ?>" id="<?php echo esc_attr($field_name); ?>" value="" tabindex="-1" autocomplete="off">
    </p>
    <input type="hidden" name="wp_multi_form_time" value="<?php echo esc_attr(time()); ?>">
    <?php
}
add_action('comment_form_top', 'wp_multi_render_honeypot_field');

// Zähler/Statistik für einen geblockten Spam-Versuch aktualisieren
function wp_multi_register_spam_hit($reason, $ip = '') {
    update_option('wp_multi_honeypot_hits', get_option('wp_multi_honeypot_hits', 0) + 1);
    update_option('wp_multi_blocked_comments', get_option('wp_multi_blocked_comments', 0) + 1);

    if ($ip) {
        $spammer_ips = get_option('wp_multi_spammer_ips', []);
        if (!in_array($ip, $spammer_ips, true)) {
            $spammer_ips[] = $ip;
            update_option('wp_multi_spammer_ips', $spammer_ips);
        }
    }

    $submissions = get_option('wp_multi_spam_submissions', []);
    $submissions[] = [
        'reason'    => $reason,
        'ip'        => $ip,
        'timestamp' => current_time('mysql'),
    ];
    // Auf die letzten 200 Einträge begrenzen, damit die Option nicht unbegrenzt wächst
    if (count($submissions) > 200) {
        $submissions = array_slice($submissions, -200);
    }
    update_option('wp_multi_spam_submissions', $submissions);
}

// Honeypot-/Zeitfallen-Prüfung sowie IP-/Keyword-/Link-Filter beim Absenden eines Kommentars
function wp_multi_validate_comment_submission($commentdata) {
    $ip = function_exists('get_user_ip') ? get_user_ip() : (isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '');

    // Honeypot-Feld: darf von einem Menschen nie ausgefüllt werden
    $field_name = get_option('wp_multi_honeypot_field', 'iwlxja5187');
    if (!empty($_POST[$field_name])) {
        wp_multi_register_spam_hit('honeypot', $ip);
        wp_die(esc_html(get_option('wp_multi_honeypot_error', 'Spamming or your Javascript is disabled !!')));
    }

    // Zeit-Falle: Formular darf nicht schneller als 3 Sekunden nach dem Laden abgeschickt werden
    if (isset($_POST['wp_multi_form_time'])) {
        $elapsed = time() - absint($_POST['wp_multi_form_time']);
        if ($elapsed < 3) {
            wp_multi_register_spam_hit('honeypot_zeitfalle', $ip);
            wp_die(esc_html(get_option('wp_multi_honeypot_error', 'Spamming or your Javascript is disabled !!')));
        }
    }

    // Blockierte IP-Adressen
    $blocked_ips = array_filter(array_map('trim', explode("\n", (string) get_option('wp_multi_blocked_ips', ''))));
    if ($ip && in_array($ip, $blocked_ips, true)) {
        wp_multi_register_spam_hit('blocked_ip', $ip);
        wp_die(esc_html__('Deine IP-Adresse wurde für Kommentare gesperrt.', 'wp-multi'));
    }

    $content = isset($commentdata['comment_content']) ? $commentdata['comment_content'] : '';

    // Blockierte Schlüsselwörter
    $blocked_keywords = array_filter(array_map('trim', explode(',', (string) get_option('wp_multi_blocked_keywords', ''))));
    foreach ($blocked_keywords as $keyword) {
        if ($keyword !== '' && stripos($content, $keyword) !== false) {
            wp_multi_register_spam_hit('keyword', $ip);
            wp_die(esc_html__('Dein Kommentar enthält nicht erlaubte Inhalte.', 'wp-multi'));
        }
    }

    // Maximale Anzahl an Links im Kommentar
    $max_links = absint(get_option('wp_multi_max_links', 3));
    if ($max_links > 0 && preg_match_all('#https?://#i', $content) > $max_links) {
        wp_multi_register_spam_hit('links', $ip);
        wp_die(esc_html__('Dein Kommentar enthält zu viele Links.', 'wp-multi'));
    }

    // Kommentarfilter: Telefonnummern, E-Mails, URLs, IPs, Schimpfwörter durch * ersetzen
    $commentdata['comment_content'] = wp_multi_apply_comment_content_filter($content);

    return $commentdata;
}
add_filter('preprocess_comment', 'wp_multi_validate_comment_submission');


