HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux bsx-1-dev 6.8.0-101-generic #101-Ubuntu SMP PREEMPT_DYNAMIC Mon Feb 9 10:15:05 UTC 2026 x86_64
User: www-data (33)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/www/html/wp-content/plugins/bsx/be/pref-user-main.php
<?php
/**
 * User Preferences - CLEAN VERSION
 * Nur die benötigten Shortcodes & Funktionen
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// =====================================================
// TABELLEN-KONFIGURATION
// =====================================================

define('UP_TABLE_NAME', 'wp_bsx_up');

function up_get_table_name() {
    return UP_TABLE_NAME;
}


// =====================================================
// REST API ENDPUNKTE
// =====================================================

add_action('rest_api_init', function() {
    // Get preferences
    register_rest_route('user-preferences/v1', '/preferences', array(
        'methods' => 'GET',
        'callback' => 'up_get_preferences',
        'permission_callback' => function() { return is_user_logged_in(); },
    ));

    // Create preference
    register_rest_route('user-preferences/v1', '/preferences', array(
        'methods' => 'POST',
        'callback' => 'up_create_preference',
        'permission_callback' => function() { return is_user_logged_in(); },
    ));

    // Update preference
    register_rest_route('user-preferences/v1', '/preferences/(?P<id>\d+)', array(
        'methods' => 'PUT',
        'callback' => 'up_update_preference',
        'permission_callback' => function() { return is_user_logged_in(); },
    ));

    // Delete preference
    register_rest_route('user-preferences/v1', '/preferences/(?P<id>\d+)', array(
        'methods' => 'DELETE',
        'callback' => 'up_delete_preference',
        'permission_callback' => function() { return is_user_logged_in(); },
    ));
});

function up_get_preferences(WP_REST_Request $request) {
    global $wpdb;
    $table_name = up_get_table_name();
    $current_user_id = get_current_user_id();

    $results = $wpdb->get_results($wpdb->prepare(
        "SELECT * FROM $table_name WHERE user_id = %d ORDER BY created_at DESC",
        $current_user_id
    ));

    $preferences = array();
    foreach ($results as $row) {
        $preferences[] = array(
            'id' => (string) $row->id,
            'userId' => (string) $row->user_id,
            'itemId' => $row->item_id,
            'itemName' => $row->item_name,
            'type' => $row->type,
            'notifyEmail' => (bool) $row->notify_email,
            'notifyPush' => (bool) $row->notify_push,
            'createdAt' => mysql2date('c', $row->created_at),
            'updatedAt' => mysql2date('c', $row->updated_at)
        );
    }

    return rest_ensure_response($preferences);
}

function up_create_preference(WP_REST_Request $request) {
    global $wpdb;
    $table_name = up_get_table_name();
    $current_user_id = get_current_user_id();

    $data = json_decode($request->get_body(), true);
    
    if (empty($data['itemId']) || empty($data['itemName']) || empty($data['type'])) {
        return new WP_Error('missing_fields', 'Missing required fields', array('status' => 400));
    }

    if (!in_array($data['type'], array('campaign', 'cassandra'))) {
        return new WP_Error('invalid_type', 'Type must be "campaign" or "cassandra"', array('status' => 400));
    }

    // Check if exists
    $exists = $wpdb->get_var($wpdb->prepare(
        "SELECT id FROM $table_name WHERE user_id = %d AND item_id = %s AND type = %s",
        $current_user_id,
        sanitize_text_field($data['itemId']),
        sanitize_text_field($data['type'])
    ));

    if ($exists) {
        return new WP_Error('duplicate', 'Preference already exists', array('status' => 409));
    }

    // Insert
    $result = $wpdb->insert(
        $table_name,
        array(
            'user_id' => $current_user_id,
            'item_id' => sanitize_text_field($data['itemId']),
            'item_name' => sanitize_text_field($data['itemName']),
            'type' => sanitize_text_field($data['type']),
            'notify_email' => isset($data['notifyEmail']) ? (int) $data['notifyEmail'] : 1,
            'notify_push' => isset($data['notifyPush']) ? (int) $data['notifyPush'] : 0,
        ),
        array('%d', '%s', '%s', '%s', '%d', '%d')
    );

    if ($result === false) {
        return new WP_Error('database_error', 'Failed to create preference', array('status' => 500));
    }

    $preference_id = $wpdb->insert_id;
    $preference = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM $table_name WHERE id = %d",
        $preference_id
    ));

    return rest_ensure_response(array(
        'id' => (string) $preference->id,
        'userId' => (string) $preference->user_id,
        'itemId' => $preference->item_id,
        'itemName' => $preference->item_name,
        'type' => $preference->type,
        'notifyEmail' => (bool) $preference->notify_email,
        'notifyPush' => (bool) $preference->notify_push,
        'createdAt' => mysql2date('c', $preference->created_at),
        'updatedAt' => mysql2date('c', $preference->updated_at)
    ));
}

function up_update_preference(WP_REST_Request $request) {
    global $wpdb;
    $table_name = up_get_table_name();
    $current_user_id = get_current_user_id();
    $preference_id = $request->get_param('id');

    // Verify ownership
    $preference = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM $table_name WHERE id = %d AND user_id = %d",
        $preference_id,
        $current_user_id
    ));

    if (!$preference) {
        return new WP_Error('not_found', 'Preference not found', array('status' => 404));
    }

    $data = json_decode($request->get_body(), true);

    $update_data = array();
    $update_format = array();

    if (isset($data['notifyEmail'])) {
        $update_data['notify_email'] = (int) $data['notifyEmail'];
        $update_format[] = '%d';
    }

    if (isset($data['notifyPush'])) {
        $update_data['notify_push'] = (int) $data['notifyPush'];
        $update_format[] = '%d';
    }

    if (empty($update_data)) {
        return new WP_Error('no_fields', 'No fields to update', array('status' => 400));
    }

    $wpdb->update(
        $table_name,
        $update_data,
        array('id' => $preference_id),
        $update_format,
        array('%d')
    );

    $updated = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM $table_name WHERE id = %d",
        $preference_id
    ));

    return rest_ensure_response(array(
        'id' => (string) $updated->id,
        'userId' => (string) $updated->user_id,
        'itemId' => $updated->item_id,
        'itemName' => $updated->item_name,
        'type' => $updated->type,
        'notifyEmail' => (bool) $updated->notify_email,
        'notifyPush' => (bool) $updated->notify_push,
        'createdAt' => mysql2date('c', $updated->created_at),
        'updatedAt' => mysql2date('c', $updated->updated_at)
    ));
}

function up_delete_preference(WP_REST_Request $request) {
    global $wpdb;
    $table_name = up_get_table_name();
    $current_user_id = get_current_user_id();
    $preference_id = $request->get_param('id');

    // Verify ownership
    $preference = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM $table_name WHERE id = %d AND user_id = %d",
        $preference_id,
        $current_user_id
    ));

    if (!$preference) {
        return new WP_Error('not_found', 'Preference not found', array('status' => 404));
    }

    $wpdb->delete(
        $table_name,
        array('id' => $preference_id),
        array('%d')
    );

    return rest_ensure_response(array(
        'success' => true,
        'message' => 'Preference deleted'
    ));
}

// =====================================================
// SHORTCODE 1: Dual Icons (für Single Pages)
// =====================================================

function up_preference_icons_shortcode($atts) {
    if (!is_user_logged_in()) {
        return '';
    }

    $atts = shortcode_atts(array(
        'item_id' => get_the_ID(),
        'item_type' => get_post_type(),
        'item_name' => get_the_title()
    ), $atts);

    $unique_id = 'dual-badge-' . uniqid();

    ob_start();
    ?>
    <div id="<?php echo esc_attr($unique_id); ?>" 
         class="dual-preference-badge-container"
         data-item-id="<?php echo esc_attr($atts['item_id']); ?>" 
         data-item-type="<?php echo esc_attr($atts['item_type']); ?>" 
         data-item-name="<?php echo esc_attr($atts['item_name']); ?>">
    </div>
    <?php
    
    add_action('wp_footer', function() use ($unique_id) {
        ?>
        <script>
        (function() {
            function initDualBadge() {
                if (typeof UserPreferencesManager === 'undefined' || typeof DualPreferenceBadge === 'undefined') {
                    setTimeout(initDualBadge, 100);
                    return;
                }
                
                const container = document.getElementById('<?php echo esc_js($unique_id); ?>');
                if (!container) return;
                
                if (!window.globalPreferencesManager) {
                    window.globalPreferencesManager = new UserPreferencesManager();
                    window.globalPreferencesManager.init().then(function() {
                        const badge = new DualPreferenceBadge(
                            window.globalPreferencesManager,
                            container.dataset.itemId,
                            container.dataset.itemType,
                            container.dataset.itemName
                        );
                        badge.init(container);
                    });
                } else {
                    const badge = new DualPreferenceBadge(
                        window.globalPreferencesManager,
                        container.dataset.itemId,
                        container.dataset.itemType,
                        container.dataset.itemName
                    );
                    badge.init(container);
                }
            }
            
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', initDualBadge);
            } else {
                initDualBadge();
            }
        })();
        </script>
        <?php
    }, 999);
    
    return ob_get_clean();
}
add_shortcode('preference_icons', 'up_preference_icons_shortcode');

// =====================================================
// SHORTCODE 2: Minimal List (für Account Page)
// =====================================================

function up_preferences_list_minimal_shortcode($atts) {
    if (!is_user_logged_in()) {
        return '<p>Bitte logge dich ein.</p>';
    }

    $atts = shortcode_atts(array(
        'title' => ''
    ), $atts);

    global $wpdb;
    $table_name = up_get_table_name();
    $user_id = get_current_user_id();

    $preferences = $wpdb->get_results($wpdb->prepare(
        "SELECT * FROM $table_name WHERE user_id = %d ORDER BY created_at DESC",
        $user_id
    ));

    if (empty($preferences)) {
        return '<p class="no-preferences">Du hast noch keine Präferenzen gespeichert.</p>';
    }

    ob_start();
    ?>
    <div class="preferences-list-minimal">
        <?php if ($atts['title']) : ?>
            <h3><?php echo esc_html($atts['title']); ?></h3>
        <?php endif; ?>
        
        <div class="preferences-grid">
            <?php foreach ($preferences as $pref) : ?>
                <div class="preference-card">
                    <div class="preference-card-content">
                        <div class="preference-card-header">
                            <span class="preference-type-icon">
                                <?php echo $pref->type === 'campaign' ? '📢' : '🔮'; ?>
                            </span>
                            <h4 class="preference-card-title">
                                <a href="<?php echo get_permalink($pref->item_id); ?>">
                                    <?php echo esc_html($pref->item_name); ?>
                                </a>
                            </h4>
                        </div>
                        
                        <div class="preference-card-icons">
                            <span class="icon-indicator active" title="Favorit">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                                </svg>
                            </span>
                            
                            <?php if ($pref->notify_email) : ?>
                                <span class="icon-indicator active email" title="E-Mail">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                        <path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/>
                                    </svg>
                                </span>
                            <?php endif; ?>
                            
                            <?php if ($pref->notify_push) : ?>
                                <span class="icon-indicator active push" title="Push">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                        <path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/>
                                    </svg>
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('preferences_list_minimal', 'up_preferences_list_minimal_shortcode');

// =====================================================
// SCRIPTS ENQUEUE
// =====================================================

function up_enqueue_preference_scripts() {
    if (!is_user_logged_in()) {
        return;
    }

    $plugin_url = plugins_url('bsx');

    // CSS
    wp_enqueue_style('user-preferences',
        $plugin_url . '/ass/css/dualPreferenceBadge.css',
        array(), '1.0.0'
    );

    // JavaScript
    wp_enqueue_script('user-preferences-manager',
        $plugin_url . '/ass/js/userPreferences-clean.js',
        array(), '1.0.0', true
    );

    wp_enqueue_script('dual-preference-badge',
        $plugin_url . '/ass/js/dualPreferenceBadge-clean.js',
        array('user-preferences-manager'), '1.0.0', true
    );

    // Localize
    wp_localize_script('user-preferences-manager', 'userPreferencesConfig', array(
        'apiEndpoint' => rest_url('user-preferences/v1'),
        'userId' => get_current_user_id(),
        'nonce' => wp_create_nonce('wp_rest'),
        'isLoggedIn' => true
    ));
}
add_action('wp_enqueue_scripts', 'up_enqueue_preference_scripts');
?>