prefix . 'ai_app_onsite_prompt_editor'; $table_name_model_settings = $wpdb->prefix . 'ai_app_onsite_model_settings'; $table_name_plugin_settings = $wpdb->prefix . 'ai_app_onsite_plugin_settings'; $table_name_field_selector = $wpdb->prefix . 'ai_app_onsite_field_selector_settings'; $model_settings = $wpdb->get_results("SELECT * FROM $table_name_model_settings", ARRAY_A); $plugin_settings = $wpdb->get_results("SELECT * FROM $table_name_plugin_settings", ARRAY_A); $formData = $_POST; $field_names = array_keys($formData); $field_values = array_values($formData); $pairs = array_combine($field_names, $field_values); $banned_words = unserialize($plugin_settings[0]['banned_words']); $app_email = $plugin_settings[0]['app_email']; function containsBannedWordPart($value, $banned_word) { // Split banned word into parts by space $banned_parts = explode(' ', $banned_word); foreach ($banned_parts as $part) { // Use preg_match to find exact words if (preg_match('/\b' . preg_quote($part, '/') . '\b/i', $value)) { return true; } } return false; } // Iterate through field values and check against banned words foreach ($field_values as $value) { foreach ($banned_words as $banned_word) { if (containsBannedWordPart($value, $banned_word)) { wp_send_json_error("Banned word included in: " . $value); break; } } } $field_selector_settings = $wpdb->get_results("SELECT `field_label` FROM $table_name_field_selector", ARRAY_A); $fieldLabels = array_column($field_selector_settings, 'field_label'); // Process each element of the array $fieldLabels = array_map(function ($item) { // Replace spaces with underscores in each item return preg_replace('/\s+/', '_', $item); }, $fieldLabels); if (isset($app_email) && !empty($app_email)) { $resultArray = []; // Create a new array with matching values from the second array $resultArray = array_filter( $pairs, function ($key) use ($fieldLabels) { return in_array($key, $fieldLabels); }, ARRAY_FILTER_USE_KEY ); /*Email Template Start*/ // Basic email template with placeholders $email_template = " AIappOnsite

AIappOnsite App Input Data

Here is the user input data:

Thanks for using AIappOnsite!

Let us know if you have any questions or requests.

"; // Create the dynamic list $dynamic_list = ''; foreach ($resultArray as $key => $value) { $dynamic_list .= "
  • " . ucfirst($key) . ": " . htmlspecialchars($value) . "
  • "; } // Replace the placeholder with the dynamically generated list $email_template = str_replace('{dynamic_list}', $dynamic_list, $email_template); // The dynamic email content is now ready in $email_template $to = $app_email; $subject = "AIappOnsite App Usage"; // Headers to ensure the email is sent as HTML $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // Send the email $email = mail($to, $subject, $email_template, $headers); } if (empty($model_settings)) { wp_send_json_error('Plugin Model settings are missing'); } $model_setting = $model_settings[0]; $openai_key = $model_setting['openai_key']; $key_status = $model_setting['key_status']; $model = $model_setting['model']; $temperature = $model_setting['temperature'] ?: ''; $f_penalty = $model_setting['f_penalty'] ?: ''; $p_penalty = $model_setting['p_penalty'] ?: ''; $max_tokens = $model_setting['max_tokens'] ?: ''; $top_p = $model_setting['top_p'] ?: ''; // Check for missing keys if (empty($openai_key)) { wp_send_json_error('OpenAI API key is missing'); } if (empty($model)) { wp_send_json_error('OpenAI API Model is missing'); } if ($key_status === 'false') { wp_send_json_error('OpenAI API key is disable'); } $formatted_field_names = array_map(function ($key) { return '{{' . strtolower($key) . '}}'; }, $field_names); $replace_array = array_combine($formatted_field_names, $field_values); $prompt_results = $wpdb->get_results("SELECT * FROM $table_name_prompt_editor", ARRAY_A); if (empty($prompt_results)) { wp_send_json_error('No prompt results found'); } $prompt_result = $prompt_results[0]; if (!isset($prompt_result['prompt']) || empty($prompt_result['prompt'])) { wp_send_json_error('Prompt string is empty'); } $prompt = str_replace(array_keys($replace_array), array_values($replace_array), $prompt_result['prompt']); // Check for empty prompt if (empty($prompt)) { wp_send_json_error('Prompt is missing'); } $OPENAI_API_KEY = $openai_key; $api_url = "https://api.openai.com/v1/chat/completions"; $headers = [ "Content-Type" => "application/json", "Authorization" => "Bearer $OPENAI_API_KEY" ]; $data = [ "model" => $model, "messages" => [ [ "role" => "system", "content" => "You are a detailed and organized assistant. When responding to user queries, begin with an introductory paragraph that summarizes the topic clearly. Follow this with a bullet-point list of key concepts. Finally, present a numbered list where each point is formatted as follows: '1. [Item 1]', '2. [Item 2]', ensuring that each item is concise and well-explained." ], [ "role" => "user", "content" => $prompt, ] ], "temperature" => (int)$temperature, "max_tokens" => (int)$max_tokens, "top_p" => (int)$top_p, "frequency_penalty" => (float)$f_penalty, "presence_penalty" => (float)$p_penalty ]; $response = wp_remote_post($api_url, [ 'headers' => $headers, 'body' => wp_json_encode($data), 'timeout' => 45, // Timeout after 15 seconds 'data_format' => 'body', // Ensure the body format is used ]); $response_code = wp_remote_retrieve_response_code($response); $result = json_decode(wp_remote_retrieve_body($response), true); if (isset($result['choices'][0]['message']['content'])) { // Extract the content from the API response $response_content = htmlspecialchars($result["choices"][0]["message"]["content"]); if (strpos($response_content, 'Hello!') !== false) { $response_content = str_replace('Hello!', 'Hello!

    ', $response_content); } // Convert **text** to bold using preg_replace $response_content = preg_replace('/\*\*(.*?)\*\*/', '$1', $response_content); $response_content = preg_replace('/####\s*(.*)/', '

    $1

    ', $response_content); // Use nl2br to retain new line breaks $response_content = nl2br($response_content); } else { wp_send_json_error('Invalid response from OpenAI'); } $user_stats_handler = new AI_APP_ONSITE_User_Stats_Handler(); $response_Id = $user_stats_handler->ai_app_onsite_save_user_stats($result, $prompt, $formData); // Optionally handle response from external URL $response = [ 'success' => true, 'message' => 'Form data received successfully', 'data' => $response_content, 'response_id' => $response_Id, ]; wp_send_json($response); } } new AI_APP_ONSITE_OpenAi_Api_Handler(); // Instantiate the class } function AI_APP_ONSITE_Break_Paragraph($text, $words_per_chunk = 200) { // Split the text into an array of words $words = preg_split('/\s+/', $text); $chunks = array_chunk($words, $words_per_chunk); $result = ''; foreach ($chunks as $chunk) { $result .= implode(' ', $chunk) . "\n\n"; } return $result; }