diff --git a/includes/class-psa-admin.php b/includes/class-psa-admin.php new file mode 100755 index 0000000..bded3db --- /dev/null +++ b/includes/class-psa-admin.php @@ -0,0 +1,264 @@ + array( __CLASS__, 'sanitize_settings' ), + ) + ); + + // OpenRouter Section. + add_settings_section( + 'psa_ai_section', + __( 'OpenRouter API Settings', 'peptide-search-ai' ), + array( __CLASS__, 'render_section_description' ), + 'peptide-search-ai' + ); + add_settings_field( + 'api_key', + __( 'API Key', 'peptide-search-ai' ), + array( __CLASS__, 'render_api_key_field' ), + 'peptide-search-ai', + 'psa_ai_section' + ); + add_settings_field( + 'ai_model', + __( 'Generation Model', 'peptide-search-ai' ), + array( __CLASS__, 'render_model_field' ), + 'peptide-search-ai', + 'psa_ai_section' + ); + add_settings_field( + 'validation_model', + __( 'Validation Model', 'peptide-search-ai' ), + array( __CLASS__, 'render_validation_model_field' ), + 'peptide-search-ai', + 'psa_ai_section' + ); + + // Behavior Section. + add_settings_section( + 'psa_behavior_section', + __( 'Behavior Settings', 'peptide-search-ai' ), + null, + 'peptide-search-ai' + ); + add_settings_field( + 'auto_publish', + __( 'Auto-Publish', 'peptide-search-ai' ), + array( __CLASS__, 'render_publish_field' ), + 'peptide-search-ai', + 'psa_behavior_section' + ); + add_settings_field( + 'use_pubchem', + __( 'PubChem Enrichment', 'peptide-search-ai' ), + array( __CLASS__, 'render_pubchem_field' ), + 'peptide-search-ai', + 'psa_behavior_section' + ); + } + + /** + * Sanitize settings input. + * + * @param array $input Raw input from the form. + * @return array Sanitized settings. + */ + public static function sanitize_settings( $input ) { + // Handle API key: encrypt new values, preserve existing on empty/mask. + $api_key_input = $input['api_key'] ?? ''; + $api_key_value = ''; + + if ( ! empty( $api_key_input ) && '••••••••' !== $api_key_input ) { + // New key provided: encrypt it. + $sanitized = sanitize_text_field( $api_key_input ); + $encrypted = PSA_Encryption::encrypt( $sanitized ); + $api_key_value = ( false !== $encrypted ) ? $encrypted : ''; + } else { + // Empty or mask string: preserve existing value. + $existing = self::get_setting( 'api_key', '' ); + $api_key_value = $existing; + } + + return array( + 'api_key' => $api_key_value, + 'ai_model' => sanitize_text_field( $input['ai_model'] ?? '' ), + 'validation_model' => sanitize_text_field( $input['validation_model'] ?? '' ), + 'auto_publish' => sanitize_text_field( $input['auto_publish'] ?? 'draft' ), + // Checkbox: if key is absent in POST, it was unchecked → '0'. + 'use_pubchem' => ! empty( $input['use_pubchem'] ) ? '1' : '0', + ); + } + + // ------------------------------------------------------------------------- + // Field renderers + // ------------------------------------------------------------------------- + + public static function render_section_description() { + ?> +

+ OpenRouter to access AI models. OpenRouter provides a unified API for hundreds of models including open-source options like Gemini Flash, Llama, Mistral, Qwen, and DeepSeek, as well as commercial models.', 'peptide-search-ai' ), + esc_url( 'https://openrouter.ai/' ) + ); + ?> +

+ + + +

+ + +

+ + openrouter.ai/settings/keys.
+ define( 'PSA_OPENROUTER_KEY', 'your-key-here' ); +

+ + +

+ google/gemini-2.5-flash.
+ openrouter.ai/models. + meta-llama/llama-4-maverick, deepseek/deepseek-chat-v3-0324, qwen/qwen-2.5-72b-instruct. +

+ + +

+ google/gemini-2.0-flash-001.
+ meta-llama/llama-4-scout, mistralai/mistral-small-3.1-24b-instruct. +

+ + +

+ + +

+ +
+

+ +
+ +
+ +
+

+
    +
  1. +
  2. +
  3. +
  4. +
  5. +
+ +
+

+

[peptide_search]

+

[peptide_search placeholder="Search peptides..."]

+ +
+

+

GET /wp-json/peptides/v1/search?q=BPC-157

+

+
+ false, + 'canonical_name' => $name, + 'reason' => 'Invalid characters in peptide name.', + ); + } + + $options = self::get_settings(); + $api_key = $options['api_key']; + $model = $options['validation_model']; + + if ( empty( $api_key ) ) { + return new WP_Error( 'no_api_key', 'OpenRouter API key is not configured.' ); + } + + // Check transient cache first (avoid repeated API calls for same term). + $cache_key = 'psa_validate_' . md5( strtolower( trim( $name ) ) ); + $cached = get_transient( $cache_key ); + if ( false !== $cached ) { + return $cached; + } + + $prompt = self::build_validation_prompt( $name ); + // Allow filtering of validation prompt before sending. + $prompt = apply_filters( 'psa_validation_prompt', $prompt, $name ); + $response = self::call_openrouter( + $api_key, + $model ? $model : 'google/gemini-2.0-flash-001', + $prompt, + PSA_Config::VALIDATION_MAX_TOKENS + ); + + if ( is_wp_error( $response ) ) { + return $response; + } + + $data = self::parse_ai_response( $response ); + if ( is_wp_error( $data ) ) { + return array( + 'is_valid' => false, + 'canonical_name' => $name, + 'reason' => 'Could not verify this peptide name.', + ); + } + + $result = array( + 'is_valid' => ! empty( $data['is_valid'] ) && true === $data['is_valid'], + 'canonical_name' => sanitize_text_field( $data['canonical_name'] ?? $name ), + 'reason' => sanitize_text_field( $data['reason'] ?? '' ), + ); + + // Cache for 24 hours (using PSA_Config for consistency). + set_transient( $cache_key, $result, DAY_IN_SECONDS ); // Validation cache TTL + + return $result; + } + + /** + * Background generation handler (called via WP-Cron or synchronously). + * + * @param int $post_id The placeholder post ID. + * @param string $peptide_name The peptide to research. + */ + public static function background_generate( $post_id, $peptide_name ) { + $post = get_post( $post_id ); + if ( ! $post || 'draft' !== $post->post_status || 'peptide' !== $post->post_type ) { + error_log( 'PSA: background_generate skipped — post ' . $post_id . ' not a draft peptide.' ); + return; + } + + // Only process posts that are still in 'pending' state. + $source = get_post_meta( $post_id, 'psa_source', true ); + if ( 'pending' !== $source ) { + error_log( 'PSA: background_generate skipped — post ' . $post_id . ' source is "' . $source . '", not "pending".' ); + return; + } + + $options = self::get_settings(); + $auto_publish = $options['auto_publish']; + + error_log( 'PSA: Generating content for "' . $peptide_name . '" (post ' . $post_id . ') using model: ' . ( $options['ai_model'] ? $options['ai_model'] : 'google/gemini-2.5-flash' ) ); + + // Allow developers to hook before generation starts. + do_action( 'psa_before_generation', $post_id, $peptide_name ); + + // Generate the full content. + $result = self::generate_peptide_content( $peptide_name ); + if ( is_wp_error( $result ) ) { + $err_msg = $result->get_error_message(); + error_log( 'PSA: Generation FAILED for "' . $peptide_name . '": ' . $err_msg ); + update_post_meta( $post_id, 'psa_generation_error', $err_msg ); + return; + } + + error_log( 'PSA: AI content generated successfully for "' . $peptide_name . '". Fields: ' . implode( ', ', array_keys( $result ) ) ); + + // FIX: Use 'overview' field (which the prompt returns) with fallback to 'description'. + $post_content = $result['overview'] ?? $result['description'] ?? ''; + + // Safeguard: if post_content is still empty after generation, log a warning. + if ( empty( trim( $post_content ) ) ) { + error_log( 'PSA: WARNING — AI returned valid JSON but post content (overview/description) is empty for "' . $peptide_name . '". Available keys: ' . implode( ', ', array_keys( $result ) ) ); + update_post_meta( $post_id, 'psa_generation_error', 'AI returned empty overview/description content. Available fields: ' . implode( ', ', array_keys( $result ) ) ); + return; + } + + // Try PubChem enrichment. + $pubchem_data = null; + if ( ! empty( $options['use_pubchem'] ) ) { + $pubchem_result = PSA_PubChem::lookup( $peptide_name ); + if ( is_wp_error( $pubchem_result ) ) { + // Log PubChem API failures. + error_log( 'PSA: PubChem lookup failed for "' . $peptide_name . '": ' . $pubchem_result->get_error_message() ); + } elseif ( is_array( $pubchem_result ) ) { + $pubchem_data = $pubchem_result; + error_log( 'PSA: PubChem data found for "' . $peptide_name . '" (CID: ' . ( $pubchem_data['cid'] ?? 'unknown' ) . ')' ); + } + } + + // Update the placeholder with real content. + $post_status = ( 'publish' === $auto_publish ) ? 'publish' : 'draft'; + + $update_result = wp_update_post( + array( + 'ID' => $post_id, + 'post_title' => sanitize_text_field( $result['name'] ?? $peptide_name ), + 'post_content' => wp_kses_post( $post_content ), + 'post_status' => $post_status, + ), + true + ); + + if ( is_wp_error( $update_result ) ) { + error_log( 'PSA: wp_update_post FAILED for post ' . $post_id . ': ' . $update_result->get_error_message() ); + update_post_meta( $post_id, 'psa_generation_error', 'Failed to update post: ' . $update_result->get_error_message() ); + return; + } + + // Save all meta fields — prefer PubChem data for molecular properties. + self::save_peptide_meta( $post_id, $result, $pubchem_data ); + + // Create a matching Knowledge Base article. + self::create_kb_article( $post_id, $result, $peptide_name, $post_status ); + + // Clean up generation tracking. + delete_post_meta( $post_id, 'psa_generation_started' ); + delete_post_meta( $post_id, 'psa_generation_error' ); + update_post_meta( $post_id, 'psa_generation_completed', time() ); + + // Allow developers to hook after generation completes. + do_action( 'psa_after_generation', $post_id, $result, $peptide_name ); + + error_log( 'PSA: Successfully completed generation for "' . $peptide_name . '" (post ' . $post_id . ', status: ' . $post_status . ')' ); + } + + /** + * Generate full peptide content via AI. + * + * @param string $peptide_name The peptide to research. + * @return array|WP_Error Parsed peptide data or error. + */ + public static function generate_peptide_content( $peptide_name ) { + $options = self::get_settings(); + $api_key = $options['api_key']; + $model = $options['ai_model']; + + if ( empty( $api_key ) ) { + return new WP_Error( 'no_api_key', 'OpenRouter API key is not configured.' ); + } + + $prompt = self::build_generation_prompt( $peptide_name ); + // Allow filtering of generation prompt before sending. + $prompt = apply_filters( 'psa_generation_prompt', $prompt, $peptide_name ); + $response = self::call_openrouter( + $api_key, + $model ? $model : 'google/gemini-2.5-flash', + $prompt, + PSA_Config::GENERATION_MAX_TOKENS + ); + + if ( is_wp_error( $response ) ) { + return $response; + } + + return self::parse_ai_response( $response ); + } + + // ------------------------------------------------------------------------- + // Private helpers + // ------------------------------------------------------------------------- + + /** + * Get plugin settings with defaults. + * + * @return array + */ + private static function get_settings() { + $defaults = array( + 'api_key' => '', + 'ai_model' => '', + 'validation_model' => '', + 'auto_publish' => 'draft', + 'use_pubchem' => '1', + ); + + $settings = wp_parse_args( get_option( 'psa_settings', array() ), $defaults ); + + // Decrypt API key if it's encrypted and constant is not defined. + if ( ! empty( $settings['api_key'] ) && ! ( defined( 'PSA_OPENROUTER_KEY' ) && PSA_OPENROUTER_KEY ) ) { + $decrypted = PSA_Encryption::decrypt( $settings['api_key'] ); + if ( false !== $decrypted ) { + $settings['api_key'] = $decrypted; + } + // If decrypt fails, the key might be stored in plaintext (pre-encryption migration). + // Leave it as-is for backward compatibility — it will be encrypted on next save. + } + + // Prefer wp-config.php constant over database value for security. + if ( defined( 'PSA_OPENROUTER_KEY' ) && PSA_OPENROUTER_KEY ) { + $settings['api_key'] = PSA_OPENROUTER_KEY; + } + + // Allow filtering of settings before use. + $settings = apply_filters( 'psa_ai_settings', $settings ); + + return $settings; + } + + /** + * Save meta fields for a peptide post. + * + * @param int $post_id The post ID. + * @param array $ai_data AI-generated data. + * @param array|null $pubchem_data PubChem data (or null). + */ + private static function save_peptide_meta( $post_id, $ai_data, $pubchem_data ) { + $meta = array( + 'psa_sequence' => $ai_data['sequence'] ?? '', + 'psa_molecular_weight' => ! empty( $pubchem_data['molecular_weight'] ) + ? $pubchem_data['molecular_weight'] + : ( $ai_data['molecular_weight'] ?? '' ), + 'psa_molecular_formula' => ! empty( $pubchem_data['molecular_formula'] ) + ? $pubchem_data['molecular_formula'] + : ( $ai_data['molecular_formula'] ?? '' ), + 'psa_aliases' => $ai_data['aliases'] ?? '', + 'psa_mechanism' => $ai_data['mechanism'] ?? '', + 'psa_overview' => $ai_data['overview'] ?? $ai_data['description'] ?? '', + 'psa_category_label' => $ai_data['category_label'] ?? '', + 'psa_origin' => $ai_data['origin'] ?? '', + 'psa_research_apps' => $ai_data['research_benefits'] ?? ( $ai_data['research_applications'] ?? '' ), + 'psa_safety_profile' => $ai_data['safety_side_effects'] ?? ( $ai_data['safety_profile'] ?? '' ), + 'psa_dosage_info' => $ai_data['administration_dosing'] ?? ( $ai_data['dosage_info'] ?? '' ), + 'psa_legal_regulatory' => $ai_data['legal_regulatory'] ?? '', + 'psa_references' => $ai_data['references'] ?? '', + 'psa_category' => $ai_data['category'] ?? '', + 'psa_source' => ! empty( $pubchem_data ) ? 'pubchem' : 'ai-generated', + 'psa_pubchem_cid' => $pubchem_data['cid'] ?? '', + ); + + // Allow filtering of meta before save. + $meta = apply_filters( 'psa_peptide_meta', $meta, $post_id, $ai_data, $pubchem_data ); + + foreach ( $meta as $key => $value ) { + update_post_meta( $post_id, $key, $value ); + } + } + + /** + * Validate peptide name input characters and block injection patterns. + * + * @param string $name The peptide name to validate. + * @return bool True if input looks legitimate. + */ + private static function validate_peptide_input( $name ) { + // Allow only characters that appear in legitimate peptide names. + if ( ! preg_match( '/^[\p{L}\d\s\-\(\),\.\/\+\[\]]+$/u', $name ) ) { + return false; + } + // Block obvious prompt injection patterns. + $blocked = array( 'ignore', 'instruction', 'override', 'system prompt', 'forget', 'disregard', 'pretend' ); + $lower = strtolower( $name ); + foreach ( $blocked as $word ) { + if ( strpos( $lower, $word ) !== false ) { + return false; + } + } + return true; + } + + /** + * Build the lightweight validation prompt. + * + * Uses wp_json_encode() to safely encode the peptide name within the prompt. + * This ensures special characters and quotes are properly escaped before sending to the AI. + * The JSON-encoded format also helps the AI parser recognize the input clearly. + * + * @param string $name The peptide name to validate. + * @return string Prompt text ready to send to OpenRouter API. + */ + private static function build_validation_prompt( $name ) { + $json_name = wp_json_encode( $name ); + return <<get_error_code() ) { + return $result; + } + + // Rate limited — retry with exponential backoff. + if ( $attempt < $max_retries ) { + $delay = $base_delay * pow( 2, $attempt - 1 ); // 5s, 10s, 20s + // Avoid blocking PHP workers during WP-Cron execution. + if ( defined( 'DOING_CRON' ) && DOING_CRON ) { + error_log( 'PSA: Rate limited during cron on attempt ' . $attempt . '/' . $max_retries . '. Returning to free PHP worker.' ); + return new WP_Error( 'rate_limited', 'Rate limited during background generation. Will retry on next cron trigger.' ); + } + error_log( 'PSA: Rate limited on attempt ' . $attempt . '/' . $max_retries . '. Retrying in ' . $delay . 's...' ); + sleep( $delay ); + } + } + + error_log( 'PSA: All ' . $max_retries . ' attempts failed due to rate limiting.' ); + return new WP_Error( 'rate_limited', 'OpenRouter rate limit reached after ' . $max_retries . ' retries. Consider adding credits at openrouter.ai or switching to a non-free model.' ); + } + + /** + * Single OpenRouter API call (no retry). + * + * @param string $api_key The OpenRouter API key. + * @param string $model The model identifier. + * @param string $prompt The prompt text. + * @param int $max_tokens Maximum tokens to generate. + * @return string|WP_Error Response text or error. + */ + private static function call_openrouter_once( $api_key, $model, $prompt, $max_tokens = 4096 ) { + $site_url = get_bloginfo( 'url' ); + $site_name = get_bloginfo( 'name' ); + + $response = wp_remote_post( + self::API_URL, + array( + 'timeout' => 120, + 'headers' => array( + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . $api_key, + 'HTTP-Referer' => $site_url, + 'X-Title' => $site_name, + ), + 'body' => wp_json_encode( + array( + 'model' => $model, + 'messages' => array( + array( + 'role' => 'system', + 'content' => 'You are a scientific database assistant. Return only valid JSON.', + ), + array( + 'role' => 'user', + 'content' => $prompt, + ), + ), + 'max_tokens' => $max_tokens, + 'temperature' => 0.3, + ) + ), + ) + ); + + if ( is_wp_error( $response ) ) { + error_log( 'PSA: OpenRouter connection error: ' . $response->get_error_message() ); + return new WP_Error( 'api_error', 'Failed to connect to OpenRouter API: ' . $response->get_error_message() ); + } + + $code = wp_remote_retrieve_response_code( $response ); + $raw_body = wp_remote_retrieve_body( $response ); + $body = json_decode( $raw_body, true ); + + error_log( 'PSA: OpenRouter response code: ' . $code . ' for model: ' . $model ); + + if ( 200 !== $code ) { + if ( 429 === $code ) { + error_log( 'PSA: OpenRouter rate limited (429)' ); + return new WP_Error( 'rate_limited', 'OpenRouter rate limit reached. Please try again in a few moments.' ); + } + if ( 402 === $code ) { + error_log( 'PSA: OpenRouter insufficient credits (402)' ); + return new WP_Error( 'insufficient_credits', 'OpenRouter account has insufficient credits. Please add funds at openrouter.ai.' ); + } + $msg = $body['error']['message'] ?? ( 'Unknown error (HTTP ' . $code . ')' ); + error_log( 'PSA: OpenRouter API error (' . $code . '): ' . $msg ); + error_log( 'PSA: OpenRouter raw response: ' . substr( $raw_body, 0, 500 ) ); + return new WP_Error( 'api_error', 'OpenRouter API error: ' . $msg ); + } + + if ( empty( $body['choices'][0]['message']['content'] ) ) { + error_log( 'PSA: OpenRouter returned empty content. Raw: ' . substr( $raw_body, 0, 500 ) ); + return new WP_Error( 'api_error', 'OpenRouter API returned an empty response.' ); + } + + return $body['choices'][0]['message']['content']; + } + + /** + * Parse AI response text into structured data. + * + * @param string $response_text Raw response text. + * @return array|WP_Error Parsed data or error. + */ + private static function parse_ai_response( $response_text ) { + // Strip any ... tags (some models like DeepSeek include reasoning). + $cleaned = preg_replace( '/.*?<\/think>/s', '', $response_text ); + + // Strip markdown code fences if present. + $cleaned = preg_replace( '/^```(?:json)?\s*/m', '', $cleaned ); + $cleaned = preg_replace( '/\s*```\s*$/m', '', $cleaned ); + $cleaned = trim( $cleaned ); + + $data = json_decode( $cleaned, true ); + if ( JSON_ERROR_NONE !== json_last_error() ) { + error_log( 'PSA: JSON parse error: ' . json_last_error_msg() . '. Raw (first 500 chars): ' . substr( $response_text, 0, 500 ) ); + return new WP_Error( + 'parse_error', + 'Failed to parse AI response as JSON: ' . json_last_error_msg() + ); + } + + return $data; + } + + /** + * Create a matching Echo Knowledge Base article with full structured content. + * + * @param int $peptide_post_id The peptide post ID. + * @param array $ai_data The parsed AI data. + * @param string $peptide_name The peptide name. + * @param string $post_status The post status (default: 'draft'). + */ + private static function create_kb_article( $peptide_post_id, $ai_data, $peptide_name, $post_status = 'draft' ) { + if ( ! post_type_exists( 'epkb_post_type_1' ) ) { + error_log( 'PSA: Echo Knowledge Base not active — skipping KB article.' ); + return; + } + + $title = sanitize_text_field( $ai_data['name'] ?? $peptide_name ); + $existing = get_posts( + array( + 'post_type' => 'epkb_post_type_1', + 'title' => $title, + 'post_status' => 'any', + 'numberposts' => 1, + ) + ); + + if ( ! empty( $existing ) ) { + error_log( 'PSA: KB article already exists for "' . $peptide_name . '".' ); + return; + } + + // Build header meta line. + $cat_label = ! empty( $ai_data['category_label'] ) ? $ai_data['category_label'] : ''; + $origin = ! empty( $ai_data['origin'] ) ? $ai_data['origin'] : ''; + $sequence = ! empty( $ai_data['sequence'] ) ? $ai_data['sequence'] : ''; + + $header = ''; + if ( $cat_label ) { + $header .= 'Category: ' . esc_html( $cat_label ); + } + if ( $origin ) { + $header .= ' | Origin: ' . esc_html( $origin ); + } + if ( $sequence ) { + $header .= ' | Sequence: ' . esc_html( $sequence ); + } + + // Build full article content. + $c = $header ? '

' . $header . '

' . "\n\n" : ''; + + // Overview. + $c .= '

Overview

' . "\n"; + $c .= self::paragraphs( $ai_data['overview'] ?? $ai_data['description'] ?? '' ); + + // Mechanism of Action. + if ( ! empty( $ai_data['mechanism'] ) ) { + $c .= '

Mechanism of Action

' . "\n"; + $c .= self::paragraphs( $ai_data['mechanism'] ); + } + + // Research & Potential Benefits (with h3 subheadings). + if ( ! empty( $ai_data['research_benefits'] ) || ! empty( $ai_data['research_applications'] ) ) { + $c .= '

Research & Potential Benefits

' . "\n"; + $c .= '

The following potential benefits are based on animal studies and preclinical research. Human clinical trial data is extremely limited.

' . "\n"; + $research = $ai_data['research_benefits'] ?? $ai_data['research_applications'] ?? ''; + $c .= self::research_with_subheadings( $research ); + } + + // Administration & Dosing. + if ( ! empty( $ai_data['administration_dosing'] ) || ! empty( $ai_data['dosage_info'] ) ) { + $c .= '

Administration & Dosing (Research Context)

' . "\n"; + $c .= '

Important: The following dosing information is derived from animal studies and extrapolated research. This peptide is not approved for human use. This information is provided for educational purposes only.

' . "\n"; + $c .= self::paragraphs( $ai_data['administration_dosing'] ?? $ai_data['dosage_info'] ?? '' ); + } + + // Safety & Side Effects. + if ( ! empty( $ai_data['safety_side_effects'] ) || ! empty( $ai_data['safety_profile'] ) ) { + $c .= '

Safety & Side Effects

' . "\n"; + $c .= self::paragraphs( $ai_data['safety_side_effects'] ?? $ai_data['safety_profile'] ?? '' ); + } + + // Legal & Regulatory Status. + if ( ! empty( $ai_data['legal_regulatory'] ) ) { + $c .= '

Legal & Regulatory Status

' . "\n"; + $c .= self::paragraphs( $ai_data['legal_regulatory'] ); + } + + // References. + if ( ! empty( $ai_data['references'] ) ) { + $c .= '

Notable Research References

' . "\n"; + $c .= self::paragraphs( $ai_data['references'] ); + } + + // Medical Disclaimer. + $c .= "\n" . '

Medical Disclaimer: The information on this page is provided for educational and research purposes only. This peptide is not approved for human therapeutic use. Nothing on this page constitutes medical advice. Always consult a licensed healthcare professional before using any peptide, supplement, or research chemical.

'; + + $kb_post_id = wp_insert_post( + array( + 'post_title' => $title, + 'post_content' => wp_kses_post( $c ), + 'post_type' => 'epkb_post_type_1', + 'post_status' => $post_status, + ), + true + ); + + if ( is_wp_error( $kb_post_id ) ) { + error_log( 'PSA: Failed to create KB article: ' . $kb_post_id->get_error_message() ); + return; + } + + // Assign KB category. + $category_map = array( + 'GH Secretagogues' => 'gh-secretagogues', + 'Healing & Repair' => 'healing-repair', + 'Melanocortin Peptides' => 'melanocortin-peptides', + 'Metabolic & Anti-Aging' => 'metabolic-anti-aging', + 'Nootropic & Neuroprotective' => 'nootropic-neuroprotective', + ); + + $cat_name = trim( $ai_data['category'] ?? '' ); + if ( isset( $category_map[ $cat_name ] ) ) { + $term = get_term_by( 'slug', $category_map[ $cat_name ], 'epkb_post_type_1_category' ); + if ( $term ) { + wp_set_object_terms( $kb_post_id, array( (int) $term->term_id ), 'epkb_post_type_1_category' ); + } + } + + update_post_meta( $peptide_post_id, 'psa_kb_article_id', $kb_post_id ); + update_post_meta( $kb_post_id, 'psa_peptide_post_id', $peptide_post_id ); + + error_log( 'PSA: Created KB article #' . $kb_post_id . ' for "' . $peptide_name . '"' ); + } + + /** + * Convert text to HTML paragraphs. + */ + private static function paragraphs( $text ) { + if ( empty( $text ) ) { + return ''; + } + $text = str_replace( "\r\n", "\n", $text ); + $parts = preg_split( '/\n{2,}/', trim( $text ) ); + $out = ''; + foreach ( $parts as $p ) { + $p = trim( $p ); + if ( '' === $p ) { + continue; + } + $out .= '

' . wp_kses_post( $p ) . '

' . "\n"; + } + return $out; + } + + /** + * Parse research text into h3 subheadings + paragraphs. + */ + private static function research_with_subheadings( $text ) { + if ( empty( $text ) ) { + return ''; + } + $text = str_replace( "\r\n", "\n", trim( $text ) ); + $blocks = preg_split( '/\n{2,}/', $text ); + $out = ''; + foreach ( $blocks as $block ) { + $block = trim( $block ); + if ( '' === $block ) { + continue; + } + // If block is short (under 80 chars) and has no period, treat as a subheading. + if ( strlen( $block ) < 80 && strpos( $block, '.' ) === false ) { + $out .= '

' . esc_html( $block ) . '

' . "\n"; + } else { + // Check if first line is a subheading followed by content. + $first_nl = strpos( $block, "\n" ); + if ( false !== $first_nl ) { + $first_line = trim( substr( $block, 0, $first_nl ) ); + $rest = trim( substr( $block, $first_nl + 1 ) ); + if ( strlen( $first_line ) < 80 && strpos( $first_line, '.' ) === false ) { + $out .= '

' . esc_html( $first_line ) . '

' . "\n"; + $out .= '

' . wp_kses_post( $rest ) . '

' . "\n"; + continue; + } + } + $out .= '

' . wp_kses_post( $block ) . '

' . "\n"; + } + } + return $out; + } +} diff --git a/includes/class-psa-encryption.php b/includes/class-psa-encryption.php new file mode 100755 index 0000000..8594203 --- /dev/null +++ b/includes/class-psa-encryption.php @@ -0,0 +1,129 @@ +post_content, 'peptide_search' ) && ! is_singular( 'peptide' ) ) { + return; + } + + psa_enqueue_frontend_assets(); +} +add_action( 'wp_enqueue_scripts', 'psa_maybe_enqueue_assets' ); + +/** + * Shared helper to enqueue CSS, JS, and localize script. + */ +function psa_enqueue_frontend_assets() { + wp_enqueue_style( + 'psa-styles', + PSA_PLUGIN_URL . 'assets/css/peptide-search.css', + array(), + PSA_VERSION + ); + + wp_enqueue_script( + 'psa-search', + PSA_PLUGIN_URL . 'assets/js/peptide-search.js', + array( 'jquery' ), + PSA_VERSION, + true + ); + + wp_localize_script( + 'psa-search', + 'psaAjax', + array( + 'ajaxurl' => admin_url( 'admin-ajax.php' ), + 'nonce' => wp_create_nonce( 'psa_search_nonce' ), + ) + ); +} + +/** + * On the KB page, hide Echo KB search and inject ours via wp_footer. + */ +function psa_replace_kb_search() { + if ( ! psa_is_kb_page() ) { + return; + } + + $search_html = PSA_Search::render_search_form( + array( + 'placeholder' => 'Search for a peptide (e.g., BPC-157, Thymosin Beta-4)...', + ) + ); + $encoded = wp_json_encode( $search_html ); + + echo ''; + + echo ''; +} +add_action( 'wp_footer', 'psa_replace_kb_search' ); + +function psa_activate() { + PSA_Post_Type::register_peptide_post_type(); + flush_rewrite_rules(); +} +register_activation_hook( __FILE__, 'psa_activate' ); + +function psa_deactivate() { + flush_rewrite_rules(); +} +register_deactivation_hook( __FILE__, 'psa_deactivate' ); + +function psa_get_client_ip() { + $headers = array( + 'HTTP_CF_CONNECTING_IP', + 'REMOTE_ADDR', + ); + foreach ( $headers as $header ) { + if ( ! empty( $_SERVER[ $header ] ) ) { + $ip = explode( ',', sanitize_text_field( wp_unslash( $_SERVER[ $header ] ) ) ); + $ip = trim( $ip[0] ); + if ( filter_var( $ip, FILTER_VALIDATE_IP ) ) { + return $ip; + } + } + } + return '0.0.0.0'; +} + +function psa_get_admin_user_id() { + $admins = get_users( + array( + 'role' => 'administrator', + 'number' => 1, + 'fields' => 'ID', + ) + ); + return ! empty( $admins ) ? (int) $admins[0] : 0; +}