__( 'Security check failed. Please reload the page.', 'ai-featured-image' ) ], 403 ); } // 2. Berechtigungen prüfen if ( ! current_user_can( 'edit_posts' ) || ! current_user_can( 'upload_files' ) ) { wp_send_json_error( [ 'message' => __( 'Insufficient permission to edit posts and upload files.', 'ai-featured-image' ) ], 403 ); } // 3. Daten aus Request holen und validieren $post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0; $custom_prompt = isset( $_POST['prompt'] ) ? sanitize_textarea_field( wp_unslash( $_POST['prompt'] ) ) : ''; $negative_prompt = isset( $_POST['negative_prompt'] ) ? sanitize_textarea_field( wp_unslash( $_POST['negative_prompt'] ) ) : ''; // Post ID Validierung if ( ! $post_id || ! get_post_status( $post_id ) ) { // Prüft auch, ob der Post existiert wp_send_json_error( [ 'message' => __( 'Invalid or non-existent page - or post ID.', 'ai-featured-image' ) ], 400 ); } // 4. API Einstellungen laden $options = get_option( 'aifi_settings' ); $api_service = isset( $options['api_service'] ) ? $options['api_service'] : 'stabilityai'; $api_key = null; // Korrekten API-Schlüssel basierend auf dem gewählten Dienst laden if ( $api_service === 'clipdrop' ) { $api_key = $options['clipdrop_api_key'] ?? null; } elseif ( $api_service === 'stabilityai' ) { $api_key = $options['stabilityai_api_key'] ?? null; } elseif ( $api_service === 'google' ) { $api_key = $options['google_api_key'] ?? null; } elseif ( $api_service === 'pollinations' ) { // Kein API Key für Pollinations gemäß aktueller Annahme/Cheatsheet GET } else { wp_send_json_error( [ 'message' => __( 'No valid API service selected in the settings.', 'ai-featured-image' ) ], 400 ); } // API Key Prüfung (außer für Pollinations, wenn es keinen Key braucht) if ( $api_service !== 'pollinations' && empty( $api_key ) ) { // translators: %s: Suchbegriff, nach dem gefiltert wurde. wp_send_json_error( [ 'message' => sprintf( __( 'API key not configured for service "%s".', 'ai-featured-image' ), ucfirst( $api_service ) ) ], 400 ); } // --- 5. Prompt bestimmen (ANGEPASSTE LOGIK) --- $prompt = trim( $custom_prompt ); $prompt_source = $options['prompt_source'] ?? 'title'; // Einstellung holen, Default 'title' if ( empty( $prompt ) ) { // Nur wenn kein Custom Prompt da ist, automatisch generieren switch ( $prompt_source ) { case 'excerpt': if ( has_excerpt( $post_id ) ) { $prompt = get_the_excerpt( $post_id ); } else { // Fallback, falls kein manueller Auszug da ist -> Titel nehmen $prompt = get_the_title( $post_id ); // Optional: Hier könnte man noch wp_trim_excerpt() für automatisch generierte Auszüge versuchen, // aber das kann manchmal leer sein oder unerwartete Ergebnisse liefern. Titel ist sicherer. } break; case 'content': $post_obj = get_post( $post_id ); if ( $post_obj && !empty( $post_obj->post_content ) ) { $content = $post_obj->post_content; // Bereinigen: Shortcodes entfernen, HTML-Tags entfernen, Whitespace trimmen $cleaned_content = trim( wp_strip_all_tags( strip_shortcodes( $content ), true ) ); // true entfernt auch Zeilenumbrüche etc. // Kürzen auf ca. 300 Zeichen (Wert ggf. anpassen oder konfigurierbar machen) $prompt = mb_substr( $cleaned_content, 0, 300 ); } else { // Fallback auf Titel, wenn kein Inhalt vorhanden $prompt = get_the_title( $post_id ); } break; case 'title': default: // Standard und Fallback $prompt = get_the_title( $post_id ); break; } // Bereinigen und sicherstellen, dass der Prompt nicht leer ist $prompt = trim( $prompt ); if ( empty( $prompt ) ) { // Absoluter Fallback, falls Titel/Auszug/Inhalt auch leer sein sollten $prompt = __( 'Image for post or page', 'ai-featured-image' ) . ' ' . $post_id; } } else { $prompt = __( 'Image for post or page', 'ai-featured-image' ) . ' ' . $post_id; } // Längenprüfung (als Beispiel - Limit kann je nach API variieren) $max_prompt_length = 1000; if ( mb_strlen( $prompt ) > $max_prompt_length ) { $prompt = mb_substr( $prompt, 0, $max_prompt_length ); } // Längenprüfung für negativen Prompt (optional, aber sinnvoll) if ( mb_strlen( $negative_prompt ) > $max_prompt_length ) { $negative_prompt = mb_substr( $negative_prompt, 0, $max_prompt_length ); } // 6. API Handler aufrufen $api_handler = new AIFI_API_Handler( $api_service, $api_key ); // Negativen Prompt übergeben: $result = $api_handler->generate_image( $prompt, $post_id, $negative_prompt ); // 7. Ergebnis verarbeiten if ( is_wp_error( $result ) ) { // Der Fehler wurde bereits im API Handler geloggt wp_send_json_error( [ 'message' => $result->get_error_message() ], 500 ); // Sende Fehler an JS } else { $attachment_id = $result; // Sollte die Attachment ID sein // Als Beitragsbild setzen if ( set_post_thumbnail( $post_id, $attachment_id ) ) { $thumbnail_html = get_the_post_thumbnail( $post_id, 'thumbnail' ); // Hole HTML für JS Update wp_send_json_success( [ 'message' => __( 'The post image was successfully generated and saved!', 'ai-featured-image' ), 'attachment_id' => $attachment_id, 'thumbnail_html' => $thumbnail_html // Optional: Zur Aktualisierung der UI im Editor ] ); } else { // Bild wurde zwar hochgeladen, aber nicht gesetzt. Informiere den User. // Wir senden trotzdem Success=true, da das Bild ja da ist, aber mit anderer Message // translators: %s: Bild-ID, nach der gefiltert wurde. wp_send_json_success( [ // translators: %s: Media-ID, nach der gefiltert wurde. 'message' => sprintf( __( 'The image was added to the media library (ID: "%s"), but could not be automatically set as a featured image. Please select it manually.', 'ai-featured-image' ), $attachment_id ), 'attachment_id' => $attachment_id, 'thumbnail_html' => '' // Kein Thumbnail HTML, da nicht gesetzt ] ); } } // Wichtig: wp_send_json_* ruft intern wp_die() auf. // Ein explizites wp_die() ist danach nicht mehr nötig und würde ggf. die Ausgabe stören. } } // Ende der Klasse