PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 2.6.0
MxChat – AI Chatbot & Content Generation for WordPress v2.6.0
3.2.22 3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 All 153 releases
← All changes | includes/class-mxchat-integrator.php +8554 -3454 2.0.52.6.0 View file →
@@ -1,3454 +1,8554 @@
1 -<?php
2 -if (!defined('ABSPATH')) {
3 - exit;
4 -}
5 -
6 -class MxChat_Integrator {
7 - private $options;
8 - private $prompts_options;
9 - private $chat_count;
10 - private $fallbackResponse;
11 - private $productCardHtml;
12 - private $word_handler;
13 -
14 -public function __construct() {
15 - $this->options = get_option('mxchat_options');
16 - $this->prompts_options = get_option('mxchat_prompts_options', array());
17 -
18 - $this->chat_count = get_option('mxchat_chat_count', 0);
19 - $this->word_handler = new MXChat_Word_Handler($this->options);
20 -
21 - add_action('wp_enqueue_scripts', array($this, 'mxchat_enqueue_scripts_styles'));
22 - add_action('wp_ajax_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
23 - add_action('wp_ajax_nopriv_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
24 -
25 - add_action('wp_ajax_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
26 - add_action('wp_ajax_nopriv_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
27 - // Add the AJAX actions for checking if the pre-chat message was dismissed
28 - add_action('wp_ajax_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
29 - add_action('wp_ajax_nopriv_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
30 -
31 - add_action('wp_ajax_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
32 - add_action('wp_ajax_nopriv_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
33 -
34 - add_action('wp_ajax_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
35 - add_action('wp_ajax_nopriv_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
36 -
37 - if (!wp_next_scheduled('mxchat_reset_rate_limits')) {
38 - wp_schedule_event(time(), 'daily', 'mxchat_reset_rate_limits');
39 - }
40 -
41 - // Add REST API routes registration
42 - add_action('rest_api_init', array($this, 'register_routes'));
43 -
44 - add_action('wp_ajax_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
45 - add_action('wp_ajax_nopriv_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
46 -
47 - add_action('mxchat_reset_rate_limits', array($this, 'mxchat_reset_rate_limits'));
48 -
49 - add_action('wp_ajax_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
50 - add_action('wp_ajax_nopriv_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
51 - add_action('wp_ajax_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
52 - add_action('wp_ajax_nopriv_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
53 -
54 - // Add these with your other add_action hooks
55 - add_action('wp_ajax_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
56 - add_action('wp_ajax_nopriv_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
57 - add_action('wp_ajax_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
58 - add_action('wp_ajax_nopriv_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
59 - add_action('wp_ajax_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
60 - add_action('wp_ajax_nopriv_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
61 -
62 - add_action('wp_ajax_nopriv_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
63 - add_action('wp_ajax_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
64 - add_action('wp_ajax_nopriv_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
65 - add_action('wp_ajax_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
66 -}
67 -
68 -
69 - private function mxchat_increment_chat_count() {
70 - $chat_count = get_option('mxchat_chat_count', 0);
71 - $chat_count++;
72 - update_option('mxchat_chat_count', $chat_count);
73 - }
74 -
75 -function mxchat_fetch_conversation_history() {
76 - if (empty($_POST['session_id'])) {
77 - wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
78 - wp_die();
79 - }
80 -
81 - $session_id = sanitize_text_field($_POST['session_id']);
82 - $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history
83 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai'); // Get current chat mode
84 -
85 - if (empty($history)) {
86 - // Even if history is empty, return the chat mode
87 - wp_send_json_success([
88 - 'conversation' => [],
89 - 'chat_mode' => $chat_mode
90 - ]);
91 - wp_die();
92 - }
93 -
94 - wp_send_json_success([
95 - 'conversation' => $history,
96 - 'chat_mode' => $chat_mode
97 - ]);
98 - wp_die();
99 -}
100 -private function mxchat_fetch_conversation_history_for_ajax($session_id) {
101 - $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history based on session ID
102 - $formatted_history = [];
103 -
104 - // Format the history to align with the expected structure for OpenAI
105 - foreach ($history as $entry) {
106 - $formatted_history[] = [
107 - 'role' => $entry['role'], // Ensure this matches 'user' or 'assistant'
108 - 'content' => $entry['content']
109 - ];
110 - }
111 -
112 - return $formatted_history;
113 -}
114 -
115 -
116 -private function mxchat_fetch_conversation_history_for_ai($session_id) {
117 - $history = get_option("mxchat_history_{$session_id}", []);
118 - $formatted_history = [];
119 -
120 - // Adjusted for code-heavy conversations
121 - $max_tokens = 120000; // Context window size
122 - $reserved_tokens = 5000; // Space for system prompts + current query
123 - $current_token_count = 0;
124 -
125 - // Allowed HTML tags for content sanitization
126 - $allowed_tags = [
127 - 'pre' => ['class' => true],
128 - 'code' => ['class' => true],
129 - 'span' => ['class' => true],
130 - 'div' => ['class' => true],
131 - 'strong' => [],
132 - 'em' => []
133 - ];
134 -
135 - foreach (array_reverse($history) as $entry) {
136 - // Preserve code blocks while sanitizing other HTML
137 - $clean_content = wp_kses($entry['content'], $allowed_tags);
138 -
139 - // Detect code blocks in content
140 - $has_code = false;
141 -// Replace the HTML check with:
142 -// Allow messages that contain code blocks or are plain text
143 -if (strpos($clean_content, '<pre') === false &&
144 - strpos($clean_content, '<code') === false &&
145 - $clean_content !== strip_tags($entry['content'])) {
146 - continue;
147 -}
148 -
149 - // Skip entries that lost significant content during sanitization
150 - if (!$has_code && $clean_content !== strip_tags($entry['content'])) {
151 - continue;
152 - }
153 -
154 - // More accurate token estimation (1 token ≈ 4 characters)
155 - $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
156 -
157 - // Check token budget with the new estimate
158 - if (($current_token_count + $token_estimate + $reserved_tokens) > $max_tokens) {
159 - // Try to fit partial content if it's the first entry
160 - if (empty($formatted_history)) {
161 - $clean_content = mb_substr($clean_content, 0, ($max_tokens - $reserved_tokens) * 4);
162 - $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
163 - } else {
164 - break;
165 - }
166 - }
167 -
168 - // Add to formatted history
169 - $formatted_history[] = [
170 - 'role' => $entry['role'],
171 - 'content' => $clean_content
172 - ];
173 -
174 - $current_token_count += $token_estimate;
175 - }
176 -
177 - // Reverse back to maintain chronological order
178 - $formatted_history = array_reverse($formatted_history);
179 -
180 - // Add system message about code context
181 - array_unshift($formatted_history, [
182 - 'role' => 'system',
183 - 'content' => 'Preserved code blocks are marked with [CODE BLOCK PRESERVED]. '
184 - . 'Maintain formatting and syntax highlighting when referencing code.'
185 - ]);
186 -
187 - return $formatted_history;
188 -}
189 -
190 -public function register_routes() {
191 - //error_log(esc_html__('Registering MxChat REST routes', 'mxchat'));
192 -
193 - register_rest_route('mxchat/v1', '/stream', [
194 - 'methods' => 'GET',
195 - 'callback' => [$this, 'mxchat_stream_events'],
196 - 'permission_callback' => [$this, 'verify_chat_session'],
197 - ]);
198 -
199 - register_rest_route('mxchat/v1', '/agent-response', [
200 - 'methods' => 'POST',
201 - 'callback' => [$this, 'mxchat_handle_agent_response'],
202 - 'permission_callback' => [$this, 'verify_slack_request'],
203 - ]);
204 -
205 - register_rest_route('mxchat/v1', '/slack-interaction', [
206 - 'methods' => 'POST',
207 - 'callback' => [$this, 'handle_slack_interaction'],
208 - 'permission_callback' => [$this, 'verify_slack_request'],
209 - ]);
210 -
211 - //error_log(esc_html__('MxChat REST routes registered', 'mxchat'));
212 -}
213 -
214 -/**
215 - * Verify valid chat session
216 - */
217 -public function verify_chat_session($request) {
218 - $session_id = $request->get_param('session_id');
219 - if (empty($session_id)) {
220 - //error_log(esc_html__('Empty session ID in chat request', 'mxchat'));
221 - return false;
222 - }
223 -
224 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
225 - return $chat_mode === 'agent';
226 -}
227 -
228 -/**
229 - * Verify request is coming from Slack.
230 - *
231 - * @param WP_REST_Request $request
232 - * @return bool True if valid, false otherwise.
233 - */
234 -public function verify_slack_request($request) {
235 - // Get the Slack signing secret from your plugin options
236 - $valid_key = $this->options['live_agent_secret_key'] ?? '';
237 -
238 - if (empty($valid_key)) {
239 - //error_log(esc_html__('Slack signing secret not configured', 'mxchat'));
240 - return false;
241 - }
242 -
243 - $timestamp = $request->get_header('X-Slack-Request-Timestamp');
244 - $slack_signature = $request->get_header('X-Slack-Signature');
245 -
246 - // Verify timestamp to prevent replay attacks
247 - if (abs(time() - intval($timestamp)) > 300) {
248 - //error_log(esc_html__('Slack request timestamp too old', 'mxchat'));
249 - return false;
250 - }
251 -
252 - // Get raw request body
253 - $request_body = file_get_contents('php://input');
254 -
255 - // Create the signature base string
256 - $sig_basestring = "v0:{$timestamp}:{$request_body}";
257 -
258 - // Calculate expected signature
259 - $my_signature = 'v0=' . hash_hmac('sha256', $sig_basestring, $valid_key);
260 -
261 - // Compare signatures
262 - return hash_equals($my_signature, $slack_signature);
263 -}
264 -public function mxchat_stream_events(WP_REST_Request $request) {
265 - header('Content-Type: text/event-stream');
266 - header('Cache-Control: no-cache');
267 - header('Connection: keep-alive');
268 -
269 - $session_id = sanitize_text_field($request->get_param('session_id'));
270 - $last_seen_id = sanitize_text_field($request->get_param('last_seen_id')) ?: '';
271 -
272 - if (empty($session_id)) {
273 - echo esc_html__("event: error\ndata: ", 'mxchat') . esc_html__('Missing session_id', 'mxchat') . "\n\n";
274 - flush();
275 - exit;
276 - }
277 -
278 - $history = get_option("mxchat_history_{$session_id}", []);
279 -
280 - // Filter only new messages
281 - $new_messages = array_filter($history, function ($message) use ($last_seen_id) {
282 - return !empty($message['id']) && $message['id'] > $last_seen_id;
283 - });
284 -
285 - // Send new messages if available
286 - if (!empty($new_messages)) {
287 - echo esc_html__("event: newMessages\ndata: ", 'mxchat') . json_encode(array_values($new_messages)) . "\n\n";
288 - } else {
289 - // Keep the connection alive
290 - echo esc_html__("event: keepAlive\ndata: ", 'mxchat') . "{}\n\n";
291 - }
292 - flush();
293 - exit;
294 -}
295 -
296 -
297 -
298 -
299 -private function mxchat_save_chat_message($session_id, $role, $message) {
300 - global $wpdb;
301 -
302 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
303 - //error_log("[DEBUG] mxchat_save_chat_message -> START for session_id: {$session_id}, role: {$role}");
304 -
305 - // 1) Extract agent name if present
306 - $agent_name = '';
307 - if (preg_match('/^Agent: (.*?) - /', $message, $matches)) {
308 - $agent_name = $matches[1];
309 - $message = str_replace("Agent: $agent_name - ", '', $message);
310 -
311 - $session_meta_key = "mxchat_agent_name_{$session_id}";
312 - if (empty(get_option($session_meta_key))) {
313 - update_option($session_meta_key, $agent_name);
314 - //error_log("[DEBUG] mxchat_save_chat_message -> Stored agent_name in option: {$session_meta_key} => {$agent_name}");
315 - }
316 - }
317 -
318 - // 2) Generate unique message_id
319 - $message_id = uniqid();
320 - //error_log("[DEBUG] mxchat_save_chat_message -> Generated message_id: {$message_id}");
321 -
322 - // 3) Determine user_id
323 - $user_id = is_user_logged_in() ? get_current_user_id() : 0;
324 -
325 - // 4) Determine user_identifier
326 - $user_identifier = $agent_name
327 - ? $agent_name
328 - : MxChat_User::mxchat_get_user_identifier();
329 -
330 - // 5) Determine displayed_name
331 - $user_email = MxChat_User::mxchat_get_user_email();
332 - $displayed_name = $agent_name ? $agent_name : ($user_email ?: $user_identifier);
333 -
334 - // 6) Check for a saved email in wp_options
335 - $email_option_key = "mxchat_email_{$session_id}";
336 - $saved_email = get_option($email_option_key);
337 - //error_log("[DEBUG] mxchat_save_chat_message -> Checking wp_options for email_option_key: {$email_option_key}, found: {$saved_email}");
338 -
339 - // If found, update DB user_email
340 - if ($saved_email) {
341 - $update_res = $wpdb->update(
342 - $table_name,
343 - ['user_email' => $saved_email],
344 - ['session_id' => $session_id],
345 - ['%s'],
346 - ['%s']
347 - );
348 - //error_log("[DEBUG] mxchat_save_chat_message -> Attempted DB user_email update for session_id {$session_id}. update_res: {$update_res}");
349 - }
350 -
351 - // 7) Save to session history in wp_options
352 - $history_key = "mxchat_history_{$session_id}";
353 - $history = get_option($history_key, []);
354 - $history[] = [
355 - 'id' => $message_id,
356 - 'role' => $role,
357 - 'content' => $message,
358 - 'timestamp' => round(microtime(true) * 1000),
359 - 'agent_name' => $displayed_name,
360 - ];
361 - update_option($history_key, $history);
362 - //error_log("[DEBUG] mxchat_save_chat_message -> Updated session history in option: {$history_key}");
363 -
364 - // 8) Save the message to DB (INSERT)
365 - $insert_data = [
366 - 'user_id' => $user_id,
367 - 'user_identifier'=> $user_identifier,
368 - 'user_email' => $saved_email ?: $user_email,
369 - 'session_id' => $session_id,
370 - 'role' => $role,
371 - 'message' => $message,
372 - 'timestamp' => current_time('mysql', 1),
373 - ];
374 - $wpdb->insert($table_name, $insert_data);
375 - //error_log("[DEBUG] mxchat_save_chat_message -> Inserted message into DB. row_id: {$wpdb->insert_id}, data: " . print_r($insert_data, true));
376 -
377 - //error_log("[DEBUG] mxchat_save_chat_message -> END for session_id: {$session_id}");
378 - return $message_id;
379 -}
380 -
381 -public function mxchat_handle_save_email_and_response() {
382 - //error_log('[DEBUG] ---------- mxchat_handle_save_email_and_response START ----------');
383 -
384 - // Validate nonce
385 - if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
386 - error_log(esc_html__('[ERROR] Invalid nonce in mxchat_handle_save_email_and_response', 'mxchat'));
387 - wp_send_json_error(['message' => esc_html__('Invalid nonce.', 'mxchat')]);
388 - wp_die();
389 - }
390 -
391 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
392 - $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
393 -
394 - //error_log("[DEBUG] handle_save_email_and_response -> session_id: {$session_id}, email: {$email}");
395 -
396 - if (empty($session_id) || empty($email)) {
397 - //error_log("[ERROR] Missing session_id or email: session_id={$session_id}, email={$email}");
398 - wp_send_json_error(['message' => esc_html__('Session ID or email is missing.', 'mxchat')]);
399 - wp_die();
400 - }
401 -
402 - // 1) Always store in wp_options
403 - $option_key = "mxchat_email_{$session_id}";
404 - update_option($option_key, $email);
405 - //error_log("[DEBUG] handle_save_email_and_response -> updated option: {$option_key} => {$email}");
406 -
407 - // 2) (Optional) Also store in DB if a row already exists
408 - global $wpdb;
409 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
410 -
411 - // Make sure we have a valid placeholder in prepare
412 - $sql = $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", $session_id);
413 - $session_count = $wpdb->get_var($sql);
414 -
415 - //error_log("[DEBUG] handle_save_email_and_response -> session_count for {$session_id}: {$session_count} (SQL: {$sql})");
416 -
417 - if ($session_count) {
418 - // Update user_email if row(s) exist
419 - $update_sql = $wpdb->prepare(
420 - "UPDATE {$table_name} SET user_email = %s WHERE session_id = %s",
421 - $email,
422 - $session_id
423 - );
424 - $wpdb->query($update_sql);
425 - //error_log("[DEBUG] handle_save_email_and_response -> DB updated: {$update_sql}");
426 - } else {
427 - //error_log("[INFO] handle_save_email_and_response -> No DB entry for {$session_id}, so email is only in wp_options.");
428 - }
429 -
430 - // Provide success response
431 - $bot_message = __('Thanks for providing your email! You can continue chatting now.', 'mxchat');
432 - //error_log("[DEBUG] handle_save_email_and_response -> success, returning bot_message: {$bot_message}");
433 - wp_send_json_success(['message' => $bot_message]);
434 - wp_die();
435 -}
436 -
437 -public function mxchat_check_email_provided() {
438 - //error_log('[DEBUG] ---------- mxchat_check_email_provided START ----------');
439 -
440 - if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
441 - //error_log('[ERROR] Invalid nonce in mxchat_check_email_provided');
442 - wp_send_json_error(['message' => esc_html__('Invalid nonce', 'mxchat')]);
443 - }
444 -
445 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
446 - if (empty($session_id)) {
447 - //error_log('[ERROR] No session ID provided in mxchat_check_email_provided');
448 - wp_send_json_error(['message' => esc_html__('No session ID provided', 'mxchat')]);
449 - }
450 -
451 - // Check if the user is logged in
452 - if (is_user_logged_in()) {
453 - $current_user = wp_get_current_user();
454 - //error_log("[DEBUG] User is logged in as {$current_user->user_email}");
455 - wp_send_json_success(['logged_in' => true, 'email' => $current_user->user_email]);
456 - }
457 -
458 - $option_key = "mxchat_email_{$session_id}";
459 - $stored_email = get_option($option_key, '');
460 -
461 - //error_log("[DEBUG] mxchat_check_email_provided -> Checking option: {$option_key}, found: {$stored_email}");
462 -
463 - if (!empty($stored_email)) {
464 - //error_log("[DEBUG] mxchat_check_email_provided -> Email found, returning success");
465 - wp_send_json_success(['email' => $stored_email]);
466 - } else {
467 - //error_log("[DEBUG] mxchat_check_email_provided -> No email found, returning error");
468 - wp_send_json_error(['message' => esc_html__('No email found', 'mxchat')]);
469 - }
470 -}
471 -
472 -
473 -// First, add this helper function to get the highest rate limit for a user's roles
474 -private function get_user_role_rate_limit($user_id) {
475 - //error_log(esc_html__("Checking rate limit for user ID: ", 'mxchat') . $user_id);
476 -
477 - if (!$user_id) {
478 - //error_log(esc_html__("No user ID provided, using logged-out limit: ", 'mxchat') . ($this->options['rate_limit_logged_out'] ?? '10'));
479 - return $this->options['rate_limit_logged_out'] ?? '10';
480 - }
481 -
482 - $user = get_userdata($user_id);
483 - if (!$user || !$user->roles) {
484 - //error_log(esc_html__("No user data or roles found, using logged-out limit: ", 'mxchat') . ($this->options['rate_limit_logged_out'] ?? '10'));
485 - return $this->options['rate_limit_logged_out'] ?? '10';
486 - }
487 -
488 - //error_log(esc_html__("User roles: ", 'mxchat') . print_r($user->roles, true));
489 - //error_log(esc_html__("Available role rate limits: ", 'mxchat') . print_r($this->options['role_rate_limits'] ?? [], true));
490 -
491 - $max_limit = 0;
492 - foreach ($user->roles as $role) {
493 - //error_log(esc_html__("Checking limit for role: ", 'mxchat') . $role);
494 - if (isset($this->options['role_rate_limits'][$role])) {
495 - $role_limit = $this->options['role_rate_limits'][$role];
496 - //error_log(esc_html__("Found limit for role ", 'mxchat') . $role . esc_html__(": ", 'mxchat') . $role_limit);
497 -
498 - if ($role_limit === 'unlimited') {
499 - //error_log(esc_html__("Returning unlimited for role: ", 'mxchat') . $role);
500 - return 'unlimited';
501 - }
502 -
503 - $max_limit = max($max_limit, (int)$role_limit);
504 - //error_log(esc_html__("Current max limit: ", 'mxchat') . $max_limit);
505 - } else {
506 - //error_log(esc_html__("No limit found for role: ", 'mxchat') . $role);
507 - }
508 - }
509 -
510 - $final_limit = $max_limit > 0 ? (string)$max_limit : '100';
511 - //error_log(esc_html__("Final rate limit: ", 'mxchat') . $final_limit);
512 - return $final_limit;
513 -}
514 -
515 -
516 -// Add this to your plugin's main PHP file
517 -public function mxchat_check_new_messages() {
518 - if (!isset($_POST['session_id']) || !isset($_POST['last_seen_id'])) {
519 - wp_send_json_error(['message' => 'Missing required parameters']);
520 - wp_die();
521 - }
522 -
523 - $session_id = sanitize_text_field($_POST['session_id']);
524 - $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
525 -
526 - // Get chat history
527 - $history = get_option("mxchat_history_{$session_id}", []);
528 -
529 - if (empty($history)) {
530 - wp_send_json_success([
531 - 'hasNewMessages' => false,
532 - 'new_messages' => []
533 - ]);
534 - wp_die();
535 - }
536 -
537 - // Filter new messages
538 - $new_messages = array_filter($history, function($message) use ($last_seen_id) {
539 - return isset($message['id']) && $message['id'] > $last_seen_id;
540 - });
541 -
542 - // Sort by ID to ensure proper order
543 - usort($new_messages, function($a, $b) {
544 - return $a['id'] <=> $b['id'];
545 - });
546 -
547 - wp_send_json_success([
548 - 'hasNewMessages' => !empty($new_messages),
549 - 'new_messages' => array_values($new_messages),
550 - 'latestMessageId' => end($new_messages)['id'] ?? $last_seen_id
551 - ]);
552 - wp_die();
553 -}
554 -
555 -public function mxchat_handle_chat_request() {
556 - global $wpdb;
557 -
558 -
559 - // Check if MX Chat Moderation is active
560 - if (class_exists('MX_Chat_Moderation')) {
561 - // Get user email and IP
562 - $user_email = '';
563 - $user_ip = $_SERVER['REMOTE_ADDR'];
564 -
565 - // If user is logged in, get their email
566 - if (is_user_logged_in()) {
567 - $current_user = wp_get_current_user();
568 - $user_email = $current_user->user_email;
569 - }
570 -
571 - // Create ban handler instance
572 - $ban_handler = new MX_Chat_Ban_Handler();
573 -
574 - // Check if user is banned by IP
575 - if ($ban_handler->check_ban($user_ip, 'ip')) {
576 - wp_send_json([
577 - 'success' => false,
578 - 'message' => esc_html__('Access denied. Your IP address has been banned.', 'mxchat'),
579 - 'status' => 'banned'
580 - ]);
581 - wp_die();
582 - }
583 -
584 - // If user is logged in, also check email
585 - if (!empty($user_email) && $ban_handler->check_ban($user_email, 'email')) {
586 - wp_send_json([
587 - 'success' => false,
588 - 'message' => esc_html__('Access denied. Your email address has been banned.', 'mxchat'),
589 - 'status' => 'banned'
590 - ]);
591 - wp_die();
592 - }
593 - }
594 -
595 -
596 - // Reset fallback response at the start of each request
597 - $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
598 - $this->productCardHtml = '';
599 -
600 - // Get the actual WordPress user ID if logged in
601 - $is_logged_in = is_user_logged_in();
602 - if ($is_logged_in) {
603 - $user_id = get_current_user_id(); // This will get the actual WordPress user ID
604 - } else {
605 - // For logged-out users, use your existing identifier method
606 - $user_id = $this->mxchat_get_user_identifier();
607 - }
608 -
609 - // Get and sanitize the user identifier
610 - $user_id = sanitize_key($user_id);
611 -
612 - // Determine if user is logged in
613 - $is_logged_in = is_user_logged_in();
614 - //error_log("User logged in status: " . ($is_logged_in ? 'true' : 'false'));
615 -
616 - // Get rate limit based on user status
617 - // Get rate limit based on user status
618 - $rate_limit = $is_logged_in
619 - ? $this->get_user_role_rate_limit($user_id)
620 - : ($this->options['rate_limit_logged_out'] ?? '10');
621 -
622 - //error_log("Selected rate limit: " . $rate_limit);
623 -
624 - // Rest of your code remains the same
625 - // If rate limit is 'unlimited', skip rate limiting checks
626 - if ($rate_limit !== 'unlimited') {
627 - // Convert rate limit to integer
628 - $rate_limit = intval($rate_limit);
629 - // Setup rate limiting
630 - $rate_limit_transient_key = 'mxchat_chat_limit_' . $user_id;
631 - $chat_count = get_transient($rate_limit_transient_key);
632 - if ($chat_count === false) {
633 - // Initialize new counter if none exists
634 - $chat_count = 0;
635 - }
636 - // Check if user has exceeded their rate limit
637 - if ($chat_count >= $rate_limit) {
638 - // Get custom rate limit message or use default
639 - $rate_limit_message = isset($this->options['rate_limit_message'])
640 - ? $this->options['rate_limit_message']
641 - : esc_html__('Rate limit exceeded. Please try again later.', 'mxchat');
642 - // Replace placeholder if it exists in the message
643 - $rate_limit_message = str_replace(
644 - array('{limit}', '{count}', '{remaining}'),
645 - array($rate_limit, $chat_count, max(0, $rate_limit - $chat_count)),
646 - $rate_limit_message
647 - );
648 - wp_send_json([
649 - 'success' => false,
650 - 'message' => $rate_limit_message,
651 - 'status' => 'rate_limit_exceeded',
652 - 'limit' => $rate_limit,
653 - 'count' => $chat_count
654 - ]);
655 - wp_die();
656 - }
657 - // Increment the counter
658 - $chat_count++;
659 - // Store the updated count with 24-hour expiration
660 - set_transient($rate_limit_transient_key, $chat_count, DAY_IN_SECONDS);
661 - }
662 -
663 - // Rest of your existing code...
664 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
665 - //error_log("Session ID: $session_id");
666 -
667 - if (empty($session_id)) {
668 - //error_log("Error: Session ID is missing.");
669 - wp_send_json_error(esc_html__('Session ID is missing.', 'mxchat'));
670 - wp_die();
671 - }
672 -
673 - // Validate and sanitize the incoming message
674 - if (empty($_POST['message'])) {
675 - //error_log("Error: No message received.");
676 - wp_send_json_error(esc_html__('No message received.', 'mxchat'));
677 - wp_die();
678 - }
679 -
680 -
681 -// Modify the message sanitization to preserve PHP tags in code blocks
682 -$allowed_tags = [
683 - 'pre' => [],
684 - 'code' => ['class' => true],
685 - 'span' => ['class' => true],
686 - 'div' => ['class' => true],
687 -];
688 -
689 -// First preserve code blocks
690 -$message = preg_replace_callback('/<pre><code.*?>.*?<\/code><\/pre>/s', function($matches) {
691 - return htmlspecialchars_decode($matches[0]);
692 -}, $_POST['message']);
693 -
694 -// Then apply sanitization
695 -$message = wp_kses($message, $allowed_tags);
696 -
697 -// Decode code blocks
698 -$message = preg_replace_callback('/(&lt;pre&gt;&lt;code.*?&gt;.*?&lt;\/code&gt;&lt;\/pre&gt;)/s', function($matches) {
699 - return htmlspecialchars_decode($matches[1]);
700 -}, $message);
701 -
702 -$message = trim($message);
703 -
704 -// Preserve code blocks from markdown conversion
705 -$message = preg_replace('/```(\w+)?\s*([\s\S]+?)```/s', '<pre><code class="$1">$2</code></pre>', $message);
706 -
707 - // Save the user's message
708 - $this->mxchat_save_chat_message($session_id, 'user', $message);
709 -
710 - // Check if the message is an email address
711 - if (is_email($message)) {
712 - // Add the email to Loops
713 - $this->add_email_to_loops($message);
714 -
715 - // Send success response
716 - $response_message = $this->options['email_capture_response'] ??
717 - esc_html__('Thank you! Your coupon is on the way!', 'mxchat');
718 -
719 - wp_send_json([
720 - 'success' => true,
721 - 'status' => 'email_captured',
722 - 'message' => $response_message
723 - ]);
724 - wp_die();
725 - }
726 -
727 - $intent_info = '';
728 -
729 - // Check chat mode
730 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
731 - //error_log("Chat Mode: $chat_mode");
732 -
733 - // Handle agent mode
734 - if ($chat_mode === 'agent') {
735 - // First, check for switch intent before doing anything else
736 - $intent_matched = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
737 -
738 - // If we matched an intent and it's the switch intent, handle it
739 - if ($intent_matched && !empty($this->fallbackResponse['text'])) {
740 - //error_log("Switch to chatbot intent detected");
741 -
742 - // Update chat mode first
743 - update_option("mxchat_mode_{$session_id}", 'ai');
744 -
745 - // Clear any existing PDF context to start fresh
746 - $this->clear_pdf_transients($session_id);
747 -
748 - // Prepare clean switch response
749 - $response_data = [
750 - 'text' => $this->fallbackResponse['text'],
751 - 'html' => '',
752 - 'session_id' => $session_id,
753 - 'chat_mode' => 'ai'
754 - ];
755 -
756 - // Save the mode switch message
757 - $this->mxchat_save_chat_message($session_id, 'system', esc_html__('Switched to AI chat mode', 'mxchat'));
758 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
759 -
760 - // Send response and exit
761 - wp_send_json($response_data);
762 - wp_die();
763 - } elseif (!$intent_matched) {
764 - // No intent matched, handle live agent message
765 - try {
766 - $this->mxchat_send_user_message_to_agent($message, $user_id, $session_id);
767 - //error_log("Message sent to agent.");
768 -
769 - wp_send_json_success([
770 - 'status' => 'waiting_for_agent',
771 - 'message' => esc_html__('Message sent to live agent.', 'mxchat')
772 - ]);
773 - } catch (\Exception $e) {
774 - //error_log("Error sending message to agent: " . $e->getMessage());
775 - wp_send_json_error(esc_html__('Failed to send message to agent', 'mxchat'));
776 - }
777 - wp_die();
778 - }
779 - }
780 -
781 - // Step 1: Check for new PDF URL in the message
782 - if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
783 - $new_pdf_url = $matches[0];
784 -
785 - // Check if this is likely a PDF-related request
786 - $pdf_keywords = ['pdf', 'document', 'read', 'analyze'];
787 - $is_pdf_request = false;
788 -
789 - foreach ($pdf_keywords as $keyword) {
790 - if (stripos($message, $keyword) !== false) {
791 - $is_pdf_request = true;
792 - break;
793 - }
794 - }
795 -
796 - // If it looks like a PDF request or we're waiting for a PDF URL
797 - if ($is_pdf_request || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
798 - // Validate HTTPS
799 - if (wp_http_validate_url($new_pdf_url) && parse_url($new_pdf_url, PHP_URL_SCHEME) === 'https') {
800 - // Extract filename from URL
801 - $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
802 -
803 - // Clear previous PDF transients
804 - $this->clear_pdf_transients($session_id);
805 -
806 - // Process new PDF
807 - $max_pages = $this->options['pdf_max_pages'] ?? 69;
808 - $embeddings = $this->fetch_and_split_pdf_pages($new_pdf_url, $max_pages);
809 -
810 - if ($embeddings === 'too_many_pages') {
811 - $error_text = sprintf(
812 - $this->options['pdf_intent_error_text'] ??
813 - esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
814 - $max_pages
815 - );
816 - $this->fallbackResponse['text'] = $error_text;
817 - } elseif ($embeddings) {
818 - // Store new PDF information
819 - // Create a more meaningful filename from URL
820 - $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
821 -
822 - // If the filename is generic (like results_download.php), create a more descriptive one
823 - if (in_array($pdf_filename, ['results_download.php', 'download.php', 'view.php', 'pdf.php']) ||
824 - strpos($pdf_filename, '.php') !== false) {
825 - // Create a timestamp-based name
826 - $pdf_filename = 'Document_' . date('Y-m-d_H-i') . '.pdf';
827 - }
828 -
829 - set_transient('mxchat_pdf_url_' . $session_id, $new_pdf_url, HOUR_IN_SECONDS);
830 - set_transient('mxchat_pdf_filename_' . $session_id, $pdf_filename, HOUR_IN_SECONDS);
831 - set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
832 - set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
833 -
834 - $success_text = $this->options['pdf_intent_success_text'] ??
835 - esc_html__("I've processed the new PDF '{$pdf_filename}'. What questions do you have about it?", 'mxchat');
836 -
837 - // Return success with filename for UI update
838 - wp_send_json([
839 - 'success' => true,
840 - 'message' => $success_text,
841 - 'data' => [
842 - 'filename' => $pdf_filename
843 - ]
844 - ]);
845 - wp_die();
846 - } else {
847 - $error_text = $this->options['pdf_intent_error_text'] ??
848 - esc_html__("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
849 - $this->fallbackResponse['text'] = $error_text;
850 - }
851 -
852 - wp_send_json([
853 - 'success' => false,
854 - 'message' => $this->fallbackResponse['text']
855 - ]);
856 - wp_die();
857 - }
858 - }
859 - }
860 -
861 - // Step 2: Detect intent and handle intent-based responses
862 - $intent_matched = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
863 - //error_log("Intent Matched: " . ($intent_matched ? "Yes" : "No"));
864 -
865 - // Step 3: If intent is matched and handled, respond immediately
866 - if ($intent_matched && (!empty($this->fallbackResponse['text']) || !empty($this->fallbackResponse['html']))) {
867 - //error_log("Intent response triggered.");
868 - $response_data = [
869 - 'text' => $this->fallbackResponse['text'],
870 - 'html' => $this->fallbackResponse['html'],
871 - 'session_id' => $session_id
872 - ];
873 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text'] . $this->fallbackResponse['html']);
874 - wp_send_json($response_data);
875 - wp_die();
876 - }
877 -
878 - // If no intent matched or product not found, proceed with AI response
879 - //error_log("No matching intent or fallback. Generating AI response.");
880 -
881 - // Step 4: Generate AI response
882 - $conversation_history = $this->mxchat_fetch_conversation_history_for_ai($session_id);
883 - $this->mxchat_increment_chat_count();
884 -
885 - // Generate embedding for the user's query
886 - $user_message_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
887 - if (!is_array($user_message_embedding)) {
888 - //error_log("Failed to generate message embedding for session $session_id");
889 - wp_send_json_error(esc_html__('Error processing your message.', 'mxchat'));
890 - wp_die();
891 - }
892 -
893 - // Build context with both knowledge base and PDF content if available
894 - $context_content = "User asked: '{$message}'\n\n";
895 -
896 - // Get relevant content from knowledge base
897 - $relevant_content = $this->mxchat_find_relevant_content($user_message_embedding);
898 - if (!empty($relevant_content)) {
899 - $context_content .= "Relevant content from knowledge database:\n" . $relevant_content . "\n\n";
900 - }
901 -
902 -
903 - // Check for and include PDF content
904 - $pdf_url = get_transient('mxchat_pdf_url_' . $session_id);
905 - $pdf_embeddings = get_transient('mxchat_pdf_embeddings_' . $session_id);
906 - $pdf_filename = get_transient('mxchat_pdf_filename_' . $session_id);
907 - if ($pdf_url && $pdf_embeddings && get_transient('mxchat_include_pdf_in_context_' . $session_id)) {
908 - $relevant_pdf_pages = $this->find_relevant_pdf_pages($user_message_embedding, $pdf_embeddings);
909 - if (!empty($relevant_pdf_pages)) {
910 - $context_content .= "Relevant content from PDF document '{$pdf_filename}':\n";
911 - foreach ($relevant_pdf_pages as $page_data) {
912 - $context_content .= "Page {$page_data['page_number']} of '{$pdf_filename}': {$page_data['text']}\n";
913 - }
914 - $context_content .= "\n";
915 - }
916 - }
917 -
918 - // Check for and include Word content
919 - $word_url = get_transient('mxchat_word_url_' . $session_id);
920 - $word_embeddings = get_transient('mxchat_word_embeddings_' . $session_id);
921 - $word_filename = get_transient('mxchat_word_filename_' . $session_id);
922 - if ($word_url && $word_embeddings && get_transient('mxchat_include_word_in_context_' . $session_id)) {
923 - $relevant_word_chunks = $this->word_handler->mxchat_find_relevant_word_chunks($user_message_embedding, $word_embeddings);
924 - if (!empty($relevant_word_chunks)) {
925 - $context_content .= "Relevant content from Word document '{$word_filename}':\n";
926 - foreach ($relevant_word_chunks as $chunk_data) {
927 - $context_content .= "Section {$chunk_data['chunk_number']} of '{$word_filename}': {$chunk_data['text']}\n";
928 - }
929 - $context_content .= "\n";
930 - }
931 - }
932 - // Generate the response using the full context
933 - $response = $this->mxchat_generate_response(
934 - $context_content,
935 - $this->options['api_key'],
936 - $this->options['xai_api_key'],
937 - $this->options['claude_api_key'],
938 - $this->options['deepseek_api_key'],
939 - $conversation_history
940 - );
941 -
942 - $this->mxchat_save_chat_message($session_id, 'bot', $response);
943 -
944 - // Step 5: Save additional content if available
945 - if (!empty($this->productCardHtml)) {
946 - $this->mxchat_save_chat_message($session_id, 'bot', $this->productCardHtml);
947 - }
948 -
949 - if (!empty($this->fallbackResponse['html'])) {
950 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
951 - }
952 -
953 - // Step 6: Return the response
954 - $response_data = [
955 - 'text' => $response,
956 - 'html' => !empty($this->productCardHtml) ? $this->productCardHtml : ($this->fallbackResponse['html'] ?? ''),
957 - 'session_id' => $session_id
958 - ];
959 -
960 - wp_send_json($response_data);
961 - wp_die();
962 -}
963 -
964 -// New function to check intents and invoke the callback function
965 -private function mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id) {
966 - global $wpdb;
967 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
968 -
969 - //error_log('🔍 MXCHAT DEBUG: Intent Check Started ==================');
970 - //error_log("🔍 MXCHAT DEBUG: Message: '$message'");
971 - //error_log("🔍 MXCHAT DEBUG: Chat Mode: $chat_mode");
972 -
973 - // Generate the user embedding
974 - //error_log('🔄 MXCHAT DEBUG: Generating user embedding');
975 - $user_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
976 - if (!is_array($user_embedding)) {
977 - //error_log('❌ MXCHAT DEBUG: Failed to generate user embedding');
978 - return false;
979 - }
980 - //error_log('✅ MXCHAT DEBUG: User embedding generated successfully');
981 -
982 - // Fetch intents from the database
983 - $table_name = $wpdb->prefix . 'mxchat_intents';
984 - if ($chat_mode === 'agent') {
985 - //error_log('🔍 MXCHAT DEBUG: Agent mode - fetching only chatbot switch intent');
986 - $query = $wpdb->prepare(
987 - "SELECT * FROM $table_name WHERE callback_function = %s",
988 - 'mxchat_handle_switch_to_chatbot_intent'
989 - );
990 - $intents = $wpdb->get_results($query);
991 - } else {
992 - //error_log('🔍 MXCHAT DEBUG: AI mode - fetching all intents');
993 - $intents = $wpdb->get_results("SELECT * FROM $table_name");
994 - }
995 -
996 - //error_log('🔍 MXCHAT DEBUG: Found ' . count($intents) . ' intents to check');
997 -
998 - if (empty($intents)) {
999 - //error_log('❌ MXCHAT DEBUG: No intents found in database');
1000 - return false;
1001 - }
1002 -
1003 - $highest_similarity = -INF;
1004 - $matched_intent = null;
1005 -
1006 - //error_log('📊 MXCHAT DEBUG: Intent Similarity Scores ==================');
1007 - foreach ($intents as $intent) {
1008 - //error_log("🔄 MXCHAT DEBUG: Checking intent: '{$intent->intent_label}' (callback: {$intent->callback_function})");
1009 -
1010 - $intent_embedding_serialized = $intent->embedding_vector;
1011 - $intent_embedding = $intent_embedding_serialized
1012 - ? unserialize($intent_embedding_serialized, ['allowed_classes' => false])
1013 - : null;
1014 -
1015 - if (!is_array($intent_embedding)) {
1016 - //error_log("❌ MXCHAT DEBUG: Invalid embedding for intent: {$intent->intent_label}");
1017 - continue;
1018 - }
1019 -
1020 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $intent_embedding);
1021 - $intent_threshold = isset($intent->similarity_threshold) ? $intent->similarity_threshold : 0.85;
1022 -
1023 -
1024 - if ($similarity >= $intent_threshold && $similarity > $highest_similarity) {
1025 - $highest_similarity = $similarity;
1026 - $matched_intent = $intent;
1027 - //error_log("✅ MXCHAT DEBUG: New best match: '{$intent->intent_label}' with similarity {$similarity}");
1028 - }
1029 - }
1030 - //error_log('📊 MXCHAT DEBUG: End Intent Scores ==================');
1031 -
1032 - if ($matched_intent) {
1033 - //error_log("🎯 MXCHAT DEBUG: Final Intent Match: '{$matched_intent->intent_label}'");
1034 - //error_log("🔄 MXCHAT DEBUG: Invoking callback: {$matched_intent->callback_function}");
1035 -
1036 - // If the callback is a method on this instance (core callback), call it directly
1037 - if (method_exists($this, $matched_intent->callback_function)) {
1038 - //error_log('🔍 MXCHAT DEBUG: Using direct method call for core callback');
1039 - $callback_result = call_user_func(
1040 - [$this, $matched_intent->callback_function],
1041 - $message,
1042 - $user_id,
1043 - $session_id,
1044 - $matched_intent,
1045 - $user_context // Add user context
1046 - );
1047 - } else {
1048 - //error_log('🔍 MXCHAT DEBUG: Using apply_filters for add-on callback');
1049 - // Otherwise, use apply_filters for add-on callbacks
1050 - $callback_result = apply_filters(
1051 - $matched_intent->callback_function,
1052 - false, // default return value
1053 - $message,
1054 - $user_id,
1055 - $session_id,
1056 - $matched_intent
1057 - );
1058 - }
1059 -
1060 - //error_log('🔍 MXCHAT DEBUG: Callback result type: ' . gettype($callback_result));
1061 - if ($callback_result !== false) {
1062 - //error_log('✅ MXCHAT DEBUG: Intent handled successfully');
1063 - $this->fallbackResponse = $callback_result;
1064 - return true;
1065 - }
1066 - //error_log('❌ MXCHAT DEBUG: Callback returned false');
1067 - } else {
1068 - //error_log('❌ MXCHAT DEBUG: No matching intent found');
1069 - }
1070 -
1071 - //error_log('🔍 MXCHAT DEBUG: Intent Check Completed ==================');
1072 - return false;
1073 -}
1074 -
1075 -
1076 -// Helper function to clear PDF and Word document related transients
1077 -private function clear_pdf_transients($session_id) {
1078 - // PDF transients
1079 - delete_transient('mxchat_pdf_url_' . $session_id);
1080 - delete_transient('mxchat_pdf_embeddings_' . $session_id);
1081 - delete_transient('mxchat_include_pdf_in_context_' . $session_id);
1082 - delete_transient('mxchat_waiting_for_pdf_url_' . $session_id);
1083 -
1084 - // Word document transients
1085 - delete_transient('mxchat_word_url_' . $session_id);
1086 - delete_transient('mxchat_word_filename_' . $session_id);
1087 - delete_transient('mxchat_word_embeddings_' . $session_id);
1088 - delete_transient('mxchat_include_word_in_context_' . $session_id);
1089 - delete_transient('mxchat_waiting_for_word_' . $session_id);
1090 -}
1091 -
1092 -
1093 -
1094 -//verified good
1095 -public function mxchat_handle_email_capture($message, $user_id, $session_id) {
1096 - // Log the message safely
1097 - //error_log("Triggered email capture intent for message: " . sanitize_text_field($message));
1098 -
1099 - // Initiate email capture flow
1100 - $response = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Would you like to join our mailing list? Please provide your email below.", 'mxchat'));
1101 -
1102 - set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
1103 - $this->mxchat_save_chat_message($session_id, 'bot', $response);
1104 -
1105 - // Respond to the user
1106 - wp_send_json(['message' => $response]);
1107 - wp_die();
1108 -}
1109 -
1110 -//very good
1111 -public function mxchat_generate_image($message, $user_id, $session_id) {
1112 - // Prepare a prompt for DALL-E
1113 - $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
1114 -
1115 - // Use the existing OpenAI API key
1116 - $openai_api_key = sanitize_text_field($this->options['api_key']);
1117 -
1118 - // Call DALL-E to generate an image
1119 - $image_response = $this->mxchat_generate_dalle_image($prompt, $openai_api_key);
1120 -
1121 - // Check if the response contains an image URL
1122 - if (isset($image_response['imageUrl'])) {
1123 - $image_url = esc_url_raw($image_response['imageUrl']);
1124 -
1125 - // Construct the HTML with a CSS class instead of inline styles
1126 - $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
1127 -
1128 - $response_text = esc_html__('Here is the image I generated:', 'mxchat');
1129 - } else {
1130 - $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
1131 - $response_html = '';
1132 - //error_log("DALL-E image generation error: " . esc_html($image_response['error'] ?? 'Unknown error.'));
1133 - }
1134 -
1135 - // Save both text and HTML responses
1136 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text . "\n" . $response_html);
1137 -
1138 - // Prepare the response data
1139 - $response_data = [
1140 - 'message' => $response_text,
1141 - 'html' => $response_html,
1142 - 'image_url' => $image_url ?? '',
1143 - ];
1144 -
1145 - // Send the JSON response
1146 - header('Content-Type: application/json; charset=' . get_option('blog_charset'));
1147 - echo json_encode($response_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
1148 - wp_die();
1149 -}
1150 -private function mxchat_generate_dalle_image($prompt, $api_key, $model = 'dall-e-3', $timeout = 60) {
1151 - $api_url = 'https://api.openai.com/v1/images/generations';
1152 - $body = json_encode([
1153 - 'prompt' => sanitize_text_field($prompt),
1154 - 'n' => 1,
1155 - 'size' => '1024x1024',
1156 - 'model' => sanitize_text_field($model),
1157 - ]);
1158 -
1159 - $args = [
1160 - 'body' => $body,
1161 - 'headers' => [
1162 - 'Content-Type' => 'application/json',
1163 - 'Authorization' => 'Bearer ' . sanitize_text_field($api_key),
1164 - ],
1165 - 'method' => 'POST',
1166 - 'timeout' => absint($timeout),
1167 - ];
1168 -
1169 - $response = wp_remote_post($api_url, $args);
1170 -
1171 - if (is_wp_error($response)) {
1172 - //error_log("DALL-E request failed: " . $response->get_error_message());
1173 - return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
1174 - }
1175 -
1176 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
1177 -
1178 - if (isset($response_body['data'][0]['url'])) {
1179 - return ['imageUrl' => esc_url_raw($response_body['data'][0]['url'])];
1180 - } else {
1181 - //error_log("DALL-E response error: " . wp_remote_retrieve_body($response));
1182 - return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
1183 - }
1184 -}
1185 -
1186 -/**
1187 - * Handle web search requests.
1188 - *
1189 - * Sends the refined search query to the Brave Search API and displays neatly formatted,
1190 - * styled search results. Results are cached for performance.
1191 - *
1192 - * @since 1.0.0
1193 - * @param string $message The user's search query.
1194 - * @param string $user_id The user identifier.
1195 - * @param string $session_id The current session ID.
1196 - * @return void
1197 - */
1198 -public function mxchat_handle_search_request( $message, $user_id, $session_id ) {
1199 - // Step 1: Interpret and refine the search query
1200 - $refined_search_query = $this->mxchat_interpret_search_query( $message );
1201 -
1202 - if ( empty( $refined_search_query ) ) {
1203 - $this->fallbackResponse = array(
1204 - 'text' => esc_html__( 'I apologize, but could you please rephrase your search request?', 'mxchat' ),
1205 - );
1206 - return;
1207 - }
1208 -
1209 - // Retrieve and validate API settings
1210 - $options = get_option( 'mxchat_options' );
1211 - $api_key = isset( $options['brave_api_key'] ) ? sanitize_text_field( $options['brave_api_key'] ) : '';
1212 - $results_count = isset( $options['brave_results_count'] ) ? absint( $options['brave_results_count'] ) : 5;
1213 -
1214 - if ( empty( $api_key ) ) {
1215 - $this->fallbackResponse = array(
1216 - 'text' => esc_html__( 'Search functionality is temporarily unavailable. Please try again later.', 'mxchat' ),
1217 - );
1218 - return;
1219 - }
1220 -
1221 - // Build the API request URL
1222 - $api_url = add_query_arg(
1223 - array(
1224 - 'q' => rawurlencode( $refined_search_query ),
1225 - 'count' => $results_count,
1226 - 'text_decorations' => 'true',
1227 - 'rich_data' => 'true',
1228 - ),
1229 - 'https://api.search.brave.com/res/v1/web/search'
1230 - );
1231 -
1232 - // Attempt to retrieve cached results first
1233 - $transient_key = 'mxchat_search_' . md5( $refined_search_query );
1234 - $results = get_transient( $transient_key );
1235 -
1236 - if ( false === $results ) {
1237 - // Fetch new results from the Brave Search API
1238 - $response = wp_remote_get(
1239 - $api_url,
1240 - array(
1241 - 'headers' => array(
1242 - 'Accept' => 'application/json',
1243 - 'Accept-Encoding' => 'gzip',
1244 - 'X-Subscription-Token'=> $api_key,
1245 - ),
1246 - 'timeout' => 10,
1247 - )
1248 - );
1249 -
1250 - if ( is_wp_error( $response ) ) {
1251 - $this->fallbackResponse = array(
1252 - 'text' => esc_html__( 'I encountered an error while searching. Please try again.', 'mxchat' ),
1253 - );
1254 - return;
1255 - }
1256 -
1257 - $results = json_decode( wp_remote_retrieve_body( $response ), true );
1258 -
1259 - if ( json_last_error() !== JSON_ERROR_NONE ) {
1260 - $this->fallbackResponse = array(
1261 - 'text' => esc_html__( 'I received an invalid response from the search service.', 'mxchat' ),
1262 - );
1263 - return;
1264 - }
1265 -
1266 - // Cache results for one hour
1267 - set_transient( $transient_key, $results, HOUR_IN_SECONDS );
1268 - }
1269 -
1270 - // Process and display results
1271 - if ( ! empty( $results['web']['results'] ) && is_array( $results['web']['results'] ) ) {
1272 - $html = $this->generate_search_results_html( $results['web']['results'], $refined_search_query );
1273 -
1274 - // Only return HTML (no large text summary)
1275 - $this->fallbackResponse = array(
1276 - 'html' => $html,
1277 - );
1278 -
1279 - // Save to chat history
1280 - $this->mxchat_save_chat_message( $session_id, 'bot', $html );
1281 - } else {
1282 - $this->fallbackResponse = array(
1283 - 'text' => sprintf(
1284 - esc_html__( 'I couldn\'t find any relevant results for "%s". Would you like to try different search terms?', 'mxchat' ),
1285 - esc_html( $refined_search_query )
1286 - ),
1287 - );
1288 - }
1289 -}
1290 -
1291 -
1292 -/**
1293 - * Format search results into a natural text summary.
1294 - *
1295 - * @since 1.0.0
1296 - * @param array $results The search results from the API.
1297 - * @param string $query The original search query.
1298 - * @return string The text summary of the top results.
1299 - */
1300 -private function format_search_results( $results, $query ) {
1301 - $summary = sprintf(
1302 - esc_html__( 'Here are the most relevant results for "%s":', 'mxchat' ),
1303 - esc_html( $query )
1304 - ) . "\n\n";
1305 -
1306 - $max_results = min( count( $results ), 3 );
1307 - for ( $i = 0; $i < $max_results; $i++ ) {
1308 - $result = $results[ $i ];
1309 - $title = isset( $result['title'] ) ? wp_strip_all_tags( $result['title'] ) : '';
1310 - $description = isset( $result['description'] ) ? wp_strip_all_tags( $result['description'] ) : '';
1311 -
1312 - // Append title and description to the summary
1313 - $summary .= sprintf(
1314 - "%s\n%s\n\n",
1315 - esc_html( $title ),
1316 - esc_html( $description )
1317 - );
1318 - }
1319 -
1320 - return $summary;
1321 -}
1322 -
1323 -/**
1324 - * Generate HTML markup for search results.
1325 - *
1326 - * @since 1.0.0
1327 - * @param array $results The search results from the API.
1328 - * @param string $query The user-refined query.
1329 - * @return string The HTML markup for displaying the results.
1330 - */
1331 -private function generate_search_results_html( $results, $query ) {
1332 - ob_start();
1333 - ?>
1334 - <div class="mxchat-search-results">
1335 - <?php foreach ( $results as $result ) :
1336 - $title = isset( $result['title'] ) ? wp_strip_all_tags( $result['title'] ) : '';
1337 - $url = isset( $result['url'] ) ? esc_url( $result['url'] ) : '#';
1338 - $description = isset( $result['description'] ) ? wp_strip_all_tags( $result['description'] ) : '';
1339 - $favicon = isset( $result['meta_url']['favicon'] ) ? esc_url( $result['meta_url']['favicon'] ) : '';
1340 - $thumbnail = isset( $result['thumbnail']['src'] ) ? esc_url( $result['thumbnail']['src'] ) : '';
1341 - $domain = parse_url( $url, PHP_URL_HOST );
1342 - ?>
1343 - <div class="mxchat-search-item">
1344 - <div class="mxchat-search-header">
1345 - <?php if ( $favicon ) : ?>
1346 - <img
1347 - src="<?php echo esc_url( $favicon ); ?>"
1348 - class="mxchat-site-icon"
1349 - alt="<?php echo esc_attr__( 'Site icon', 'mxchat' ); ?>"
1350 - width="16"
1351 - height="16"
1352 - />
1353 - <?php endif; ?>
1354 - <div class="mxchat-site-url"><?php echo esc_html( $domain ); ?></div>
1355 - </div>
1356 -
1357 - <div class="mxchat-search-content">
1358 - <h3 class="mxchat-search-title">
1359 - <a href="<?php echo esc_url( $url ); ?>"
1360 - target="_blank"
1361 - rel="noopener noreferrer"
1362 - >
1363 - <?php echo esc_html( $title ); ?>
1364 - </a>
1365 - </h3>
1366 -
1367 - <?php if ( $thumbnail ) : ?>
1368 - <div class="mxchat-search-thumbnail">
1369 - <img
1370 - src="<?php echo esc_url( $thumbnail ); ?>"
1371 - alt="<?php echo esc_attr__( 'Thumbnail image', 'mxchat' ); ?>"
1372 - loading="lazy"
1373 - />
1374 - </div>
1375 - <?php endif; ?>
1376 -
1377 - <div class="mxchat-search-description">
1378 - <?php echo esc_html( $description ); ?>
1379 - </div>
1380 - </div>
1381 - </div>
1382 - <?php endforeach; ?>
1383 - </div>
1384 - <?php
1385 - return ob_get_clean();
1386 -}
1387 -
1388 -
1389 -//very good
1390 -public function mxchat_handle_image_search_request($message, $user_id, $session_id) {
1391 -
1392 - // Step 1: Interpret the search query for better results
1393 - $refined_search_query = $this->mxchat_interpret_search_query($message);
1394 -
1395 -
1396 - // If no query was interpreted, return a fallback message
1397 - if (empty($refined_search_query)) {
1398 - $this->fallbackResponse = [
1399 - 'text' => __("I'm sorry, I couldn't interpret your search query. Please specify what you'd like to see images of.", 'mxchat'),
1400 - 'html' => "",
1401 - ];
1402 - return;
1403 - }
1404 -
1405 - // Brave API URL
1406 - $api_url = 'https://api.search.brave.com/res/v1/images/search';
1407 -
1408 - // Retrieve Brave API settings
1409 - $options = get_option('mxchat_options');
1410 - $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
1411 -
1412 - if (empty($api_key)) {
1413 -/*
1414 - if (defined('WP_DEBUG') && WP_DEBUG) {
1415 - error_log("Brave API key is missing.");
1416 - }
1417 -*/
1418 -
1419 - $this->fallbackResponse = [
1420 - 'text' => __("API key is not configured. Please set it in the Brave Search Settings.", 'mxchat'),
1421 - 'html' => "",
1422 - ];
1423 - return;
1424 - }
1425 -
1426 - $image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
1427 - $safe_search = isset($options['brave_safe_search']) ? sanitize_text_field($options['brave_safe_search']) : 'strict';
1428 -
1429 - // Append query parameters based on settings
1430 - $api_url = add_query_arg([
1431 - 'q' => rawurlencode($refined_search_query),
1432 - 'count' => $image_count,
1433 - 'safesearch' => $safe_search,
1434 - ], $api_url);
1435 -
1436 -/*
1437 - // Log the final API URL for the search
1438 - if (defined('WP_DEBUG') && WP_DEBUG) {
1439 - error_log("Final API URL for Brave Image Search: " . esc_url_raw($api_url));
1440 - }
1441 -*/
1442 -
1443 -
1444 - // Implement caching
1445 - $transient_key = 'mxchat_image_search_' . md5($refined_search_query);
1446 - $body = get_transient($transient_key);
1447 -
1448 - if (false === $body) {
1449 - $args = [
1450 - 'headers' => [
1451 - 'Accept' => 'application/json',
1452 - 'Accept-Encoding' => 'gzip',
1453 - 'X-Subscription-Token' => $api_key,
1454 - ],
1455 - 'timeout' => 10,
1456 - ];
1457 -
1458 - $response = wp_remote_get($api_url, $args);
1459 -
1460 - if (is_wp_error($response)) {
1461 -/*
1462 - if (defined('WP_DEBUG') && WP_DEBUG) {
1463 - error_log("Brave Image API request failed: " . $response->get_error_message());
1464 - }
1465 -*/
1466 -
1467 - $this->fallbackResponse = [
1468 - 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
1469 - 'html' => "",
1470 - ];
1471 - return;
1472 - }
1473 -
1474 - $body = json_decode(wp_remote_retrieve_body($response), true);
1475 - set_transient($transient_key, $body, HOUR_IN_SECONDS);
1476 - }
1477 -
1478 - // Process the API response
1479 - if (isset($body['results']) && is_array($body['results']) && count($body['results']) > 0) {
1480 - $html_output = '<div class="mxchat-image-gallery">';
1481 -
1482 - foreach ($body['results'] as $image) {
1483 - $image_url = isset($image['url']) ? esc_url($image['url']) : '';
1484 - $thumbnail_url = isset($image['thumbnail']['src']) ? esc_url($image['thumbnail']['src']) : '';
1485 - $title = isset($image['title']) ? esc_html($image['title']) : esc_html__('Image', 'mxchat');
1486 -
1487 - if ($image_url && $thumbnail_url) {
1488 - $html_output .= '<div class="mxchat-image-item">';
1489 - $html_output .= '<strong class="mxchat-image-title">' . $title . '</strong>';
1490 - $html_output .= '<a href="' . $image_url . '" target="_blank" rel="noopener noreferrer" class="mxchat-image-link">';
1491 - $html_output .= '<img src="' . $thumbnail_url . '" alt="' . $title . '" class="mxchat-image-thumbnail">';
1492 - $html_output .= '</a></div>';
1493 - }
1494 - }
1495 -
1496 - $html_output .= '</div>';
1497 -
1498 - $this->fallbackResponse = [
1499 - 'text' => "",
1500 - 'html' => $html_output,
1501 - ];
1502 -
1503 - // Save response in chat history
1504 - $this->mxchat_save_chat_message($session_id, 'bot', $html_output);
1505 -
1506 - } else {
1507 -/*
1508 - if (defined('WP_DEBUG') && WP_DEBUG) {
1509 - error_log("Brave Image API response did not contain expected data structure or was empty: " . print_r($body, true));
1510 - }
1511 -*/
1512 -
1513 - $this->fallbackResponse = [
1514 - 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
1515 - 'html' => "",
1516 - ];
1517 - }
1518 -}
1519 -public function mxchat_interpret_search_query($user_query) {
1520 - $system_prompt = esc_html__("Interpret the user's request to provide only the essential keywords or phrases for image searching. Remove conversational language, politeness, or extra context. Return a concise search query that doesn't lose any of the original meaning.", 'mxchat');
1521 -
1522 - // Retrieve OpenAI API key using 'api_key' as the option key
1523 - $api_key = isset($this->options['api_key']) ? sanitize_text_field($this->options['api_key']) : sanitize_text_field(get_option('mxchat_options')['api_key']);
1524 -
1525 - /*
1526 - // Log the API key check, without exposing the key
1527 - if (defined('WP_DEBUG') && WP_DEBUG) {
1528 - error_log("Retrieved OpenAI API Key: " . ($api_key ? "Present" : "Missing"));
1529 - }
1530 - */
1531 -
1532 - if (empty($api_key)) {
1533 - //error_log("OpenAI API key is missing.");
1534 - return sanitize_text_field($user_query); // Default to the original query if API key is missing
1535 - }
1536 -
1537 - $url = 'https://api.openai.com/v1/chat/completions';
1538 - $args = [
1539 - 'headers' => [
1540 - 'Authorization' => 'Bearer ' . $api_key,
1541 - 'Content-Type' => 'application/json',
1542 - ],
1543 - 'body' => wp_json_encode([
1544 - 'model' => 'gpt-3.5-turbo',
1545 - 'messages' => [
1546 - ['role' => 'system', 'content' => $system_prompt],
1547 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
1548 - ],
1549 - 'temperature' => 0.2,
1550 - 'max_tokens' => 20,
1551 - ]),
1552 - 'method' => 'POST',
1553 - ];
1554 -
1555 - $response = wp_remote_post($url, $args);
1556 -
1557 - if (is_wp_error($response)) {
1558 - //error_log("OpenAI request failed: " . $response->get_error_message());
1559 - return sanitize_text_field($user_query); // Fallback to the original query if there's an error
1560 - }
1561 -
1562 - $body = json_decode(wp_remote_retrieve_body($response), true);
1563 -
1564 - // Check for a valid response and sanitize output
1565 - if (isset($body['choices'][0]['message']['content'])) {
1566 - $interpreted_query = sanitize_text_field(trim($body['choices'][0]['message']['content']));
1567 -
1568 - /*
1569 - // Log the interpreted query for debugging
1570 - if (defined('WP_DEBUG') && WP_DEBUG) {
1571 - error_log("Interpreted search query: " . $interpreted_query);
1572 - }
1573 - */
1574 -
1575 - return $interpreted_query;
1576 - } else {
1577 - //error_log("Unexpected API response format: " . print_r($body, true));
1578 - return sanitize_text_field($user_query);
1579 - }
1580 -}
1581 -
1582 -
1583 -
1584 -private function find_product_in_message($message) {
1585 - global $wpdb;
1586 -
1587 - // Get embedding for the search query
1588 - $query_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
1589 - if (!is_array($query_embedding)) {
1590 - return null;
1591 - }
1592 -
1593 - // Get relevant content as string
1594 - $relevant_content = $this->mxchat_find_relevant_products($query_embedding);
1595 - if (empty($relevant_content)) {
1596 - // Return null to indicate no results and set fallback response
1597 - $this->fallbackResponse['text'] = esc_html__("I couldn't find any relevant products based on your query. Could you please be more specific about the product you're looking for?", 'mxchat');
1598 - return null;
1599 - }
1600 -
1601 - // Extract product URLs from the content
1602 - preg_match_all('/https?:\/\/[^\s<>"\']+?\/product\/[^\s<>"\']+/', $relevant_content, $matches);
1603 -
1604 - if (!empty($matches[0])) {
1605 - // Try each URL found
1606 - foreach ($matches[0] as $url) {
1607 - // Clean the URL
1608 - $url = rtrim($url, '/."\']');
1609 -
1610 - // Get the product slug
1611 - $path = parse_url($url, PHP_URL_PATH);
1612 - $slug = basename(rtrim($path, '/'));
1613 -
1614 - // Find product by slug
1615 - $args = array(
1616 - 'post_type' => 'product',
1617 - 'post_status' => 'publish',
1618 - 'name' => $slug,
1619 - 'posts_per_page' => 1
1620 - );
1621 -
1622 - $products = get_posts($args);
1623 -
1624 - if (!empty($products)) {
1625 - $product_id = $products[0]->ID;
1626 - $product = wc_get_product($product_id);
1627 -
1628 - if ($product && $product->is_purchasable()) {
1629 - return $product_id;
1630 - }
1631 - }
1632 - }
1633 - }
1634 -
1635 - // Fallback: Look for product names in the content
1636 - $products = wc_get_products([
1637 - 'status' => 'publish',
1638 - 'limit' => -1,
1639 - 'return' => 'all'
1640 - ]);
1641 -
1642 - foreach ($products as $product) {
1643 - $name = $product->get_name();
1644 - if (stripos($relevant_content, $name) !== false) {
1645 - if ($product->is_purchasable()) {
1646 - return $product->get_id();
1647 - }
1648 - }
1649 - }
1650 -
1651 - // If no product is found after all checks, set the fallback response
1652 - $this->fallbackResponse['text'] = esc_html__("I couldn't find any relevant products based on your query. Try to be more specific", 'mxchat');
1653 - return null;
1654 -}
1655 -
1656 -// New method to handle intent responses
1657 -private function generate_intent_response($context_content, $session_id) {
1658 - // Convert the context array to a structured string for the AI
1659 - $context_string = $this->format_intent_context($context_content);
1660 -
1661 - // Generate AI response using the context
1662 - $response = $this->mxchat_generate_response(
1663 - $context_string,
1664 - $this->options['api_key'],
1665 - $this->options['xai_api_key'],
1666 - $this->options['claude_api_key'],
1667 - $this->options['deepseek_api_key'],
1668 - $this->mxchat_fetch_conversation_history_for_ai($session_id)
1669 - );
1670 -
1671 - $this->fallbackResponse['text'] = $response;
1672 - return true;
1673 -}
1674 -// Helper method to format intent context
1675 -private function format_intent_context($context) {
1676 - $context_string = esc_html__("INTENT CONTEXT:\n", 'mxchat');
1677 -
1678 - switch ($context['intent']) {
1679 - case 'add_to_cart':
1680 - if ($context['status'] === 'success') {
1681 - $context_string .= esc_html__("Action: Successfully added product to cart\n", 'mxchat');
1682 - $context_string .= sprintf(esc_html__("Product: %s\n", 'mxchat'), $context['product']['name']);
1683 - $context_string .= esc_html__("Available actions: ", 'mxchat') . implode(', ', $context['available_actions']) . "\n";
1684 - $context_string .= sprintf(esc_html__("Cart URL: %s\n", 'mxchat'), $context['cart_url']);
1685 - $context_string .= esc_html__("\nPlease inform the user of the successful addition and their available options.", 'mxchat');
1686 - } else {
1687 - $context_string .= esc_html__("Action: Failed to add product to cart\n", 'mxchat');
1688 - $context_string .= sprintf(esc_html__("Reason: %s\n", 'mxchat'), $context['reason']);
1689 - switch ($context['reason']) {
1690 - case 'woocommerce_not_available':
1691 - $context_string .= esc_html__("\nPlease inform the user that shopping features are not available.", 'mxchat');
1692 - break;
1693 - case 'no_product_context':
1694 - $context_string .= esc_html__("\nPlease ask the user to specify which product they want to add.", 'mxchat');
1695 - break;
1696 - case 'product_not_found':
1697 - $context_string .= esc_html__("\nPlease inform the user that the product couldn't be found and ask them to try again.", 'mxchat');
1698 - break;
1699 - case 'add_to_cart_failed':
1700 - $context_string .= esc_html__("\nPlease apologize to the user and suggest they try again or ask for assistance.", 'mxchat');
1701 - break;
1702 - }
1703 - }
1704 - break;
1705 - }
1706 -
1707 - return $context_string;
1708 -}
1709 -
1710 -
1711 -//very good
1712 -private function add_email_to_loops($email) {
1713 - // Sanitize the email
1714 - $email = sanitize_email($email);
1715 -
1716 - // Retrieve and sanitize options
1717 - $api_key = isset($this->options['loops_api_key']) ? sanitize_text_field($this->options['loops_api_key']) : '';
1718 - $mailing_list_id = isset($this->options['loops_mailing_list']) ? sanitize_text_field($this->options['loops_mailing_list']) : '';
1719 -
1720 - // Check for missing API key or mailing list ID
1721 - if (empty($api_key) || empty($mailing_list_id)) {
1722 - //error_log(esc_html__('Loops API key or mailing list ID is missing.', 'mxchat'));
1723 - return;
1724 - }
1725 -
1726 - $data = array(
1727 - 'email' => $email,
1728 - 'subscribed' => true,
1729 - 'source' => __('MxChat AI Chatbot', 'mxchat'),
1730 - 'mailingLists' => array($mailing_list_id => true),
1731 - );
1732 -
1733 - $url = 'https://app.loops.so/api/v1/contacts/create';
1734 - $args = array(
1735 - 'body' => wp_json_encode($data),
1736 - 'headers' => array(
1737 - 'Authorization' => 'Bearer ' . $api_key,
1738 - 'Content-Type' => 'application/json',
1739 - ),
1740 - 'method' => 'POST',
1741 - 'timeout' => 45,
1742 - );
1743 -
1744 - $response = wp_remote_post($url, $args);
1745 -
1746 - // Handle errors in the API request
1747 - if (is_wp_error($response)) {
1748 - //error_log(esc_html__('Error adding email to Loops: ', 'mxchat') . $response->get_error_message());
1749 - return;
1750 - }
1751 -
1752 - // Check for non-200 HTTP responses
1753 - $response_code = wp_remote_retrieve_response_code($response);
1754 - if ($response_code != 200) {
1755 - $response_body = wp_remote_retrieve_body($response);
1756 - //error_log(esc_html__('Loops API responded with code ', 'mxchat') . $response_code . ': ' . $response_body);
1757 - }
1758 -}
1759 -
1760 -public function mxchat_handle_pdf_discussion($message, $user_id, $session_id) {
1761 - // Get the maximum number of pages allowed from admin settings
1762 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
1763 -
1764 - // Retrieve options for dynamic texts
1765 - $trigger_text = $this->options['pdf_intent_trigger_text'] ?? __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
1766 - $success_text = $this->options['pdf_intent_success_text'] ?? __("I've processed the PDF. What questions do you have about it?", 'mxchat');
1767 - $error_text = $this->options['pdf_intent_error_text'] ?? __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
1768 -
1769 - // Check for explicit request for new PDF
1770 - $new_pdf_requested = stripos($message, 'new') !== false ||
1771 - stripos($message, 'another') !== false ||
1772 - stripos($message, 'different') !== false;
1773 -
1774 - // If user mentions adding/reading a PDF, set waiting flag
1775 - if (stripos($message, 'pdf') !== false ||
1776 - stripos($message, 'document') !== false ||
1777 - stripos($message, 'read') !== false) {
1778 - set_transient('mxchat_waiting_for_pdf_url_' . $session_id, true, HOUR_IN_SECONDS);
1779 - $this->fallbackResponse['text'] = $trigger_text;
1780 - return;
1781 - }
1782 -
1783 - // If we're waiting for a URL or user requested new PDF
1784 - if ($new_pdf_requested || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
1785 - if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
1786 - // Process URL... (rest of your existing URL processing code)
1787 - } else {
1788 - $this->fallbackResponse['text'] = $trigger_text;
1789 - }
1790 - return;
1791 - }
1792 -
1793 - // Default to proceeding with conversation if no specific PDF action is needed
1794 - $this->fallbackResponse['text'] = '';
1795 -}
1796 -private function fetch_and_split_pdf_pages($pdf_source, $max_pages) {
1797 - $upload_dir = wp_upload_dir();
1798 - $temp_file = null;
1799 -
1800 - try {
1801 - // Handle URL vs local file
1802 - if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
1803 - // Validate and download the file from URL
1804 - $temp_file = wp_tempnam($pdf_source); // Safe temporary file name
1805 - $response = wp_remote_get($pdf_source, ['timeout' => 60]);
1806 -
1807 - if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
1808 - //error_log(esc_html__("Failed to download PDF. Error: ", 'mxchat') . print_r($response, true));
1809 - return false;
1810 - }
1811 -
1812 - file_put_contents($temp_file, wp_remote_retrieve_body($response));
1813 -
1814 - // Validate that the downloaded file is a PDF
1815 - $mime_type = mime_content_type($temp_file);
1816 - if ($mime_type !== 'application/pdf') {
1817 - //error_log(esc_html__("Invalid MIME type detected for PDF: ", 'mxchat') . $mime_type);
1818 - unlink($temp_file);
1819 - return false;
1820 - }
1821 - } else {
1822 - // For local files, use the provided path directly
1823 - $temp_file = $pdf_source;
1824 - }
1825 -
1826 - // Parse and process the PDF
1827 - $parser = new \Smalot\PdfParser\Parser();
1828 - $pdf = $parser->parseFile($temp_file);
1829 - $pages = $pdf->getPages();
1830 -
1831 - if (count($pages) > $max_pages) {
1832 - //error_log(esc_html__("PDF exceeds the maximum allowed pages: ", 'mxchat') . count($pages));
1833 - if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
1834 - unlink($temp_file);
1835 - }
1836 - return esc_html__('too_many_pages', 'mxchat');
1837 - }
1838 -
1839 - $embeddings = [];
1840 - foreach ($pages as $page_number => $page) {
1841 - $text = $page->getText();
1842 -
1843 - // Ensure text is non-empty before generating embeddings
1844 - if (empty(trim($text))) {
1845 - //error_log(esc_html__("Skipping empty page: ", 'mxchat') . ($page_number + 1));
1846 - continue;
1847 - }
1848 -
1849 - $embedding = $this->mxchat_generate_embedding(
1850 - esc_html__("Page ", 'mxchat') . ($page_number + 1) . ": " . $text,
1851 - $this->options['api_key']
1852 - );
1853 -
1854 - if ($embedding) {
1855 - $embeddings[] = [
1856 - 'page_number' => $page_number + 1,
1857 - 'embedding' => $embedding,
1858 - 'text' => $text,
1859 - ];
1860 - } else {
1861 - //error_log(esc_html__("Failed to generate embedding for page ", 'mxchat') . ($page_number + 1));
1862 - }
1863 - }
1864 -
1865 - // Clean up downloaded file if it was from URL
1866 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file) {
1867 - unlink($temp_file);
1868 - }
1869 -
1870 - return $embeddings;
1871 -
1872 - } catch (\Exception $e) {
1873 - // error_log(esc_html__("Error parsing or processing PDF: ", 'mxchat') . $e->getMessage());
1874 -
1875 - // Cleanup in case of exception
1876 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
1877 - unlink($temp_file);
1878 - }
1879 -
1880 - return false;
1881 - }
1882 -}
1883 -private function find_relevant_pdf_pages($query_embedding, $embeddings) {
1884 - //error_log(esc_html__("find_relevant_pdf_pages called.", 'mxchat'));
1885 -
1886 - $most_relevant = null;
1887 - $highest_similarity = -INF;
1888 -
1889 - foreach ($embeddings as $page_data) {
1890 - $similarity = $this->mxchat_calculate_cosine_similarity($query_embedding, $page_data['embedding']);
1891 -
1892 - if ($similarity > $highest_similarity) {
1893 - $highest_similarity = $similarity;
1894 - $most_relevant = $page_data['page_number'];
1895 - }
1896 - }
1897 -
1898 - if (!is_null($most_relevant)) {
1899 - $page_numbers = range(max(1, $most_relevant - 1), min(count($embeddings), $most_relevant + 1));
1900 - return array_filter($embeddings, function ($page) use ($page_numbers) {
1901 - return in_array($page['page_number'], $page_numbers);
1902 - });
1903 - }
1904 -
1905 - return [];
1906 -}
1907 -// Add this to your class
1908 -public function handle_pdf_upload() {
1909 - check_ajax_referer('mxchat_chat_nonce', 'nonce');
1910 -
1911 - if (!isset($_FILES['pdf_file']) || !isset($_POST['session_id'])) {
1912 - wp_send_json_error(esc_html__('Missing required parameters.', 'mxchat'));
1913 - return;
1914 - }
1915 -
1916 - $file = $_FILES['pdf_file'];
1917 - $session_id = sanitize_text_field($_POST['session_id']);
1918 - $original_filename = sanitize_text_field($file['name']);
1919 -
1920 - $file_type = wp_check_filetype($file['name'], ['pdf' => 'application/pdf']);
1921 - if ($file_type['type'] !== 'application/pdf') {
1922 - wp_send_json_error(esc_html__('Invalid file type. Only PDF files are allowed.', 'mxchat'));
1923 - return;
1924 - }
1925 -
1926 - $upload_dir = wp_upload_dir();
1927 - $pdf_filename = 'mxchat_' . $session_id . '_' . time() . '.pdf';
1928 - $pdf_path = $upload_dir['path'] . '/' . $pdf_filename;
1929 -
1930 - if (!move_uploaded_file($file['tmp_name'], $pdf_path)) {
1931 - wp_send_json_error(esc_html__('Failed to upload file.', 'mxchat'));
1932 - return;
1933 - }
1934 -
1935 - $this->clear_pdf_transients($session_id);
1936 -
1937 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
1938 - $embeddings = $this->fetch_and_split_pdf_pages($pdf_path, $max_pages);
1939 -
1940 - if ($embeddings === 'too_many_pages') {
1941 - unlink($pdf_path);
1942 - $error_message = sprintf(
1943 - $this->options['pdf_intent_error_text'] ??
1944 - esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
1945 - $max_pages
1946 - );
1947 - wp_send_json_error($error_message);
1948 - return;
1949 - }
1950 -
1951 - if ($embeddings === false || empty($embeddings)) {
1952 - unlink($pdf_path);
1953 - $error_message = $this->options['pdf_intent_error_text'] ??
1954 - esc_html__('The uploaded PDF appears to be empty or contains unsupported content.', 'mxchat');
1955 - wp_send_json_error($error_message);
1956 - return;
1957 - }
1958 -
1959 - if (!empty($embeddings)) {
1960 - set_transient('mxchat_pdf_url_' . $session_id, $pdf_path, HOUR_IN_SECONDS);
1961 - set_transient('mxchat_pdf_filename_' . $session_id, $original_filename, HOUR_IN_SECONDS);
1962 - set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
1963 - set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
1964 -
1965 - $success_message = $this->options['pdf_intent_success_text'] ??
1966 - esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat');
1967 -
1968 - wp_send_json_success([
1969 - 'message' => $success_message,
1970 - 'filename' => $original_filename
1971 - ]);
1972 - return;
1973 - }
1974 -
1975 - unlink($pdf_path);
1976 - $error_message = $this->options['pdf_intent_error_text'] ??
1977 - esc_html__('Sorry, I couldn\'t process the PDF. Please ensure it\'s a valid file.', 'mxchat');
1978 - wp_send_json_error($error_message);
1979 - return;
1980 -}
1981 -public function handle_pdf_remove() {
1982 - check_ajax_referer('mxchat_chat_nonce', 'nonce');
1983 -
1984 - if (empty($_POST['session_id'])) {
1985 - wp_send_json_error(esc_html__('Session ID missing.', 'mxchat'));
1986 - wp_die();
1987 - }
1988 -
1989 - $session_id = sanitize_text_field($_POST['session_id']);
1990 - $pdf_path = get_transient('mxchat_pdf_url_' . $session_id);
1991 -
1992 - if ($pdf_path && file_exists($pdf_path)) {
1993 - unlink($pdf_path);
1994 - }
1995 -
1996 - $this->clear_pdf_transients($session_id);
1997 -
1998 - wp_send_json_success([
1999 - 'message' => esc_html__('PDF removed successfully.', 'mxchat')
2000 - ]);
2001 - wp_die();
2002 -}
2003 -
2004 -
2005 -
2006 -
2007 -function mxchat_fetch_new_messages() {
2008 - $session_id = sanitize_text_field($_POST['session_id']);
2009 - $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
2010 - $persistence_enabled = $_POST['persistence_enabled'] === 'true';
2011 - $initial_timestamp = isset($_POST['initial_timestamp']) ? intval($_POST['initial_timestamp']) : 0;
2012 -
2013 - if (empty($session_id)) {
2014 - //error_log(esc_html__('Fetch new messages error: Session ID missing.', 'mxchat'));
2015 - wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
2016 - wp_die();
2017 - }
2018 -
2019 - $history = get_option("mxchat_history_{$session_id}", []);
2020 -
2021 - $new_messages = array_filter($history, function ($message) use ($last_seen_id, $persistence_enabled, $initial_timestamp) {
2022 - // If persistence is enabled, show all new messages
2023 - if ($persistence_enabled) {
2024 - return !empty($message['id']) &&
2025 - strcmp($message['id'], $last_seen_id) > 0 &&
2026 - $message['role'] === 'agent';
2027 - }
2028 -
2029 - // If persistence is disabled, only show messages after initial timestamp
2030 - return !empty($message['id']) &&
2031 - $message['role'] === 'agent' &&
2032 - $message['timestamp'] > $initial_timestamp;
2033 - });
2034 -
2035 - //error_log(esc_html__("New agent messages fetched for session $session_id. Last seen ID: $last_seen_id", 'mxchat'));
2036 -
2037 - wp_send_json_success([
2038 - 'new_messages' => array_values($new_messages)
2039 - ]);
2040 - wp_die();
2041 -}
2042 -
2043 -
2044 -public function mxchat_live_agent_handover($message, $user_id, $session_id) {
2045 - // First check if live agents are available
2046 - $live_agent_available = $this->options['live_agent_status'] ?? 'off';
2047 - if ($live_agent_available !== 'on') {
2048 - $away_message = $this->options['live_agent_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
2049 - $this->fallbackResponse = [
2050 - 'text' => $away_message,
2051 - 'html' => '',
2052 - 'images' => [],
2053 - 'chat_mode' => 'ai'
2054 - ];
2055 - wp_send_json([
2056 - 'text' => $away_message,
2057 - 'html' => '',
2058 - 'chat_mode' => 'ai',
2059 - 'session_id' => $session_id
2060 - ]);
2061 - wp_die();
2062 - }
2063 -
2064 - $slack_webhook_url = $this->options['live_agent_webhook_url'] ?? '';
2065 - if (empty($slack_webhook_url)) {
2066 - return false;
2067 - }
2068 -
2069 - // Get recent chat history (last 5 messages)
2070 - $history = get_option("mxchat_history_{$session_id}", []);
2071 - $recent_history = array_slice($history, -5); // Get last 5 messages
2072 -
2073 - // Format conversation history
2074 - $conversation_context = "";
2075 - if (!empty($recent_history)) {
2076 - $conversation_context = "*Recent Conversation:*\n";
2077 - foreach ($recent_history as $hist_message) {
2078 - $role_display = $hist_message['role'] === 'user' ? 'User' : 'AI';
2079 - $conversation_context .= ">{$role_display}: {$hist_message['content']}\n";
2080 - }
2081 - $conversation_context .= "\n";
2082 - }
2083 -
2084 - update_option("mxchat_mode_{$session_id}", 'agent');
2085 -
2086 - $webhook_data = [
2087 - 'blocks' => [
2088 - [
2089 - 'type' => 'header',
2090 - 'text' => [
2091 - 'type' => 'plain_text',
2092 - 'text' => '🔔 New Live Agent Request',
2093 - 'emoji' => true
2094 - ]
2095 - ],
2096 - [
2097 - 'type' => 'section',
2098 - 'fields' => [
2099 - [
2100 - 'type' => 'mrkdwn',
2101 - 'text' => sprintf('*User ID:*\n`%s`', $user_id)
2102 - ],
2103 - [
2104 - 'type' => 'mrkdwn',
2105 - 'text' => sprintf('*Session ID:*\n`%s`', $session_id)
2106 - ]
2107 - ]
2108 - ]
2109 - ]
2110 - ];
2111 -
2112 - // Add conversation history if exists
2113 - if (!empty($conversation_context)) {
2114 - $webhook_data['blocks'][] = [
2115 - 'type' => 'section',
2116 - 'text' => [
2117 - 'type' => 'mrkdwn',
2118 - 'text' => $conversation_context
2119 - ]
2120 - ];
2121 - }
2122 -
2123 - // Add the current message
2124 - $webhook_data['blocks'][] = [
2125 - 'type' => 'section',
2126 - 'text' => [
2127 - 'type' => 'mrkdwn',
2128 - 'text' => sprintf('*Current Message:*\n%s', $message)
2129 - ]
2130 - ];
2131 -
2132 - // Add the reply button
2133 - $webhook_data['blocks'][] = [
2134 - 'type' => 'actions',
2135 - 'elements' => [
2136 - [
2137 - 'type' => 'button',
2138 - 'text' => [
2139 - 'type' => 'plain_text',
2140 - 'text' => '✍️ Reply',
2141 - 'emoji' => true
2142 - ],
2143 - 'value' => $session_id,
2144 - 'action_id' => 'reply_to_user',
2145 - 'style' => 'primary'
2146 - ]
2147 - ]
2148 - ];
2149 -
2150 - $response = wp_remote_post($slack_webhook_url, [
2151 - 'body' => json_encode($webhook_data),
2152 - 'headers' => [
2153 - 'Content-Type' => 'application/json',
2154 - ],
2155 - ]);
2156 -
2157 - if (is_wp_error($response)) {
2158 - return false;
2159 - }
2160 -
2161 - $success_message = $this->options['live_agent_notification_message'] ?? 'Live agent has been notified.';
2162 - $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
2163 -
2164 - $this->fallbackResponse = [
2165 - 'text' => $success_message,
2166 - 'html' => '',
2167 - 'images' => [],
2168 - 'chat_mode' => 'agent'
2169 - ];
2170 -
2171 - wp_send_json([
2172 - 'success' => true,
2173 - 'text' => $success_message,
2174 - 'html' => '',
2175 - 'chat_mode' => 'agent',
2176 - 'session_id' => $session_id,
2177 - 'fallbackResponse' => $this->fallbackResponse
2178 - ]);
2179 - wp_die();
2180 -}
2181 -public function mxchat_send_user_message_to_agent($message, $user_id, $session_id) {
2182 - $slack_webhook_url = $this->options['live_agent_webhook_url'] ?? '';
2183 -
2184 - if (empty($slack_webhook_url)) {
2185 - //error_log(esc_html__('Slack Webhook URL is not configured.', 'mxchat'));
2186 - return false;
2187 - }
2188 -
2189 - $webhook_data = [
2190 - 'blocks' => [
2191 - [
2192 - 'type' => 'header',
2193 - 'text' => [
2194 - 'type' => 'plain_text',
2195 - 'text' => esc_html__('📩 New Chat Message', 'mxchat'),
2196 - 'emoji' => true
2197 - ]
2198 - ],
2199 - [
2200 - 'type' => 'section',
2201 - 'fields' => [
2202 - [
2203 - 'type' => 'mrkdwn',
2204 - 'text' => sprintf(esc_html__('*User ID:*\n`%s`', 'mxchat'), $user_id)
2205 - ],
2206 - [
2207 - 'type' => 'mrkdwn',
2208 - 'text' => sprintf(esc_html__('*Session ID:*\n`%s`', 'mxchat'), $session_id)
2209 - ]
2210 - ]
2211 - ],
2212 - [
2213 - 'type' => 'section',
2214 - 'text' => [
2215 - 'type' => 'mrkdwn',
2216 - 'text' => sprintf(esc_html__('*Message:*\n%s', 'mxchat'), $message)
2217 - ]
2218 - ],
2219 - [
2220 - 'type' => 'actions',
2221 - 'elements' => [
2222 - [
2223 - 'type' => 'button',
2224 - 'text' => [
2225 - 'type' => 'plain_text',
2226 - 'text' => esc_html__('✍️ Reply', 'mxchat'),
2227 - 'emoji' => true
2228 - ],
2229 - 'value' => $session_id,
2230 - 'action_id' => 'reply_to_user',
2231 - 'style' => 'primary'
2232 - ]
2233 - ]
2234 - ]
2235 - ]
2236 - ];
2237 -
2238 - $response = wp_remote_post($slack_webhook_url, [
2239 - 'body' => json_encode($webhook_data),
2240 - 'headers' => [
2241 - 'Content-Type' => 'application/json',
2242 - ],
2243 - ]);
2244 -
2245 - if (is_wp_error($response)) {
2246 - //error_log(esc_html__('Error sending message to Slack: ', 'mxchat') . $response->get_error_message());
2247 - return false;
2248 - }
2249 -
2250 - //error_log(esc_html__('Message sent to Slack successfully.', 'mxchat'));
2251 - return true;
2252 -}
2253 -public function handle_slack_interaction(WP_REST_Request $request) {
2254 - //error_log('Received Slack interaction');
2255 -
2256 - $payload = json_decode($request->get_param('payload'), true);
2257 - //error_log('Payload: ' . print_r($payload, true));
2258 -
2259 - // Handle button click
2260 - if ($payload['type'] === 'block_actions' && $payload['actions'][0]['action_id'] === 'reply_to_user') {
2261 - $session_id = $payload['actions'][0]['value'];
2262 - $trigger_id = $payload['trigger_id'];
2263 -
2264 - // Get Bot Token from settings
2265 - $slack_token = $this->options['live_agent_bot_token'] ?? '';
2266 -
2267 - if (empty($slack_token)) {
2268 - //error_log('Slack Bot Token not configured');
2269 - return new WP_REST_Response(['error' => esc_html__('Bot token not configured', 'mxchat')], 400);
2270 - }
2271 - $response = wp_remote_post('https://slack.com/api/views.open', [
2272 - 'headers' => [
2273 - 'Content-Type' => 'application/json',
2274 - 'Authorization' => 'Bearer ' . $slack_token
2275 - ],
2276 - 'body' => json_encode([
2277 - 'trigger_id' => $trigger_id,
2278 - 'view' => [
2279 - 'type' => 'modal',
2280 - 'callback_id' => 'reply_modal',
2281 - 'title' => [
2282 - 'type' => 'plain_text',
2283 - 'text' => __('Reply to User', 'mxchat')
2284 - ],
2285 - 'submit' => [
2286 - 'type' => 'plain_text',
2287 - 'text' => __('Send', 'mxchat')
2288 - ],
2289 - 'close' => [
2290 - 'type' => 'plain_text',
2291 - 'text' => __('Cancel', 'mxchat')
2292 - ],
2293 - 'blocks' => [
2294 - [
2295 - 'type' => 'input',
2296 - 'block_id' => 'reply_block',
2297 - 'label' => [
2298 - 'type' => 'plain_text',
2299 - 'text' => sprintf(__('Reply to session: %s', 'mxchat'), $session_id)
2300 - ],
2301 - 'element' => [
2302 - 'type' => 'plain_text_input',
2303 - 'action_id' => 'message',
2304 - 'multiline' => true,
2305 - 'placeholder' => [
2306 - 'type' => 'plain_text',
2307 - 'text' => __('Type your message here...', 'mxchat')
2308 - ]
2309 - ]
2310 - ]
2311 - ],
2312 - 'private_metadata' => $session_id
2313 - ]
2314 - ])
2315 - ]);
2316 -
2317 - //error_log('Views.open response: ' . print_r($response, true));
2318 -
2319 - // Return immediate acknowledgment
2320 - return new WP_REST_Response(['ok' => true]);
2321 - }
2322 -
2323 - // Handle modal submission
2324 -// Handle modal submission
2325 -if ($payload['type'] === 'view_submission') {
2326 - $session_id = $payload['view']['private_metadata'];
2327 - $message = $payload['view']['state']['values']['reply_block']['message']['value'];
2328 -
2329 - // Save the message (keep the message_id but don't include in response)
2330 - $this->mxchat_save_chat_message($session_id, 'agent', $message);
2331 -
2332 - // Keep the original response format for Slack
2333 - return new WP_REST_Response([
2334 - 'response_action' => 'clear'
2335 - ]);
2336 -}
2337 -
2338 - // Default acknowledgment
2339 - return new WP_REST_Response(['ok' => true]);
2340 -}
2341 -
2342 -public function mxchat_handle_agent_response(WP_REST_Request $request) {
2343 - //error_log('Received agent response request');
2344 - //error_log('Request data: ' . print_r($request->get_params(), true));
2345 - // error_log('Raw body: ' . file_get_contents('php://input'));
2346 -
2347 - // Get the data from Slack's slash command format
2348 - $command_text = $request->get_param('text');
2349 - // error_log('Command text: ' . $command_text);
2350 -
2351 - if (empty($command_text)) {
2352 - //error_log(esc_html__('Agent response error: No command text received', 'mxchat'));
2353 - return new WP_REST_Response([
2354 - 'error' => esc_html__('Command text is required. Format: /reply session_id message', 'mxchat')
2355 - ], 400);
2356 - }
2357 -
2358 - // Split the command text into session_id and message
2359 - $parts = explode(' ', $command_text, 2);
2360 - if (count($parts) !== 2) {
2361 - //error_log('Agent response error: Invalid command format');
2362 - return new WP_REST_Response([
2363 - 'error' => esc_html__('Invalid format. Use: /reply session_id message', 'mxchat')
2364 - ], 400);
2365 - }
2366 -
2367 - $session_id = sanitize_text_field($parts[0]);
2368 - $message = sanitize_text_field($parts[1]);
2369 -
2370 - //error_log("Processing agent response - Session ID: $session_id, Message: $message");
2371 -
2372 - // Save the message
2373 - $message_id = $this->mxchat_save_chat_message($session_id, 'agent', $message);
2374 -
2375 - if (!$message_id) {
2376 - // error_log('Failed to save agent message');
2377 - return new WP_REST_Response([
2378 - 'error' => esc_html__('Failed to save message', 'mxchat')
2379 - ], 500);
2380 - }
2381 -
2382 - // Return success response in Slack's expected format
2383 - return new WP_REST_Response([
2384 - 'response_type' => 'in_channel',
2385 - 'text' => esc_html__("Message sent successfully to session $session_id", 'mxchat')
2386 - ], 200);
2387 -}
2388 -
2389 -
2390 -public function mxchat_handle_switch_to_chatbot_intent($message, $user_id, $session_id) {
2391 - //error_log(esc_html__("Switching back to chatbot mode via intent.", 'mxchat'));
2392 -
2393 - // Just update mode to AI
2394 - update_option("mxchat_mode_{$session_id}", 'ai');
2395 -
2396 - // Initialize states
2397 - $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
2398 - $this->productCardHtml = '';
2399 -
2400 - // Set the response message
2401 - $this->fallbackResponse['text'] = esc_html__('You are now chatting with the AI chatbot.', 'mxchat');
2402 -
2403 - return true; // Intent was handled
2404 -}
2405 -
2406 -
2407 -
2408 -
2409 -// For the word upload handler
2410 -public function mxchat_handle_word_upload() {
2411 - // Delegate to word handler
2412 - $this->word_handler->mxchat_handle_word_upload();
2413 -}
2414 -
2415 -// For the word removal handler
2416 -public function mxchat_handle_word_remove() {
2417 - // Delegate to word handler
2418 - $this->word_handler->mxchat_handle_word_remove();
2419 -}
2420 -
2421 -// For the word status check
2422 -public function mxchat_check_word_status() {
2423 - // Delegate to word handler
2424 - $this->word_handler->mxchat_check_word_status();
2425 -}
2426 -
2427 -
2428 -private function mxchat_get_user_identifier() {
2429 - return MxChat_User::mxchat_get_user_identifier();
2430 -}
2431 -
2432 -private function mxchat_generate_embedding($text, $api_key) {
2433 - $endpoint = 'https://api.openai.com/v1/embeddings';
2434 -
2435 - $body = wp_json_encode([
2436 - 'input' => $text,
2437 - 'model' => 'text-embedding-ada-002'
2438 - ]);
2439 -
2440 - $args = [
2441 - 'body' => $body,
2442 - 'headers' => [
2443 - 'Content-Type' => 'application/json',
2444 - 'Authorization' => 'Bearer ' . $api_key,
2445 - ],
2446 - 'timeout' => 60,
2447 - 'redirection' => 5,
2448 - 'blocking' => true,
2449 - 'httpversion' => '1.0',
2450 - 'sslverify' => true,
2451 - ];
2452 -
2453 - $response = wp_remote_post($endpoint, $args);
2454 -
2455 - if (is_wp_error($response)) {
2456 - return null;
2457 - }
2458 -
2459 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
2460 -
2461 - if (isset($response_body['data'][0]['embedding']) && is_array($response_body['data'][0]['embedding'])) {
2462 - return $response_body['data'][0]['embedding'];
2463 - } else {
2464 - return null;
2465 - }
2466 - }
2467 -
2468 -
2469 -private function mxchat_find_relevant_content($user_embedding) {
2470 - //error_log('MXChat Vector Search: Starting content search...');
2471 -
2472 - // Retrieve the add-on settings from the database.
2473 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
2474 -
2475 - // Determine whether Pinecone is enabled.
2476 - // We expect the sanitized setting to be a string '1' if enabled, otherwise '0'.
2477 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
2478 -
2479 - //error_log('Pinecone enabled flag: ' . $use_pinecone);
2480 -
2481 - if ($use_pinecone === 1) {
2482 - //error_log('MXChat Vector Search: Using Pinecone database');
2483 - return $this->find_relevant_content_pinecone($user_embedding);
2484 - } else {
2485 - //error_log('MXChat Vector Search: Using WordPress database');
2486 - return $this->find_relevant_content_wordpress($user_embedding);
2487 - }
2488 -}
2489 -
2490 -private function find_relevant_content_wordpress($user_embedding) {
2491 - global $wpdb;
2492 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
2493 - $cache_key = 'mxchat_system_prompt_embeddings';
2494 - $batch_size = 500;
2495 -
2496 - // Retrieve embeddings from cache or database
2497 - $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
2498 - if ($embeddings === false) {
2499 - $embeddings = [];
2500 - $offset = 0;
2501 -
2502 - // Load in batches and build cache
2503 - do {
2504 - $query = $wpdb->prepare(
2505 - "SELECT id, embedding_vector
2506 - FROM {$system_prompt_table}
2507 - LIMIT %d OFFSET %d",
2508 - $batch_size,
2509 - $offset
2510 - );
2511 -
2512 - $batch = $wpdb->get_results($query);
2513 - if (empty($batch)) {
2514 - break;
2515 - }
2516 -
2517 - $embeddings = array_merge($embeddings, $batch);
2518 - $offset += $batch_size;
2519 -
2520 - // Free memory
2521 - unset($batch);
2522 -
2523 - } while (true);
2524 -
2525 - if (empty($embeddings)) {
2526 - return ''; // Return an empty string if no embeddings found
2527 - }
2528 - wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
2529 - }
2530 -
2531 - // Initialize array to store relevant results with similarity scores
2532 - $relevant_results = [];
2533 - // Iterate through embeddings to calculate similarity
2534 - foreach ($embeddings as $embedding) {
2535 - $database_embedding = $embedding->embedding_vector
2536 - ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
2537 - : null;
2538 - if (is_array($database_embedding) && is_array($user_embedding)) {
2539 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
2540 - $relevant_results[] = [
2541 - 'id' => $embedding->id,
2542 - 'similarity' => $similarity
2543 - ];
2544 - }
2545 - // Free memory
2546 - unset($database_embedding);
2547 - }
2548 -
2549 - // Retrieve the similarity threshold
2550 - $similarity_threshold = ((int) get_option('mxchat_similarity_threshold', 80)) / 100;
2551 -
2552 - // Filter and sort relevant results by similarity
2553 - $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
2554 - return $result['similarity'] >= $similarity_threshold;
2555 - });
2556 - usort($relevant_results, function ($a, $b) {
2557 - return $b['similarity'] <=> $a['similarity'];
2558 - });
2559 -
2560 - // Limit to the top 5 results
2561 - $top_results = array_slice($relevant_results, 0, 5);
2562 -
2563 - // Initialize the final content
2564 - $content = '';
2565 -
2566 - // Fetch and combine content for the top results
2567 - foreach ($top_results as $result) {
2568 - $chunk_content = $this->fetch_content_with_product_links($result['id']);
2569 - // Check if the content is PDF-related and add surrounding pages
2570 - if (strpos($chunk_content, '{"document_type":"pdf"') !== false) {
2571 - $surrounding_content = $wpdb->get_results($wpdb->prepare(
2572 - "SELECT article_content FROM {$system_prompt_table}
2573 - WHERE id IN (
2574 - (SELECT id FROM {$system_prompt_table} WHERE id < %d ORDER BY id DESC LIMIT 1),
2575 - (SELECT id FROM {$system_prompt_table} WHERE id > %d ORDER BY id ASC LIMIT 1)
2576 - )",
2577 - $result['id'],
2578 - $result['id']
2579 - ));
2580 - // Add previous content if it exists
2581 - if (!empty($surrounding_content[0])) {
2582 - $content .= $surrounding_content[0]->article_content . "\n\n";
2583 - }
2584 - // Add the main chunk content
2585 - $content .= $chunk_content . "\n\n";
2586 - // Add next content if it exists
2587 - if (!empty($surrounding_content[1])) {
2588 - $content .= $surrounding_content[1]->article_content . "\n\n";
2589 - }
2590 - } else {
2591 - // For non-PDF content, add directly
2592 - $content .= $chunk_content . "\n\n";
2593 - }
2594 - }
2595 -
2596 - return trim($content);
2597 -}
2598 -/**
2599 - * Find relevant content in Pinecone vector database
2600 - */
2601 -private function find_relevant_content_pinecone($user_embedding) {
2602 - $options = get_option('mxchat_pinecone_addon_options', array());
2603 - $api_key = $options['mxchat_pinecone_api_key'] ?? '';
2604 - $host = $options['mxchat_pinecone_host'] ?? '';
2605 -
2606 - if (empty($host) || empty($api_key)) {
2607 - //error_log('Pinecone credentials not properly configured');
2608 - return '';
2609 - }
2610 -
2611 - // Get similarity threshold from WordPress settings
2612 - $similarity_threshold = ((int) get_option('mxchat_similarity_threshold', 80)) / 100;
2613 -
2614 - // Prepare the query request for Pinecone
2615 - $api_endpoint = "https://{$host}/query";
2616 -
2617 - $request_body = array(
2618 - 'vector' => $user_embedding,
2619 - 'topK' => 5,
2620 - 'includeMetadata' => true,
2621 - 'includeValues' => true
2622 - );
2623 -
2624 - $response = wp_remote_post($api_endpoint, array(
2625 - 'headers' => array(
2626 - 'Api-Key' => $api_key,
2627 - 'accept' => 'application/json',
2628 - 'content-type' => 'application/json'
2629 - ),
2630 - 'body' => wp_json_encode($request_body),
2631 - 'timeout' => 30
2632 - ));
2633 -
2634 - if (is_wp_error($response)) {
2635 - //error_log('Pinecone query error: ' . $response->get_error_message());
2636 - return '';
2637 - }
2638 -
2639 - $response_code = wp_remote_retrieve_response_code($response);
2640 - if ($response_code !== 200) {
2641 - //error_log('Pinecone API error: ' . wp_remote_retrieve_body($response));
2642 - return '';
2643 - }
2644 -
2645 - $results = json_decode(wp_remote_retrieve_body($response), true);
2646 - if (empty($results['matches'])) {
2647 - return '';
2648 - }
2649 -
2650 - // Initialize the final content
2651 - $content = '';
2652 -
2653 - // Process each match
2654 - foreach ($results['matches'] as $match) {
2655 - // Skip if similarity is below threshold
2656 - if ($match['score'] < $similarity_threshold) {
2657 - continue;
2658 - }
2659 -
2660 - if (!empty($match['metadata']['text']) && !empty($match['metadata']['source_url'])) {
2661 - // Add content with citation
2662 - $content .= $match['metadata']['text'] . "\n";
2663 - $content .= "Source: " . $match['metadata']['source_url'] . "\n\n";
2664 - }
2665 - }
2666 -
2667 - return trim($content);
2668 -}
2669 -
2670 -
2671 -private function mxchat_find_relevant_products($user_embedding) {
2672 - //error_log('MXChat Vector Search: Starting product search...');
2673 -
2674 - // Retrieve the add-on settings from the database
2675 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
2676 -
2677 - // Determine whether Pinecone is enabled
2678 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
2679 -
2680 - //error_log('Pinecone enabled flag: ' . $use_pinecone);
2681 -
2682 - if ($use_pinecone === 1) {
2683 - //error_log('MXChat Vector Search: Using Pinecone database for products');
2684 - return $this->find_relevant_products_pinecone($user_embedding);
2685 - } else {
2686 - //error_log('MXChat Vector Search: Using WordPress database for products');
2687 - return $this->find_relevant_products_wordpress($user_embedding);
2688 - }
2689 -}
2690 -
2691 -private function find_relevant_products_wordpress($user_embedding) {
2692 - global $wpdb;
2693 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
2694 - $cache_key = 'mxchat_system_prompt_embeddings';
2695 - $batch_size = 500;
2696 -
2697 - // Original WordPress database search logic
2698 - // [Previous implementation remains the same]
2699 - $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
2700 - if ($embeddings === false) {
2701 - $embeddings = [];
2702 - $offset = 0;
2703 -
2704 - do {
2705 - $query = $wpdb->prepare(
2706 - "SELECT id, embedding_vector
2707 - FROM {$system_prompt_table}
2708 - LIMIT %d OFFSET %d",
2709 - $batch_size,
2710 - $offset
2711 - );
2712 -
2713 - $batch = $wpdb->get_results($query);
2714 - if (empty($batch)) {
2715 - break;
2716 - }
2717 -
2718 - $embeddings = array_merge($embeddings, $batch);
2719 - $offset += $batch_size;
2720 -
2721 - unset($batch);
2722 -
2723 - } while (true);
2724 -
2725 - if (empty($embeddings)) {
2726 - return '';
2727 - }
2728 - wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
2729 - }
2730 -
2731 - $relevant_results = [];
2732 - foreach ($embeddings as $embedding) {
2733 - $database_embedding = $embedding->embedding_vector
2734 - ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
2735 - : null;
2736 - if (is_array($database_embedding) && is_array($user_embedding)) {
2737 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
2738 - $relevant_results[] = [
2739 - 'id' => $embedding->id,
2740 - 'similarity' => $similarity
2741 - ];
2742 - }
2743 - unset($database_embedding);
2744 - }
2745 -
2746 - // Use fixed threshold for products
2747 - $similarity_threshold = 0.85;
2748 -
2749 - $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
2750 - return $result['similarity'] >= $similarity_threshold;
2751 - });
2752 - usort($relevant_results, function ($a, $b) {
2753 - return $b['similarity'] <=> $a['similarity'];
2754 - });
2755 -
2756 - $top_results = array_slice($relevant_results, 0, 5);
2757 - $content = '';
2758 -
2759 - foreach ($top_results as $result) {
2760 - $chunk_content = $this->fetch_content_with_product_links($result['id']);
2761 - $content .= $chunk_content . "\n\n";
2762 - }
2763 -
2764 - return trim($content);
2765 -}
2766 -
2767 -// Modified search function with correct filter syntax
2768 -private function find_relevant_products_pinecone($user_embedding) {
2769 - //error_log('Starting Pinecone product search...');
2770 -
2771 - $options = get_option('mxchat_pinecone_addon_options', array());
2772 - $api_key = $options['mxchat_pinecone_api_key'] ?? '';
2773 - $host = $options['mxchat_pinecone_host'] ?? '';
2774 -
2775 - if (empty($host) || empty($api_key)) {
2776 - //error_log('Pinecone credentials not properly configured for product search');
2777 - return '';
2778 - }
2779 -
2780 - $similarity_threshold = 0.85;
2781 - $api_endpoint = "https://{$host}/query";
2782 -
2783 - $request_body = array(
2784 - 'vector' => $user_embedding,
2785 - 'topK' => 5,
2786 - 'includeMetadata' => true,
2787 - 'includeValues' => true,
2788 - 'filter' => array(
2789 - 'type' => 'product'
2790 - )
2791 - );
2792 -
2793 - //error_log('Sending request to Pinecone with body: ' . wp_json_encode($request_body));
2794 -
2795 - $response = wp_remote_post($api_endpoint, array(
2796 - 'headers' => array(
2797 - 'Api-Key' => $api_key,
2798 - 'accept' => 'application/json',
2799 - 'content-type' => 'application/json'
2800 - ),
2801 - 'body' => wp_json_encode($request_body),
2802 - 'timeout' => 30
2803 - ));
2804 -
2805 - if (is_wp_error($response)) {
2806 - //error_log('Pinecone product query error: ' . $response->get_error_message());
2807 - return '';
2808 - }
2809 -
2810 - $response_code = wp_remote_retrieve_response_code($response);
2811 - //error_log('Pinecone response code: ' . $response_code);
2812 -
2813 - if ($response_code !== 200) {
2814 - //error_log('Pinecone API error during product search: ' . wp_remote_retrieve_body($response));
2815 - return '';
2816 - }
2817 -
2818 - $results = json_decode(wp_remote_retrieve_body($response), true);
2819 - //error_log('Pinecone raw response: ' . wp_remote_retrieve_body($response));
2820 -
2821 - if (empty($results['matches'])) {
2822 - //error_log('No matches found in Pinecone response');
2823 - return '';
2824 - }
2825 -
2826 - $content = '';
2827 - foreach ($results['matches'] as $match) {
2828 - if ($match['score'] < $similarity_threshold) {
2829 - //error_log("Match below threshold: " . $match['score']);
2830 - continue;
2831 - }
2832 -
2833 - if (!empty($match['metadata']['text'])) {
2834 - $content .= $match['metadata']['text'];
2835 - if (!empty($match['metadata']['source_url'])) {
2836 - $content .= "\n\nFor more details, check out this product: " . esc_url($match['metadata']['source_url']);
2837 - }
2838 - $content .= "\n\n";
2839 - }
2840 - }
2841 -
2842 - return trim($content);
2843 -}
2844 -
2845 -
2846 -private function fetch_content_with_product_links($most_relevant_id) {
2847 - global $wpdb;
2848 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
2849 -
2850 - // Fetch the article content and associated product URL
2851 - $query = $wpdb->prepare("SELECT article_content, source_url FROM {$system_prompt_table} WHERE id = %d", $most_relevant_id);
2852 - $result = $wpdb->get_row($query);
2853 -
2854 - if ($result) {
2855 - // Append the product link to the content if available
2856 - $content = $result->article_content;
2857 - if (!empty($result->source_url)) {
2858 - $content .= "\n\nFor more details, check out this product: " . esc_url($result->source_url);
2859 - }
2860 - return $content;
2861 - }
2862 -
2863 - return null;
2864 -}
2865 -
2866 -// Function definition
2867 -private function mxchat_generate_response($relevant_content, $api_key, $xai_api_key, $claude_api_key, $deepseek_api_key, $conversation_history) {
2868 - try {
2869 - if (!$relevant_content) {
2870 - return esc_html__("I'm sorry, I couldn't find relevant information on that topic.", 'mxchat');
2871 - }
2872 -
2873 - // Ensure conversation_history is an array
2874 - if (!is_array($conversation_history)) {
2875 - $conversation_history = array();
2876 - }
2877 -
2878 - // Get selected model with default fallback
2879 - $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-4o';
2880 -
2881 - // Extract model prefix to determine the provider
2882 - $model_parts = explode('-', $selected_model);
2883 - $provider = strtolower($model_parts[0]);
2884 -
2885 - // Handle model selection based on provider prefix
2886 - switch ($provider) {
2887 - case 'claude':
2888 - if (empty($claude_api_key)) {
2889 - throw new Exception(esc_html__('Claude API key is not configured', 'mxchat'));
2890 - }
2891 - return $this->mxchat_generate_response_claude(
2892 - $selected_model,
2893 - $claude_api_key,
2894 - $conversation_history,
2895 - $relevant_content
2896 - );
2897 -
2898 - case 'grok':
2899 - if (empty($xai_api_key)) {
2900 - throw new Exception(esc_html__('X.AI API key is not configured', 'mxchat'));
2901 - }
2902 - return $this->mxchat_generate_response_xai(
2903 - $selected_model,
2904 - $xai_api_key,
2905 - $conversation_history,
2906 - $relevant_content
2907 - );
2908 -
2909 - case 'deepseek':
2910 - if (empty($deepseek_api_key)) {
2911 - throw new Exception(esc_html__('DeepSeek API key is not configured', 'mxchat'));
2912 - }
2913 - return $this->mxchat_generate_response_deepseek(
2914 - $selected_model,
2915 - $deepseek_api_key,
2916 - $conversation_history,
2917 - $relevant_content
2918 - );
2919 -
2920 - case 'gpt':
2921 - if (empty($api_key)) {
2922 - throw new Exception(esc_html__('OpenAI API key is not configured', 'mxchat'));
2923 - }
2924 - return $this->mxchat_generate_response_openai(
2925 - $selected_model,
2926 - $api_key,
2927 - $conversation_history,
2928 - $relevant_content
2929 - );
2930 -
2931 - default:
2932 - // Default to OpenAI for custom models or unrecognized prefixes
2933 - if (empty($api_key)) {
2934 - throw new Exception(esc_html__('OpenAI API key is not configured', 'mxchat'));
2935 - }
2936 - return $this->mxchat_generate_response_openai(
2937 - $selected_model,
2938 - $api_key,
2939 - $conversation_history,
2940 - $relevant_content
2941 - );
2942 - }
2943 - } catch (Exception $e) {
2944 - //error_log('MXChat Error: ' . $e->getMessage());
2945 - return sprintf(
2946 - esc_html__('An error occurred: %s', 'mxchat'),
2947 - esc_html($e->getMessage())
2948 - );
2949 - }
2950 -}
2951 -
2952 -
2953 -private function mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content) {
2954 - // Ensure conversation_history is an array
2955 - if (!is_array($conversation_history)) {
2956 - $conversation_history = array();
2957 - }
2958 -
2959 - // Get system prompt instructions from options
2960 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
2961 -
2962 - // Create a new array for the formatted conversation
2963 - $formatted_conversation = array();
2964 -
2965 - // Add system message first
2966 - $formatted_conversation[] = array(
2967 - 'role' => 'system',
2968 - 'content' => $system_prompt_instructions . " " . $relevant_content
2969 - );
2970 -
2971 - // Add the rest of the conversation history
2972 - foreach ($conversation_history as $message) {
2973 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
2974 - $role = $message['role'];
2975 -
2976 - // Convert roles to supported format
2977 - if ($role === 'bot' || $role === 'agent') {
2978 - $role = 'assistant';
2979 - }
2980 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
2981 - $role = 'user';
2982 - }
2983 -
2984 - $formatted_conversation[] = array(
2985 - 'role' => $role,
2986 - 'content' => $message['content']
2987 - );
2988 - }
2989 - }
2990 -
2991 - $body = json_encode([
2992 - 'model' => $selected_model,
2993 - 'messages' => $formatted_conversation,
2994 - 'temperature' => 0.8,
2995 - 'stream' => false
2996 - ]);
2997 -
2998 - $args = [
2999 - 'body' => $body,
3000 - 'headers' => [
3001 - 'Content-Type' => 'application/json',
3002 - 'Authorization' => 'Bearer ' . $deepseek_api_key,
3003 - ],
3004 - 'timeout' => 60,
3005 - 'redirection' => 5,
3006 - 'blocking' => true,
3007 - 'httpversion' => '1.0',
3008 - 'sslverify' => true,
3009 - ];
3010 -
3011 - $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', $args);
3012 -
3013 - if (is_wp_error($response)) {
3014 - //error_log('DeepSeek API Error: ' . $response->get_error_message());
3015 - return "Sorry, there was an error processing your request.";
3016 - }
3017 -
3018 - $response_body = wp_remote_retrieve_body($response);
3019 - $decoded_response = json_decode($response_body, true);
3020 -
3021 - if (isset($decoded_response['choices'][0]['message']['content'])) {
3022 - return trim($decoded_response['choices'][0]['message']['content']);
3023 - } else {
3024 - //error_log('DeepSeek API Response Format Error: ' . print_r($decoded_response, true));
3025 - return "Sorry, I couldn't process that request.";
3026 - }
3027 -}
3028 -
3029 -private function mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content) {
3030 - // Ensure conversation_history is an array
3031 - if (!is_array($conversation_history)) {
3032 - $conversation_history = array();
3033 - }
3034 -
3035 - // Get system prompt instructions from options
3036 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3037 -
3038 - // Create a new array for the formatted conversation
3039 - $formatted_conversation = array();
3040 -
3041 - // Add system message first
3042 - $formatted_conversation[] = array(
3043 - 'role' => 'system',
3044 - 'content' => $system_prompt_instructions . " " . $relevant_content
3045 - );
3046 -
3047 - // Add the rest of the conversation history
3048 - foreach ($conversation_history as $message) {
3049 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
3050 - $role = $message['role'];
3051 -
3052 - // Convert roles to supported format
3053 - if ($role === 'bot' || $role === 'agent') {
3054 - $role = 'assistant';
3055 - }
3056 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
3057 - $role = 'user';
3058 - }
3059 -
3060 - $formatted_conversation[] = array(
3061 - 'role' => $role,
3062 - 'content' => $message['content']
3063 - );
3064 - }
3065 - }
3066 -
3067 - $body = json_encode([
3068 - 'model' => $selected_model,
3069 - 'messages' => $formatted_conversation,
3070 - 'temperature' => 0.8,
3071 - 'stream' => false
3072 - ]);
3073 -
3074 - $args = [
3075 - 'body' => $body,
3076 - 'headers' => [
3077 - 'Content-Type' => 'application/json',
3078 - 'Authorization' => 'Bearer ' . $api_key,
3079 - ],
3080 - 'timeout' => 60,
3081 - 'redirection' => 5,
3082 - 'blocking' => true,
3083 - 'httpversion' => '1.0',
3084 - 'sslverify' => true,
3085 - ];
3086 -
3087 - $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
3088 -
3089 - if (is_wp_error($response)) {
3090 - //error_log('OpenAI API Error: ' . $response->get_error_message());
3091 - return "Sorry, there was an error processing your request.";
3092 - }
3093 -
3094 - $response_body = wp_remote_retrieve_body($response);
3095 - $decoded_response = json_decode($response_body, true);
3096 -
3097 - if (isset($decoded_response['choices'][0]['message']['content'])) {
3098 - return trim($decoded_response['choices'][0]['message']['content']);
3099 - } else {
3100 - //error_log('OpenAI API Response Format Error: ' . print_r($decoded_response, true));
3101 - return "Sorry, I couldn't process that request.";
3102 - }
3103 -}
3104 -private function mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content) {
3105 - // Get system prompt instructions from options
3106 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3107 -
3108 - // Add system prompt to relevant content
3109 - $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
3110 -
3111 - // Prepend system instructions to the conversation history
3112 - array_unshift($conversation_history, [
3113 - 'role' => 'system',
3114 - 'content' => "Here are your instructions: " . $content_with_instructions
3115 - ]);
3116 -
3117 - // Ensure consistency: Replace 'bot' and 'agent' roles with supported values
3118 - foreach ($conversation_history as &$message) {
3119 - if ($message['role'] === 'bot') {
3120 - $message['role'] = 'assistant';
3121 - } elseif ($message['role'] === 'agent') {
3122 - // Tag the message as coming from a live agent
3123 - $message['role'] = 'assistant';
3124 - if (!isset($message['metadata'])) {
3125 - $message['metadata'] = ['source' => 'live_agent'];
3126 - }
3127 - }
3128 -
3129 - // Ensure all roles are valid
3130 - if (!in_array($message['role'], ['system', 'assistant', 'user', 'function', 'tool'])) {
3131 - $message['role'] = 'user'; // Default to 'user'
3132 - }
3133 - }
3134 -
3135 -
3136 - // Build the request body
3137 - $body = json_encode([
3138 - 'model' => $selected_model,
3139 - 'messages' => $conversation_history,
3140 - 'temperature' => 0.8,
3141 - 'stream' => false
3142 - ]);
3143 -
3144 - // Set up the API request
3145 - $args = [
3146 - 'body' => $body,
3147 - 'headers' => [
3148 - 'Content-Type' => 'application/json',
3149 - 'Authorization' => 'Bearer ' . $xai_api_key,
3150 - ],
3151 - 'timeout' => 60,
3152 - 'redirection' => 5,
3153 - 'blocking' => true,
3154 - 'httpversion' => '1.0',
3155 - 'sslverify' => true,
3156 - ];
3157 -
3158 - // Make the API request
3159 - $response = wp_remote_post('https://api.x.ai/v1/chat/completions', $args);
3160 -
3161 - // Process the response
3162 - if (is_wp_error($response)) {
3163 - return "Sorry, there was an error processing your request.";
3164 - }
3165 -
3166 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3167 -
3168 - if (isset($response_body['choices'][0]['message']['content'])) {
3169 - return trim($response_body['choices'][0]['message']['content']);
3170 - } else {
3171 - return "Sorry, I couldn't process that request.";
3172 - }
3173 -}
3174 -
3175 -private function mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content) {
3176 - // Get system prompt instructions from options
3177 - $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3178 -
3179 - // Clean and validate conversation history
3180 - foreach ($conversation_history as &$message) {
3181 - // Convert bot and agent roles to assistant
3182 - if ($message['role'] === 'bot' || $message['role'] === 'agent') {
3183 - $message['role'] = 'assistant';
3184 - }
3185 -
3186 - // Remove unsupported roles - Claude only supports 'assistant' and 'user'
3187 - if (!in_array($message['role'], ['assistant', 'user'])) {
3188 - $message['role'] = 'user';
3189 - }
3190 -
3191 - // Ensure content field exists
3192 - if (!isset($message['content']) || empty($message['content'])) {
3193 - $message['content'] = '';
3194 - }
3195 -
3196 - // Remove any unsupported fields
3197 - $message = array_intersect_key($message, array_flip(['role', 'content']));
3198 - }
3199 -
3200 - // Add relevant content as the latest user message
3201 - $conversation_history[] = [
3202 - 'role' => 'user',
3203 - 'content' => $relevant_content
3204 - ];
3205 -
3206 - // Build request body
3207 - $body = json_encode([
3208 - 'model' => $selected_model,
3209 - 'max_tokens' => 1000,
3210 - 'temperature' => 0.8,
3211 - 'messages' => $conversation_history,
3212 - 'system' => $system_prompt_instructions
3213 - ]);
3214 -
3215 - // Set up API request
3216 - $args = [
3217 - 'body' => $body,
3218 - 'headers' => [
3219 - 'Content-Type' => 'application/json',
3220 - 'x-api-key' => $claude_api_key,
3221 - 'anthropic-version' => '2023-06-01'
3222 - ],
3223 - 'timeout' => 60,
3224 - 'redirection' => 5,
3225 - 'blocking' => true,
3226 - 'httpversion' => '1.0',
3227 - 'sslverify' => true,
3228 - ];
3229 -
3230 - // Make API request
3231 - $response = wp_remote_post('https://api.anthropic.com/v1/messages', $args);
3232 -
3233 - // Check for WordPress errors
3234 - if (is_wp_error($response)) {
3235 - //error_log("Claude API request error: " . $response->get_error_message());
3236 - return "Sorry, there was an error connecting to the API.";
3237 - }
3238 -
3239 - // Check HTTP response code
3240 - $http_code = wp_remote_retrieve_response_code($response);
3241 - if ($http_code !== 200) {
3242 - $error_body = wp_remote_retrieve_body($response);
3243 - //error_log("Claude API HTTP error: " . $http_code . " - " . $error_body);
3244 -
3245 - // Try to extract error message from response
3246 - $error_data = json_decode($error_body, true);
3247 - $error_message = isset($error_data['error']['message']) ?
3248 - $error_data['error']['message'] :
3249 - "HTTP error " . $http_code;
3250 -
3251 - return "Sorry, the API returned an error: " . $error_message;
3252 - }
3253 -
3254 - // Parse response
3255 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3256 -
3257 - // Check for JSON decode errors
3258 - if (json_last_error() !== JSON_ERROR_NONE) {
3259 - //error_log("Claude API JSON decode error: " . json_last_error_msg());
3260 - return "Sorry, there was an error processing the API response.";
3261 - }
3262 -
3263 - // Extract and validate response content
3264 - if (isset($response_body['content']) &&
3265 - is_array($response_body['content']) &&
3266 - !empty($response_body['content']) &&
3267 - isset($response_body['content'][0]['text'])) {
3268 - return trim($response_body['content'][0]['text']);
3269 - }
3270 -
3271 - // Log unexpected response format
3272 - //error_log("Claude API unexpected response format: " . print_r($response_body, true));
3273 - return "Sorry, I received an unexpected response format from the API.";
3274 -}
3275 -public function mxchat_dismiss_pre_chat_message() {
3276 - // Get and sanitize the user identifier
3277 - $user_id = $this->mxchat_get_user_identifier();
3278 - $user_id = sanitize_key($user_id);
3279 -
3280 - // Set a transient to track that the user has dismissed the pre-chat message
3281 - $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
3282 - set_transient($transient_key, true, DAY_IN_SECONDS);
3283 -
3284 - wp_send_json_success();
3285 -}
3286 -
3287 -public function mxchat_check_pre_chat_message_status() {
3288 - // Get and sanitize the user identifier
3289 - $user_id = $this->mxchat_get_user_identifier();
3290 - $user_id = sanitize_key($user_id);
3291 -
3292 - // Check if the transient exists (i.e., if the message was dismissed)
3293 - $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
3294 - $dismissed = get_transient($transient_key);
3295 -
3296 - // Log the result to see if it's being set correctly
3297 - //error_log("Check pre-chat message dismissed for $user_id: " . ($dismissed ? 'Yes' : 'No'));
3298 -
3299 - if ($dismissed) {
3300 - wp_send_json_success(['dismissed' => true]);
3301 - } else {
3302 - wp_send_json_success(['dismissed' => false]);
3303 - }
3304 -
3305 - wp_die();
3306 -}
3307 -
3308 -private function mxchat_calculate_cosine_similarity($vectorA, $vectorB) {
3309 - if (!is_array($vectorA) || !is_array($vectorB) || empty($vectorA) || empty($vectorB)) {
3310 - return 0;
3311 - }
3312 -
3313 - $dotProduct = array_sum(array_map(function ($a, $b) {
3314 - return $a * $b;
3315 - }, $vectorA, $vectorB));
3316 - $normA = sqrt(array_sum(array_map(function ($a) {
3317 - return $a * $a;
3318 - }, $vectorA)));
3319 - $normB = sqrt(array_sum(array_map(function ($b) {
3320 - return $b * $b;
3321 - }, $vectorB)));
3322 -
3323 - if ($normA == 0 || $normB == 0) {
3324 - return 0;
3325 - }
3326 -
3327 - return $dotProduct / ($normA * $normB);
3328 - }
3329 -
3330 -public function mxchat_enqueue_scripts_styles() {
3331 - // Define version numbers for the styles and scripts
3332 - $chat_style_version = '2.0.5'; // Replace with your actual version
3333 - $chat_script_version = '2.0.5'; // Replace with your actual version
3334 -
3335 - // Enqueue the script
3336 - wp_enqueue_script(
3337 - 'mxchat-chat-js',
3338 - plugin_dir_url(__FILE__) . '../js/chat-script.js',
3339 - array('jquery'),
3340 - $chat_script_version,
3341 - true
3342 - );
3343 -
3344 - // Enqueue the CSS
3345 - wp_enqueue_style(
3346 - 'mxchat-chat-css',
3347 - plugin_dir_url(__FILE__) . '../css/chat-style.css',
3348 - array(),
3349 - $chat_style_version
3350 - );
3351 -
3352 - // Fetch options from the database
3353 - $this->options = get_option('mxchat_options');
3354 - $prompts_options = get_option('mxchat_prompts_options', array());
3355 -
3356 - // Prepare settings for JavaScript
3357 - $style_settings = array(
3358 - 'ajax_url' => admin_url('admin-ajax.php'),
3359 - 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
3360 - 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
3361 - 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
3362 - 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
3363 - 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
3364 - 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
3365 - 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
3366 - 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
3367 - 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
3368 - 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
3369 - 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
3370 - 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
3371 - 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
3372 - 'icon_color' => $this->options['icon_color'] ?? '#fff',
3373 - 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
3374 - 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
3375 - 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off', // Example for consistency
3376 -
3377 - 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
3378 - 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
3379 - 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
3380 - 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
3381 - 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
3382 - 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
3383 -
3384 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
3385 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1'
3386 - );
3387 -
3388 - // Pass the settings to the script
3389 - wp_localize_script('mxchat-chat-js', 'mxchatChat', $style_settings);
3390 -}
3391 -
3392 -
3393 -public function mxchat_reset_rate_limits() {
3394 - global $wpdb;
3395 -
3396 - // Define a cache key pattern for rate limits
3397 - $cache_key_pattern = 'mxchat_chat_limit_%';
3398 -
3399 - // Retrieve all option names matching the pattern
3400 - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
3401 - $option_names = $wpdb->get_col("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
3402 -
3403 - // db call ok; no-cache ok
3404 - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- db call ok
3405 - $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
3406 -
3407 - // Clear the relevant cache entries
3408 - foreach ($option_names as $option_name) {
3409 - wp_cache_delete($option_name, 'options');
3410 - }
3411 -
3412 - // Optionally, clear a general cache if you have one
3413 - wp_cache_delete('mxchat_all_chat_limits', 'options');
3414 - }
3415 -
3416 -private function mxchat_fetch_woocommerce_products() {
3417 - // Ensure WooCommerce is active
3418 - if (!class_exists('WooCommerce')) {
3419 - return [];
3420 - }
3421 -
3422 - $args = array(
3423 - 'post_type' => 'product',
3424 - 'post_status' => 'publish',
3425 - 'posts_per_page' => -1,
3426 - );
3427 -
3428 - $products = get_posts($args);
3429 - $product_data = [];
3430 -
3431 - foreach ($products as $product) {
3432 - $product_id = $product->ID;
3433 - $product_obj = wc_get_product($product_id);
3434 -
3435 - $product_data[] = array(
3436 - 'id' => $product_id,
3437 - 'name' => $product_obj->get_name(),
3438 - 'description' => $product_obj->get_description(),
3439 - 'short_description' => $product_obj->get_short_description(),
3440 - 'url' => get_permalink($product_id),
3441 - 'price' => $product_obj->get_regular_price(),
3442 - 'sale_price' => $product_obj->get_sale_price(),
3443 - 'stock_status' => $product_obj->get_stock_status(),
3444 - 'sku' => $product_obj->get_sku(),
3445 - 'in_stock' => $product_obj->is_in_stock(),
3446 - 'total_sales' => $product_obj->get_total_sales(),
3447 - );
3448 - }
3449 -
3450 - return $product_data;
3451 -}
3452 -
3453 -}
3454 -?>
1 +<?php
2 +if (!defined('ABSPATH')) {
3 + exit;
4 +}
5 +
6 +class MxChat_Integrator {
7 + private $options;
8 + private $prompts_options;
9 + private $chat_count;
10 + private $fallbackResponse;
11 + private $productCardHtml;
12 + private $word_handler;
13 + private $last_similarity_analysis = null;
14 + private $current_valid_urls = [];
15 + private $is_streaming = false; // ADDED: Track if current request is streaming
16 +
17 +/**
18 + * Class constructor
19 + */
20 +public function __construct() {
21 + $this->options = get_option('mxchat_options');
22 + $this->prompts_options = get_option('mxchat_prompts_options', array());
23 + $this->chat_count = get_option('mxchat_chat_count', 0);
24 + $this->word_handler = new MXChat_Word_Handler($this->options);
25 +
26 + // Add all action hooks
27 + add_action('wp_enqueue_scripts', array($this, 'mxchat_enqueue_scripts_styles'));
28 + add_action('wp_ajax_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
29 + add_action('wp_ajax_nopriv_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
30 + add_action('wp_ajax_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
31 + add_action('wp_ajax_nopriv_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
32 +
33 + // Add the AJAX actions for checking if the pre-chat message was dismissed
34 + add_action('wp_ajax_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
35 + add_action('wp_ajax_nopriv_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
36 + add_action('wp_ajax_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
37 + add_action('wp_ajax_nopriv_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
38 + add_action('wp_ajax_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
39 + add_action('wp_ajax_nopriv_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
40 +
41 + // Add REST API routes registration
42 + add_action('rest_api_init', array($this, 'register_routes'));
43 + add_action('wp_ajax_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
44 + add_action('wp_ajax_nopriv_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
45 +
46 + // Rate limit action - notice we removed the old schedule setup
47 + add_action('mxchat_reset_rate_limits', array($this, 'mxchat_reset_rate_limits'));
48 +
49 + // File upload and handling actions
50 + add_action('wp_ajax_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
51 + add_action('wp_ajax_nopriv_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
52 + add_action('wp_ajax_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
53 + add_action('wp_ajax_nopriv_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
54 +
55 + // Word document handling actions
56 + add_action('wp_ajax_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
57 + add_action('wp_ajax_nopriv_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
58 + add_action('wp_ajax_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
59 + add_action('wp_ajax_nopriv_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
60 + add_action('wp_ajax_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
61 + add_action('wp_ajax_nopriv_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
62 +
63 + // Email handling actions
64 + add_action('wp_ajax_nopriv_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
65 + add_action('wp_ajax_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
66 + add_action('wp_ajax_nopriv_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
67 + add_action('wp_ajax_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
68 +
69 + add_action('wp_ajax_mxchat_stream_chat', array($this, 'mxchat_handle_chat_request'));
70 + add_action('wp_ajax_nopriv_mxchat_stream_chat', array($this, 'mxchat_handle_chat_request'));
71 +
72 + // Testing panel AJAX actions
73 + add_action('wp_ajax_mxchat_get_system_info', array($this, 'mxchat_get_system_info'));
74 + add_action('wp_ajax_mxchat_get_similarity_threshold', array($this, 'mxchat_get_similarity_threshold'));
75 + add_action('wp_ajax_mxchat_get_kb_status', array($this, 'mxchat_get_kb_status'));
76 + add_action('wp_ajax_mxchat_start_fresh_session', array($this, 'mxchat_start_fresh_session'));
77 + // Add to your existing constructor, in the section with other AJAX actions:
78 + add_action('wp_ajax_mxchat_track_url_click', array($this, 'mxchat_track_url_click'));
79 + add_action('wp_ajax_nopriv_mxchat_track_url_click', array($this, 'mxchat_track_url_click'));
80 + add_action('wp_ajax_mxchat_track_originating_page', array($this, 'mxchat_track_originating_page'));
81 + add_action('wp_ajax_nopriv_mxchat_track_originating_page', array($this, 'mxchat_track_originating_page'));
82 + // Add chat mode checking actions
83 + add_action('wp_ajax_mxchat_get_current_chat_mode', array($this, 'mxchat_get_current_chat_mode'));
84 + add_action('wp_ajax_nopriv_mxchat_get_current_chat_mode', array($this, 'mxchat_get_current_chat_mode'));
85 +
86 + // Auto-email transcript action
87 + add_action('mxchat_send_delayed_transcript', array($this, 'mxchat_send_delayed_transcript'), 10, 1);
88 +
89 + add_filter('mxchat_check_actions_only', array($this, 'check_actions_for_addons'), 10, 4);
90 +
91 +
92 +}
93 +
94 +// In your core plugin's check_actions_for_addons method:
95 +public function check_actions_for_addons($default, $message, $user_id, $session_id) {
96 + //error_log('MxChat Core: check_actions_for_addons called with message: ' . $message);
97 +
98 + $result = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
99 +
100 + //error_log('MxChat Core: Intent check result = ' . ($result === false ? 'false' : 'true'));
101 +
102 + return $result;
103 +}
104 +
105 + private function mxchat_increment_chat_count() {
106 + $chat_count = get_option('mxchat_chat_count', 0);
107 + $chat_count++;
108 + update_option('mxchat_chat_count', $chat_count);
109 + }
110 +
111 +function mxchat_fetch_conversation_history() {
112 + if (empty($_POST['session_id'])) {
113 + wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
114 + wp_die();
115 + }
116 +
117 + $session_id = sanitize_text_field($_POST['session_id']);
118 +
119 + // SECURITY FIX: Verify session ownership before retrieving data
120 + // If IP/user changed, signal frontend to reset session instead of blocking
121 + $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
122 +
123 + // Check if this session has an owner recorded
124 + $session_owner = get_option("mxchat_session_owner_{$session_id}");
125 +
126 + // If session has an owner and it doesn't match current user, trigger session reset
127 + if ($session_owner && $session_owner !== $current_user_identifier) {
128 + wp_send_json_error([
129 + 'message' => esc_html__('Your session has expired. Starting a new conversation.', 'mxchat'),
130 + 'code' => 'session_expired',
131 + 'action' => 'reset_session'
132 + ]);
133 + wp_die();
134 + }
135 +
136 + // If no owner is set yet, claim ownership (for legacy sessions)
137 + if (!$session_owner) {
138 + update_option("mxchat_session_owner_{$session_id}", $current_user_identifier, 'no');
139 + }
140 +
141 + $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history
142 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai'); // Get current chat mode
143 +
144 + if (empty($history)) {
145 + // Even if history is empty, return the chat mode
146 + wp_send_json_success([
147 + 'conversation' => [],
148 + 'chat_mode' => $chat_mode
149 + ]);
150 + wp_die();
151 + }
152 +
153 + wp_send_json_success([
154 + 'conversation' => $history,
155 + 'chat_mode' => $chat_mode
156 + ]);
157 + wp_die();
158 +}
159 +private function mxchat_fetch_conversation_history_for_ai($session_id) {
160 + $history = get_option("mxchat_history_{$session_id}", []);
161 + $formatted_history = [];
162 +
163 + // Adjusted for code-heavy conversations
164 + $max_tokens = 120000; // Context window size
165 + $reserved_tokens = 5000; // Space for system prompts + current query
166 + $current_token_count = 0;
167 +
168 + // Allowed HTML tags for content sanitization
169 + $allowed_tags = [
170 + 'pre' => ['class' => true],
171 + 'code' => ['class' => true],
172 + 'span' => ['class' => true],
173 + 'div' => ['class' => true],
174 + 'strong' => [],
175 + 'em' => []
176 + ];
177 +
178 + foreach (array_reverse($history) as $entry) {
179 + // Preserve code blocks while sanitizing other HTML
180 + $clean_content = wp_kses($entry['content'], $allowed_tags);
181 +
182 + // Detect code blocks in content
183 + $has_code = false;
184 +// Replace the HTML check with:
185 +// Allow messages that contain code blocks or are plain text
186 +if (strpos($clean_content, '<pre') === false &&
187 + strpos($clean_content, '<code') === false &&
188 + $clean_content !== strip_tags($entry['content'])) {
189 + continue;
190 +}
191 +
192 + // Skip entries that lost significant content during sanitization
193 + if (!$has_code && $clean_content !== strip_tags($entry['content'])) {
194 + continue;
195 + }
196 +
197 + // More accurate token estimation (1 token ≈ 4 characters)
198 + $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
199 +
200 + // Check token budget with the new estimate
201 + if (($current_token_count + $token_estimate + $reserved_tokens) > $max_tokens) {
202 + // Try to fit partial content if it's the first entry
203 + if (empty($formatted_history)) {
204 + $clean_content = mb_substr($clean_content, 0, ($max_tokens - $reserved_tokens) * 4);
205 + $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
206 + } else {
207 + break;
208 + }
209 + }
210 +
211 + // Add to formatted history
212 + $formatted_history[] = [
213 + 'role' => $entry['role'],
214 + 'content' => $clean_content
215 + ];
216 +
217 + $current_token_count += $token_estimate;
218 + }
219 +
220 + // Reverse back to maintain chronological order
221 + $formatted_history = array_reverse($formatted_history);
222 +
223 + // Add system message about code context
224 + array_unshift($formatted_history, [
225 + 'role' => 'system',
226 + 'content' => 'Preserved code blocks are marked with [CODE BLOCK PRESERVED]. '
227 + . 'Maintain formatting and syntax highlighting when referencing code.'
228 + ]);
229 +
230 + return $formatted_history;
231 +}
232 +
233 +public function register_routes() {
234 + //error_log(esc_html__('Registering MxChat REST routes', 'mxchat'));
235 +
236 + register_rest_route('mxchat/v1', '/stream', [
237 + 'methods' => 'GET',
238 + 'callback' => [$this, 'mxchat_stream_events'],
239 + 'permission_callback' => [$this, 'verify_chat_session'],
240 + ]);
241 +
242 + register_rest_route('mxchat/v1', '/agent-response', [
243 + 'methods' => 'POST',
244 + 'callback' => [$this, 'mxchat_handle_agent_response'],
245 + 'permission_callback' => [$this, 'verify_slack_request'],
246 + ]);
247 +
248 + register_rest_route('mxchat/v1', '/slack-interaction', [
249 + 'methods' => 'POST',
250 + 'callback' => [$this, 'handle_slack_interaction'],
251 + 'permission_callback' => [$this, 'verify_slack_request'],
252 + ]);
253 +
254 + register_rest_route('mxchat/v1', '/slack-messages', [
255 + 'methods' => 'POST',
256 + 'callback' => [$this, 'handle_slack_messages'],
257 + 'permission_callback' => [$this, 'verify_slack_request'],
258 + ]);
259 +
260 + //error_log(esc_html__('MxChat REST routes registered', 'mxchat'));
261 +}
262 +
263 +/**
264 + * Verify valid chat session
265 + */
266 +public function verify_chat_session($request) {
267 + $session_id = $request->get_param('session_id');
268 + if (empty($session_id)) {
269 + //error_log(esc_html__('Empty session ID in chat request', 'mxchat'));
270 + return false;
271 + }
272 +
273 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
274 + return $chat_mode === 'agent';
275 +}
276 +
277 +/**
278 + * Verify request is coming from Slack.
279 + *
280 + * @param WP_REST_Request $request
281 + * @return bool True if valid, false otherwise.
282 + */
283 +public function verify_slack_request($request) {
284 + // Get the Slack signing secret from your plugin options
285 + $valid_key = $this->options['live_agent_secret_key'] ?? '';
286 +
287 + if (empty($valid_key)) {
288 + //error_log(esc_html__('Slack signing secret not configured', 'mxchat'));
289 + return false;
290 + }
291 +
292 + $timestamp = $request->get_header('X-Slack-Request-Timestamp');
293 + $slack_signature = $request->get_header('X-Slack-Signature');
294 +
295 + // Verify timestamp to prevent replay attacks
296 + if (abs(time() - intval($timestamp)) > 300) {
297 + //error_log(esc_html__('Slack request timestamp too old', 'mxchat'));
298 + return false;
299 + }
300 +
301 + // Get raw request body
302 + $request_body = file_get_contents('php://input');
303 +
304 + // Create the signature base string
305 + $sig_basestring = "v0:{$timestamp}:{$request_body}";
306 +
307 + // Calculate expected signature
308 + $my_signature = 'v0=' . hash_hmac('sha256', $sig_basestring, $valid_key);
309 +
310 + // Compare signatures
311 + return hash_equals($my_signature, $slack_signature);
312 +}
313 +public function mxchat_stream_events(WP_REST_Request $request) {
314 + header('Content-Type: text/event-stream');
315 + header('Cache-Control: no-cache');
316 + header('Connection: keep-alive');
317 +
318 + $session_id = sanitize_text_field($request->get_param('session_id'));
319 + $last_seen_id = sanitize_text_field($request->get_param('last_seen_id')) ?: '';
320 +
321 + if (empty($session_id)) {
322 + echo esc_html__("event: error\ndata: ", 'mxchat') . esc_html__('Missing session_id', 'mxchat') . "\n\n";
323 + flush();
324 + exit;
325 + }
326 +
327 + $history = get_option("mxchat_history_{$session_id}", []);
328 +
329 + // Filter only new messages
330 + $new_messages = array_filter($history, function ($message) use ($last_seen_id) {
331 + return !empty($message['id']) && $message['id'] > $last_seen_id;
332 + });
333 +
334 + // Send new messages if available
335 + if (!empty($new_messages)) {
336 + echo esc_html__("event: newMessages\ndata: ", 'mxchat') . json_encode(array_values($new_messages)) . "\n\n";
337 + } else {
338 + // Keep the connection alive
339 + echo esc_html__("event: keepAlive\ndata: ", 'mxchat') . "{}\n\n";
340 + }
341 + flush();
342 + exit;
343 +}
344 +
345 +
346 +
347 +
348 +private function mxchat_save_chat_message($session_id, $role, $message, $originating_page = null, $rag_context = null) {
349 + global $wpdb;
350 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
351 + //error_log("[DEBUG] mxchat_save_chat_message -> START for session_id: {$session_id}, role: {$role}");
352 +
353 + // Check if this is the first message in a new session (before any other database operations)
354 + $is_new_session = false;
355 + if ($role === 'user') { // Only check for user messages, not bot responses
356 + $existing_messages = $wpdb->get_var($wpdb->prepare(
357 + "SELECT COUNT(*) FROM $table_name WHERE session_id = %s",
358 + $session_id
359 + ));
360 + $is_new_session = ($existing_messages == 0);
361 +
362 + // Log for debugging
363 + if ($is_new_session) {
364 + //error_log("[DEBUG] This is a NEW session - first message");
365 + }
366 + }
367 +
368 + // SECURITY FIX: Set session ownership for new sessions
369 + if ($is_new_session && $role === 'user') {
370 + $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
371 + $session_owner_key = "mxchat_session_owner_{$session_id}";
372 +
373 + // Only set ownership if not already set
374 + if (!get_option($session_owner_key)) {
375 + update_option($session_owner_key, $current_user_identifier, 'no');
376 + //error_log("[DEBUG] Set session ownership for {$session_id} to {$current_user_identifier}");
377 + }
378 + }
379 +
380 + // 1) Extract agent name if present
381 + $agent_name = '';
382 + if (preg_match('/^Agent: (.*?) - /', $message, $matches)) {
383 + $agent_name = $matches[1];
384 + $message = str_replace("Agent: $agent_name - ", '', $message);
385 + $session_meta_key = "mxchat_agent_name_{$session_id}";
386 + if (empty(get_option($session_meta_key))) {
387 + update_option($session_meta_key, $agent_name);
388 + //error_log("[DEBUG] mxchat_save_chat_message -> Stored agent_name in option: {$session_meta_key} => {$agent_name}");
389 + }
390 + }
391 +
392 + // 2) Generate unique message_id
393 + $message_id = uniqid();
394 + //error_log("[DEBUG] mxchat_save_chat_message -> Generated message_id: {$message_id}");
395 +
396 + // 3) Determine user_id
397 + $user_id = is_user_logged_in() ? get_current_user_id() : 0;
398 +
399 + // 4) Determine user_identifier
400 + $user_identifier = $agent_name
401 + ? $agent_name
402 + : MxChat_User::mxchat_get_user_identifier();
403 +
404 + // 5) Determine displayed_name
405 + $user_email = MxChat_User::mxchat_get_user_email();
406 + $displayed_name = $agent_name ? $agent_name : ($user_email ?: $user_identifier);
407 +
408 + // 6) Check for a saved email in wp_options
409 + $email_option_key = "mxchat_email_{$session_id}";
410 + $saved_email = get_option($email_option_key);
411 + //error_log("[DEBUG] mxchat_save_chat_message -> Checking wp_options for email_option_key: {$email_option_key}, found: {$saved_email}");
412 +
413 + // Check for a saved name in wp_options
414 + $name_option_key = "mxchat_name_{$session_id}";
415 + $saved_name = get_option($name_option_key);
416 + //error_log("[DEBUG] mxchat_save_chat_message -> Checking wp_options for name_option_key: {$name_option_key}, found: {$saved_name}");
417 +
418 + // If found, update DB user_email and user_name
419 + if ($saved_email || $saved_name) {
420 + $update_data = [];
421 + if ($saved_email) {
422 + $update_data['user_email'] = $saved_email;
423 + }
424 + if ($saved_name) {
425 + $update_data['user_name'] = $saved_name;
426 + }
427 +
428 + if (!empty($update_data)) {
429 + $update_res = $wpdb->update(
430 + $table_name,
431 + $update_data,
432 + ['session_id' => $session_id],
433 + array_fill(0, count($update_data), '%s'),
434 + ['%s']
435 + );
436 + //error_log("[DEBUG] mxchat_save_chat_message -> Attempted DB user_email/user_name update for session_id {$session_id}. update_res: {$update_res}");
437 + }
438 + }
439 +
440 + // 7) Save to session history in wp_options
441 + $history_key = "mxchat_history_{$session_id}";
442 + $history = get_option($history_key, []);
443 + $history[] = [
444 + 'id' => $message_id,
445 + 'role' => $role,
446 + 'content' => $message,
447 + 'timestamp' => round(microtime(true) * 1000),
448 + 'agent_name' => $displayed_name,
449 + ];
450 + update_option($history_key, $history, 'no');
451 + //error_log("[DEBUG] mxchat_save_chat_message -> Updated session history in option: {$history_key}");
452 +
453 + // 8) Save the message to DB (INSERT)
454 + $insert_data = [
455 + 'user_id' => $user_id,
456 + 'user_identifier'=> $user_identifier,
457 + 'user_email' => $saved_email ?: $user_email,
458 + 'user_name' => $saved_name ?: '', // Add name to insert data
459 + 'session_id' => $session_id,
460 + 'role' => $role,
461 + 'message' => $message,
462 + 'timestamp' => current_time('mysql', 1),
463 + ];
464 +
465 + // IMPROVED: Handle originating page data
466 + $columns_exist = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'");
467 +
468 + if ($columns_exist) {
469 + if ($is_new_session && $role === 'user') {
470 + // For the first user message, set originating page data
471 +
472 + // First check if we have it from the parameter
473 + if ($originating_page && !empty($originating_page['url'])) {
474 + $insert_data['originating_page_url'] = $originating_page['url'];
475 + $insert_data['originating_page_title'] = $originating_page['title'] ?? '';
476 +
477 + //error_log("[DEBUG] Setting originating page from parameter: " . $originating_page['url']);
478 + }
479 + // Otherwise check if it's stored in the instance property
480 + else if (isset($this->pending_originating_page) && !empty($this->pending_originating_page['url'])) {
481 + $insert_data['originating_page_url'] = $this->pending_originating_page['url'];
482 + $insert_data['originating_page_title'] = $this->pending_originating_page['title'] ?? '';
483 +
484 + //error_log("[DEBUG] Setting originating page from pending_originating_page: " . $this->pending_originating_page['url']);
485 +
486 + // Clear after using
487 + unset($this->pending_originating_page);
488 + }
489 + // Fallback to HTTP_REFERER if nothing else is available
490 + else if (isset($_SERVER['HTTP_REFERER'])) {
491 + $referer_url = esc_url_raw($_SERVER['HTTP_REFERER']);
492 + $insert_data['originating_page_url'] = $referer_url;
493 +
494 + // Generate title from URL
495 + $parsed_url = parse_url($referer_url);
496 + $path = isset($parsed_url['path']) ? trim($parsed_url['path'], '/') : '';
497 +
498 + if (empty($path) || $path === 'index.php' || $path === 'index.html') {
499 + $insert_data['originating_page_title'] = 'Homepage';
500 + } else {
501 + $title = str_replace(['-', '_', '/', '.php', '.html'], ' ', $path);
502 + $insert_data['originating_page_title'] = ucwords(trim($title));
503 + }
504 +
505 + //error_log("[DEBUG] Setting originating page from HTTP_REFERER: " . $referer_url);
506 + }
507 +
508 + // Store for this session so all messages have the same originating page
509 + if (!empty($insert_data['originating_page_url'])) {
510 + update_option("mxchat_originating_page_{$session_id}", [
511 + 'url' => $insert_data['originating_page_url'],
512 + 'title' => $insert_data['originating_page_title']
513 + ], 'no');
514 + }
515 + } else {
516 + // For subsequent messages in the session, use the stored originating page
517 + $stored_originating = get_option("mxchat_originating_page_{$session_id}");
518 + if ($stored_originating && !empty($stored_originating['url'])) {
519 + $insert_data['originating_page_url'] = $stored_originating['url'];
520 + $insert_data['originating_page_title'] = $stored_originating['title'] ?? '';
521 + }
522 + }
523 + }
524 +
525 + // Add RAG context if provided (for bot messages)
526 + if ($rag_context !== null && $role === 'bot') {
527 + $rag_context_column_exists = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'rag_context'");
528 + if ($rag_context_column_exists) {
529 + $insert_data['rag_context'] = is_array($rag_context) ? wp_json_encode($rag_context) : $rag_context;
530 + }
531 + }
532 +
533 + $wpdb->insert($table_name, $insert_data);
534 + //error_log("[DEBUG] mxchat_save_chat_message -> Inserted message into DB. row_id: {$wpdb->insert_id}, data: " . print_r($insert_data, true));
535 +
536 + // 9) Send notification email if this is the first user message in a new session
537 + if ($wpdb->insert_id && $is_new_session && $role === 'user') {
538 + $this->send_new_chat_notification($session_id, array(
539 + 'identifier' => $user_identifier,
540 + 'email' => $saved_email ?: $user_email,
541 + 'ip' => $_SERVER['REMOTE_ADDR']
542 + ));
543 + }
544 +
545 + // 10) Schedule delayed transcript email if enabled and message is from user
546 + if ($wpdb->insert_id && $role === 'user') {
547 + $this->schedule_delayed_transcript_email($session_id);
548 + }
549 +
550 + //error_log("[DEBUG] mxchat_save_chat_message -> END for session_id: {$session_id}");
551 + return $message_id;
552 +}
553 +
554 +private function send_new_chat_notification($session_id, $user_info = array()) {
555 + $options = get_option('mxchat_transcripts_options');
556 +
557 + // Check if notifications are enabled
558 + if (empty($options['mxchat_enable_notifications'])) {
559 + return false;
560 + }
561 +
562 + // Get notification email
563 + $to = !empty($options['mxchat_notification_email']) ?
564 + $options['mxchat_notification_email'] :
565 + get_option('admin_email');
566 +
567 + if (!is_email($to)) {
568 + return false;
569 + }
570 +
571 + // Prepare email content
572 + $subject = sprintf('[%s] New Chat Session Started', get_bloginfo('name'));
573 +
574 + $user_identifier = isset($user_info['identifier']) ? $user_info['identifier'] : 'Guest';
575 + $user_email = isset($user_info['email']) ? $user_info['email'] : 'Not provided';
576 + $user_ip = isset($user_info['ip']) ? $user_info['ip'] : $_SERVER['REMOTE_ADDR'];
577 +
578 + $message = sprintf(
579 + "A new chat session has started on your website.\n\n" .
580 + "Session ID: %s\n" .
581 + "User: %s\n" .
582 + "Email: %s\n" .
583 + "IP Address: %s\n" .
584 + "Time: %s\n\n" .
585 + "View transcripts: %s",
586 + $session_id,
587 + $user_identifier,
588 + $user_email,
589 + $user_ip,
590 + current_time('mysql'),
591 + admin_url('admin.php?page=mxchat-transcripts')
592 + );
593 +
594 + // Send email
595 + return wp_mail($to, $subject, $message);
596 +}
597 +
598 +/**
599 + * Schedule delayed transcript email for a session
600 + * Reschedules if a new user message is received
601 + */
602 +private function schedule_delayed_transcript_email($session_id) {
603 + $options = get_option('mxchat_transcripts_options');
604 +
605 + // Check if auto-email is enabled
606 + if (empty($options['mxchat_auto_email_transcript_enabled'])) {
607 + return;
608 + }
609 +
610 + // Get notification email
611 + $email = !empty($options['mxchat_notification_email']) ?
612 + $options['mxchat_notification_email'] :
613 + get_option('admin_email');
614 +
615 + if (!is_email($email)) {
616 + return;
617 + }
618 +
619 + // Get delay in minutes (default 30)
620 + $delay_minutes = isset($options['mxchat_auto_email_transcript_delay']) ?
621 + intval($options['mxchat_auto_email_transcript_delay']) : 30;
622 +
623 + // Clear any existing scheduled event for this session
624 + $hook = 'mxchat_send_delayed_transcript';
625 + $args = array($session_id);
626 + $timestamp = wp_next_scheduled($hook, $args);
627 +
628 + if ($timestamp) {
629 + wp_unschedule_event($timestamp, $hook, $args);
630 + }
631 +
632 + // Schedule new event
633 + $schedule_time = time() + ($delay_minutes * 60);
634 + wp_schedule_single_event($schedule_time, $hook, $args);
635 +}
636 +
637 +/**
638 + * Check if chat messages contain contact information (email or phone number)
639 + *
640 + * @param array $messages Array of message objects with 'message' property
641 + * @param object|null $session_data Session data object with user_email property
642 + * @return bool True if contact info found, false otherwise
643 + */
644 +private function chat_contains_contact_info($messages, $session_data = null) {
645 + // Check if session already has a stored email
646 + if ($session_data && !empty($session_data->user_email)) {
647 + return true;
648 + }
649 +
650 + // Email regex pattern
651 + $email_pattern = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/';
652 +
653 + // Phone number patterns (covers various formats including international, WhatsApp style)
654 + // Matches: +1234567890, (123) 456-7890, 123-456-7890, 123.456.7890, 1234567890, +1 234 567 8900, etc.
655 + $phone_pattern = '/(?:\+?\d{1,3}[-.\s]?)?\(?\d{2,4}\)?[-.\s]?\d{2,4}[-.\s]?\d{2,4}(?:[-.\s]?\d{1,4})?/';
656 +
657 + // Only check user messages (not assistant responses)
658 + foreach ($messages as $msg) {
659 + if ($msg->role !== 'user') {
660 + continue;
661 + }
662 +
663 + $message_text = $msg->message;
664 +
665 + // Check for email
666 + if (preg_match($email_pattern, $message_text)) {
667 + return true;
668 + }
669 +
670 + // Check for phone number (must be at least 7 digits total to avoid false positives)
671 + if (preg_match($phone_pattern, $message_text, $matches)) {
672 + // Count actual digits to avoid matching short numbers
673 + $digits_only = preg_replace('/\D/', '', $matches[0]);
674 + if (strlen($digits_only) >= 7) {
675 + return true;
676 + }
677 + }
678 + }
679 +
680 + return false;
681 +}
682 +
683 +/**
684 + * Send the delayed transcript email with .txt attachment
685 + */
686 +public function mxchat_send_delayed_transcript($session_id) {
687 + global $wpdb;
688 +
689 + $options = get_option('mxchat_transcripts_options');
690 +
691 + // Get notification email
692 + $to = !empty($options['mxchat_notification_email']) ?
693 + $options['mxchat_notification_email'] :
694 + get_option('admin_email');
695 +
696 + if (!is_email($to)) {
697 + return false;
698 + }
699 +
700 + // Get all messages for this session
701 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
702 + $messages = $wpdb->get_results($wpdb->prepare(
703 + "SELECT role, message, timestamp FROM {$table_name}
704 + WHERE session_id = %s
705 + ORDER BY timestamp ASC",
706 + $session_id
707 + ));
708 +
709 + if (empty($messages)) {
710 + return false;
711 + }
712 +
713 + // Get session metadata
714 + $sessions_table = $wpdb->prefix . 'mxchat_sessions';
715 + $session_data = $wpdb->get_row($wpdb->prepare(
716 + "SELECT * FROM {$sessions_table} WHERE session_id = %s",
717 + $session_id
718 + ));
719 +
720 + // Check if contact info is required and if it's present
721 + $require_contact = !empty($options['mxchat_auto_email_transcript_require_contact']);
722 + if ($require_contact && !$this->chat_contains_contact_info($messages, $session_data)) {
723 + // Contact info required but not found - skip sending
724 + return false;
725 + }
726 +
727 + // Build transcript content
728 + $transcript_content = "Chat Transcript\n";
729 + $transcript_content .= "================\n\n";
730 + $transcript_content .= "Session ID: " . $session_id . "\n";
731 +
732 + if ($session_data) {
733 + $transcript_content .= "User: " . ($session_data->user_identifier ?: 'Guest') . "\n";
734 + $transcript_content .= "Email: " . ($session_data->user_email ?: 'Not provided') . "\n";
735 + $transcript_content .= "Started: " . $session_data->created_at . "\n";
736 + }
737 +
738 + $transcript_content .= "\n" . str_repeat("=", 50) . "\n\n";
739 +
740 + // Add messages
741 + foreach ($messages as $msg) {
742 + $role_label = ($msg->role === 'user') ? 'User' : 'Assistant';
743 + $transcript_content .= "[{$msg->timestamp}] {$role_label}:\n";
744 + $transcript_content .= $msg->message . "\n\n";
745 + }
746 +
747 + // Create temporary file for attachment
748 + $upload_dir = wp_upload_dir();
749 + $temp_file = $upload_dir['basedir'] . '/mxchat-transcript-' . $session_id . '.txt';
750 + file_put_contents($temp_file, $transcript_content);
751 +
752 + // Prepare email
753 + $subject = sprintf('[%s] Chat Transcript - Session %s', get_bloginfo('name'), substr($session_id, 0, 8));
754 +
755 + $message = "Please find attached the full chat transcript.\n\n";
756 + $message .= "Session ID: {$session_id}\n";
757 +
758 + if ($session_data) {
759 + $message .= "User: " . ($session_data->user_identifier ?: 'Guest') . "\n";
760 + $message .= "Email: " . ($session_data->user_email ?: 'Not provided') . "\n";
761 + }
762 +
763 + $message .= "\nView online: " . admin_url('admin.php?page=mxchat-transcripts');
764 +
765 + // Send email with attachment
766 + $attachments = array($temp_file);
767 + $result = wp_mail($to, $subject, $message, '', $attachments);
768 +
769 + // Clean up temporary file
770 + if (file_exists($temp_file)) {
771 + unlink($temp_file);
772 + }
773 +
774 + return $result;
775 +}
776 +
777 +
778 +
779 +public function mxchat_handle_save_email_and_response() {
780 + //error_log('[DEBUG] ---------- mxchat_handle_save_email_and_response START ----------');
781 + //error_log('DEBUG: POST data: ' . print_r($_POST, true));
782 +
783 + // Validate nonce
784 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
785 + //error_log(esc_html__('[ERROR] Invalid nonce in mxchat_handle_save_email_and_response', 'mxchat'));
786 + wp_send_json_error(['message' => esc_html__('Invalid nonce.', 'mxchat')]);
787 + wp_die();
788 + }
789 +
790 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
791 + $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
792 + $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
793 +
794 + //error_log("[DEBUG] handle_save_email_and_response -> session_id: {$session_id}, email: {$email}, name: {$name}");
795 +
796 + if (empty($session_id) || empty($email)) {
797 + //error_log("[ERROR] Missing session_id or email: session_id={$session_id}, email={$email}");
798 + wp_send_json_error(['message' => esc_html__('Session ID or email is missing.', 'mxchat')]);
799 + wp_die();
800 + }
801 +
802 + // Validate name if provided (check if name field is enabled and name is required)
803 + $options = get_option('mxchat_options', []);
804 + $name_field_enabled = isset($options['enable_name_field']) &&
805 + ($options['enable_name_field'] === '1' || $options['enable_name_field'] === 'on');
806 +
807 + if ($name_field_enabled && (empty($name) || strlen(trim($name)) < 2 || strlen(trim($name)) > 100)) {
808 + //error_log("[ERROR] Invalid name: {$name} (enabled: {$name_field_enabled})");
809 + wp_send_json_error(['message' => esc_html__('Name must be between 2 and 100 characters.', 'mxchat')]);
810 + wp_die();
811 + }
812 +
813 + // 1) Always store email in wp_options
814 + $email_option_key = "mxchat_email_{$session_id}";
815 + update_option($email_option_key, $email);
816 + //error_log("[DEBUG] handle_save_email_and_response -> updated option: {$email_option_key} => {$email}");
817 +
818 + // Store name in wp_options if provided
819 + if (!empty($name)) {
820 + $name_option_key = "mxchat_name_{$session_id}";
821 + update_option($name_option_key, $name);
822 + //error_log("[DEBUG] handle_save_email_and_response -> updated option: {$name_option_key} => {$name}");
823 + }
824 +
825 + // 2) (Optional) Also store in DB if a row already exists
826 + global $wpdb;
827 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
828 +
829 + // Make sure we have a valid placeholder in prepare
830 + $sql = $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", $session_id);
831 + $session_count = $wpdb->get_var($sql);
832 +
833 + //error_log("[DEBUG] handle_save_email_and_response -> session_count for {$session_id}: {$session_count} (SQL: {$sql})");
834 +
835 + if ($session_count) {
836 + // Update both user_email and user_name if row(s) exist
837 + if (!empty($name)) {
838 + $update_sql = $wpdb->prepare(
839 + "UPDATE {$table_name} SET user_email = %s, user_name = %s WHERE session_id = %s",
840 + $email,
841 + $name,
842 + $session_id
843 + );
844 + } else {
845 + $update_sql = $wpdb->prepare(
846 + "UPDATE {$table_name} SET user_email = %s WHERE session_id = %s",
847 + $email,
848 + $session_id
849 + );
850 + }
851 + $wpdb->query($update_sql);
852 + //error_log("[DEBUG] handle_save_email_and_response -> DB updated: {$update_sql}");
853 + } else {
854 + //error_log("[INFO] handle_save_email_and_response -> No DB entry for {$session_id}, so email/name is only in wp_options.");
855 + }
856 +
857 + // Provide success response (same as original)
858 + $bot_message = __('Thanks for providing your email! You can continue chatting now.', 'mxchat');
859 + //error_log("[DEBUG] handle_save_email_and_response -> success, returning bot_message: {$bot_message}");
860 + wp_send_json_success(['message' => $bot_message]);
861 + wp_die();
862 +}
863 +
864 +public function mxchat_check_email_provided() {
865 + //error_log('[DEBUG] ---------- mxchat_check_email_provided START ----------');
866 +
867 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
868 + //error_log('[ERROR] Invalid nonce in mxchat_check_email_provided');
869 + wp_send_json_error(['message' => esc_html__('Invalid nonce', 'mxchat')]);
870 + }
871 +
872 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
873 + if (empty($session_id)) {
874 + //error_log('[ERROR] No session ID provided in mxchat_check_email_provided');
875 + wp_send_json_error(['message' => esc_html__('No session ID provided', 'mxchat')]);
876 + }
877 +
878 + // Check if the user is logged in
879 + if (is_user_logged_in()) {
880 + $current_user = wp_get_current_user();
881 + //error_log("[DEBUG] User is logged in as {$current_user->user_email}");
882 +
883 + // Get user's display name for logged in users
884 + $user_name = !empty($current_user->display_name) ? $current_user->display_name :
885 + (!empty($current_user->first_name) ? $current_user->first_name : '');
886 +
887 + $response_data = ['logged_in' => true, 'email' => $current_user->user_email];
888 + if (!empty($user_name)) {
889 + $response_data['name'] = $user_name;
890 + }
891 +
892 + wp_send_json_success($response_data);
893 + }
894 +
895 + // Check if name field is required
896 + $options = get_option('mxchat_options', []);
897 + $name_field_enabled = isset($options['enable_name_field']) &&
898 + ($options['enable_name_field'] === '1' || $options['enable_name_field'] === 'on');
899 +
900 + $email_option_key = "mxchat_email_{$session_id}";
901 + $stored_email = get_option($email_option_key, '');
902 +
903 + // Check for stored name
904 + $name_option_key = "mxchat_name_{$session_id}";
905 + $stored_name = get_option($name_option_key, '');
906 +
907 + //error_log("[DEBUG] mxchat_check_email_provided -> Checking email option: {$email_option_key}, found: {$stored_email}");
908 + //error_log("[DEBUG] mxchat_check_email_provided -> Checking name option: {$name_option_key}, found: {$stored_name}, required: " . ($name_field_enabled ? 'yes' : 'no'));
909 +
910 + // Check if we have email and name (if name is required)
911 + $has_required_info = !empty($stored_email);
912 +
913 + if ($name_field_enabled) {
914 + $has_required_info = $has_required_info && !empty($stored_name);
915 + }
916 +
917 + if ($has_required_info) {
918 + //error_log("[DEBUG] mxchat_check_email_provided -> Required info found, returning success");
919 +
920 + $response_data = ['email' => $stored_email];
921 + if (!empty($stored_name)) {
922 + $response_data['name'] = $stored_name;
923 + }
924 +
925 + wp_send_json_success($response_data);
926 + } else {
927 + //error_log("[DEBUG] mxchat_check_email_provided -> Required info missing, returning error");
928 + wp_send_json_error(['message' => esc_html__('No email found', 'mxchat')]);
929 + }
930 +}
931 +
932 +/**
933 + * Send error response in appropriate format based on streaming mode
934 + * ADDED: Helper method to consistently handle errors in both streaming and non-streaming modes
935 + *
936 + * @param string $error_message The error message to display
937 + * @param string $error_code Optional error code for debugging
938 + */
939 +private function send_error_response($error_message, $error_code = 'api_error') {
940 + if ($this->is_streaming) {
941 + echo "data: " . json_encode([
942 + 'error' => true,
943 + 'error_message' => $error_message,
944 + 'error_code' => $error_code,
945 + 'text' => $error_message,
946 + 'message' => $error_message
947 + ]) . "\n\n";
948 + echo "data: [DONE]\n\n";
949 + flush();
950 + } else {
951 + wp_send_json_error([
952 + 'error_message' => $error_message,
953 + 'error_code' => $error_code
954 + ]);
955 + }
956 + wp_die();
957 +}
958 +
959 +public function mxchat_handle_chat_request() {
960 + global $wpdb;
961 +
962 + // Debug: Log incoming bot_id
963 + $bot_id = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
964 + error_log("=== MXCHAT DEBUG: Starting chat request ===");
965 + error_log("MXCHAT DEBUG: Bot ID received: " . $bot_id);
966 +
967 + // Get bot-specific options
968 + $bot_options = $this->get_bot_options($bot_id);
969 + $current_options = !empty($bot_options) ? $bot_options : $this->options;
970 +
971 + // Check if this is a streaming request
972 + $is_streaming = isset($_POST['action']) && $_POST['action'] === 'mxchat_stream_chat' &&
973 + isset($current_options['enable_streaming_toggle']) && $current_options['enable_streaming_toggle'] === 'on';
974 +
975 + // ADDED: Store streaming state in class property for use in private methods
976 + $this->is_streaming = $is_streaming;
977 +
978 + // Set streaming headers if needed
979 + if ($is_streaming) {
980 + // Disable output buffering
981 + while (ob_get_level()) {
982 + ob_end_flush(); // Changed from ob_end_clean()
983 + }
984 +
985 + // Set headers for SSE
986 + header('Content-Type: text/event-stream');
987 + header('Cache-Control: no-cache');
988 + header('Connection: keep-alive');
989 + header('X-Accel-Buffering: no');
990 +
991 + // Add these new lines:
992 + ob_implicit_flush(true);
993 + flush();
994 + }
995 +
996 + // Check if MX Chat Moderation is active
997 + if (class_exists('MX_Chat_Moderation')) {
998 + // Get user email and IP
999 + $user_email = '';
1000 + $user_ip = $_SERVER['REMOTE_ADDR'];
1001 +
1002 + // If user is logged in, get their email
1003 + if (is_user_logged_in()) {
1004 + $current_user = wp_get_current_user();
1005 + $user_email = $current_user->user_email;
1006 + }
1007 +
1008 + // Create ban handler instance
1009 + $ban_handler = new MX_Chat_Ban_Handler();
1010 +
1011 + // Check if user is banned by IP
1012 + if ($ban_handler->check_ban($user_ip, 'ip')) {
1013 + wp_send_json([
1014 + 'success' => false,
1015 + 'message' => esc_html__('Access denied. Your IP address has been banned.', 'mxchat'),
1016 + 'status' => 'banned'
1017 + ]);
1018 + wp_die();
1019 + }
1020 +
1021 + // If user is logged in, also check email
1022 + if (!empty($user_email) && $ban_handler->check_ban($user_email, 'email')) {
1023 + wp_send_json([
1024 + 'success' => false,
1025 + 'message' => esc_html__('Access denied. Your email address has been banned.', 'mxchat'),
1026 + 'status' => 'banned'
1027 + ]);
1028 + wp_die();
1029 + }
1030 + }
1031 +
1032 + $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
1033 + $this->productCardHtml = '';
1034 +
1035 + // Get the actual WordPress user ID if logged in
1036 + $is_logged_in = is_user_logged_in();
1037 + if ($is_logged_in) {
1038 + $user_id = get_current_user_id(); // This will get the actual WordPress user ID
1039 + } else {
1040 + // For logged-out users, use your existing identifier method
1041 + $user_id = $this->mxchat_get_user_identifier();
1042 + }
1043 +
1044 + // Get and sanitize the user identifier
1045 + $user_id = sanitize_key($user_id);
1046 +
1047 + // Check rate limit using new settings structure
1048 + $rate_limit_result = $this->check_rate_limit();
1049 +
1050 + if ($rate_limit_result !== true) {
1051 + wp_send_json([
1052 + 'success' => false,
1053 + 'message' => $rate_limit_result['message'],
1054 + 'status' => 'rate_limit_exceeded'
1055 + ]);
1056 + wp_die();
1057 + }
1058 +
1059 + // Rest of your existing code...
1060 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
1061 +
1062 + if (empty($session_id)) {
1063 + wp_send_json_error(esc_html__('Session ID is missing.', 'mxchat'));
1064 + wp_die();
1065 + }
1066 +
1067 + // SECURITY FIX: Verify session ownership before processing chat request
1068 + // If IP/user changed, signal frontend to reset session instead of blocking
1069 + $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
1070 + $session_owner = get_option("mxchat_session_owner_{$session_id}");
1071 +
1072 + if ($session_owner && $session_owner !== $current_user_identifier) {
1073 + // Instead of blocking, tell frontend to start a fresh session
1074 + wp_send_json_error([
1075 + 'message' => esc_html__('Your session has expired. Starting a new conversation.', 'mxchat'),
1076 + 'code' => 'session_expired',
1077 + 'action' => 'reset_session'
1078 + ]);
1079 + wp_die();
1080 + }
1081 +
1082 + // Validate and sanitize the incoming message
1083 + if (empty($_POST['message'])) {
1084 + wp_send_json_error(esc_html__('No message received.', 'mxchat'));
1085 + wp_die();
1086 + }
1087 +
1088 +
1089 + // Track originating page for first message in session
1090 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1091 +
1092 + // Check if originating page columns exist
1093 + $columns_exist = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'");
1094 +
1095 + if ($columns_exist) {
1096 + // Check if this session already has messages
1097 + $message_count = $wpdb->get_var($wpdb->prepare(
1098 + "SELECT COUNT(*) FROM $table_name WHERE session_id = %s",
1099 + $session_id
1100 + ));
1101 +
1102 + // If this is the first message in the session
1103 + if ($message_count == 0) {
1104 + // Get originating page from JavaScript (preferred) or HTTP_REFERER (fallback)
1105 + $originating_url = '';
1106 + $originating_title = '';
1107 +
1108 + // Try to get from POST data first (sent by JavaScript)
1109 + if (isset($_POST['current_page_url'])) {
1110 + $originating_url = esc_url_raw($_POST['current_page_url']);
1111 + $originating_title = isset($_POST['current_page_title'])
1112 + ? sanitize_text_field($_POST['current_page_title'])
1113 + : '';
1114 + }
1115 + // Fallback to HTTP_REFERER if not provided by JavaScript
1116 + else if (isset($_SERVER['HTTP_REFERER'])) {
1117 + $originating_url = esc_url_raw($_SERVER['HTTP_REFERER']);
1118 + }
1119 +
1120 + // Generate title if we have URL but no title
1121 + if ($originating_url && empty($originating_title)) {
1122 + $parsed_url = parse_url($originating_url);
1123 + $path = isset($parsed_url['path']) ? trim($parsed_url['path'], '/') : '';
1124 +
1125 + if (empty($path) || $path === 'index.php' || $path === 'index.html') {
1126 + $originating_title = 'Homepage';
1127 + } else {
1128 + // Clean up the path to make a readable title
1129 + $originating_title = str_replace(['-', '_', '/', '.php', '.html'], ' ', $path);
1130 + $originating_title = ucwords(trim($originating_title));
1131 + }
1132 + }
1133 +
1134 + // Store for later use when saving the message
1135 + $this->pending_originating_page = [
1136 + 'url' => $originating_url,
1137 + 'title' => $originating_title
1138 + ];
1139 + }
1140 + }
1141 +
1142 +
1143 +
1144 + // Get page context if provided
1145 + $page_context = null;
1146 + if (isset($_POST['page_context']) && !empty($_POST['page_context'])) {
1147 + $page_context_raw = stripslashes($_POST['page_context']);
1148 + $page_context = json_decode($page_context_raw, true);
1149 +
1150 + // Validate page context structure
1151 + if (is_array($page_context) &&
1152 + isset($page_context['url']) &&
1153 + isset($page_context['title']) &&
1154 + isset($page_context['content'])) {
1155 +
1156 + // Sanitize page context
1157 + $page_context['url'] = esc_url_raw($page_context['url']);
1158 + $page_context['title'] = sanitize_text_field($page_context['title']);
1159 + $page_context['content'] = wp_kses_post($page_context['content']);
1160 + } else {
1161 + $page_context = null;
1162 + }
1163 + }
1164 +
1165 + // Modify the message sanitization to preserve PHP tags in code blocks
1166 + $allowed_tags = [
1167 + 'pre' => [],
1168 + 'code' => ['class' => true],
1169 + 'span' => ['class' => true],
1170 + 'div' => ['class' => true],
1171 + ];
1172 +
1173 + // First preserve code blocks
1174 + $message = preg_replace_callback('/<pre><code.*?>.*?<\/code><\/pre>/s', function($matches) {
1175 + return htmlspecialchars_decode($matches[0]);
1176 + }, $_POST['message']);
1177 +
1178 + // Then apply sanitization
1179 + $message = wp_kses($message, $allowed_tags);
1180 +
1181 + // Preserve code blocks from markdown conversion
1182 + $message = preg_replace('/```(\w+)?\s*([\s\S]+?)```/s', '<pre><code class="$1">$2</code></pre>', $message);
1183 + $message = apply_filters('mxchat_filter_message', $message, 'prompt', $session_id);
1184 +
1185 + // ===== SIMPLIFIED TESTING PANEL INITIALIZATION =====
1186 + // Always initialize testing data for admins (no toggle needed)
1187 + $testing_data = null;
1188 + if (current_user_can('administrator')) {
1189 + // For vision messages, use the original user message for the query display
1190 + $query_for_testing = $message;
1191 + if (isset($_POST['vision_processed']) && $_POST['vision_processed'] && isset($_POST['original_user_message'])) {
1192 + $query_for_testing = sanitize_textarea_field($_POST['original_user_message']);
1193 + }
1194 +
1195 + $testing_data = [
1196 + 'query' => $query_for_testing,
1197 + 'timestamp' => time(),
1198 + 'top_matches' => [],
1199 + 'action_matches' => [], // Initialize action matches array
1200 + 'page_context' => $page_context, // Include page context in testing data
1201 + 'is_vision' => isset($_POST['vision_processed']) && $_POST['vision_processed'],
1202 + 'bot_id' => $bot_id // Include bot ID in testing data
1203 + ];
1204 +
1205 + // Get similarity threshold from bot options or default options
1206 + $similarity_threshold = isset($current_options['similarity_threshold'])
1207 + ? ((int) $current_options['similarity_threshold']) / 100
1208 + : 0.35;
1209 +
1210 + $testing_data['similarity_threshold'] = $similarity_threshold;
1211 +
1212 + // Determine knowledge base type using bot-specific config
1213 + $bot_pinecone_config = $this->get_bot_pinecone_config($bot_id);
1214 + $use_pinecone = isset($bot_pinecone_config['use_pinecone']) ? $bot_pinecone_config['use_pinecone'] : false;
1215 + $testing_data['knowledge_base_type'] = $use_pinecone ? 'Pinecone' : 'WordPress Database';
1216 + }
1217 + // ===== END SIMPLIFIED TESTING INITIALIZATION =====
1218 +
1219 + // Add debug before and after:
1220 + //error_log('MxChat Core: About to call mxchat_pre_process_message filter with message: ' . $message);
1221 + $pre_processed_result = apply_filters('mxchat_pre_process_message', $message, $user_id, $session_id);
1222 + //error_log('MxChat Core: Filter returned: ' . (is_array($pre_processed_result) ? 'array' : $pre_processed_result));
1223 +
1224 +
1225 + // If the pre-processing returned a result (not the original message), use it directly
1226 + if (is_array($pre_processed_result) && isset($pre_processed_result['text'])) {
1227 + // Save the AI response
1228 + $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['text']);
1229 +
1230 + // Save HTML content if provided
1231 + if (!empty($pre_processed_result['html'])) {
1232 + $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['html']);
1233 + }
1234 +
1235 + // Add testing data if admin
1236 + $response_data = [
1237 + 'text' => $pre_processed_result['text'],
1238 + 'html' => $pre_processed_result['html'] ?? '',
1239 + 'session_id' => $session_id
1240 + ];
1241 +
1242 + if ($testing_data !== null) {
1243 + $response_data['testing_data'] = $testing_data;
1244 + }
1245 +
1246 + wp_send_json($response_data);
1247 + wp_die();
1248 + }
1249 +
1250 + // Save the user's message - handle vision processed messages differently
1251 + if (isset($_POST['vision_processed']) && $_POST['vision_processed'] && isset($_POST['original_user_message'])) {
1252 + // For vision messages, save the original user message with image indicator
1253 + $original_message = sanitize_textarea_field($_POST['original_user_message']);
1254 + if (isset($_POST['vision_images_count']) && $_POST['vision_images_count'] > 0) {
1255 + $image_count = intval($_POST['vision_images_count']);
1256 + $original_message .= " [{$image_count} image(s)]";
1257 + }
1258 + $this->mxchat_save_chat_message($session_id, 'user', $original_message);
1259 + } else {
1260 + // Regular message - save as normal
1261 + $this->mxchat_save_chat_message($session_id, 'user', $message);
1262 + }
1263 +
1264 +
1265 + if (is_email($message)) {
1266 + // Add the email to Loops
1267 + $this->add_email_to_loops($message);
1268 +
1269 + // Get the user's success message instruction using current_options
1270 + $user_success_message = $current_options['email_capture_response'] ?? __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
1271 +
1272 + // Set instruction for AI using the user's success message
1273 + $this->current_action_instruction = $user_success_message;
1274 +
1275 + // Clear the email capture transient since we got the email
1276 + delete_transient('mxchat_email_capture_' . $user_id);
1277 + }
1278 +
1279 + // Check if we're in an email capture flow but user hasn't provided email yet
1280 + elseif (get_transient('mxchat_email_capture_' . $user_id)) {
1281 + // Check if the message contains an email (not the whole message being an email)
1282 + if (preg_match('/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/', $message, $matches)) {
1283 + $extracted_email = $matches[0];
1284 +
1285 + // Add the extracted email to Loops
1286 + $this->add_email_to_loops($extracted_email);
1287 +
1288 + // Get the user's success message instruction using current_options
1289 + $user_success_message = $current_options['email_capture_response'] ?? __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
1290 +
1291 + // Set instruction for AI using the user's success message
1292 + $this->current_action_instruction = $user_success_message;
1293 +
1294 + // Clear the email capture transient since we got the email
1295 + delete_transient('mxchat_email_capture_' . $user_id);
1296 + }
1297 + // If no email found but we're in capture mode, remind them
1298 + else {
1299 + // Get the original instruction to remind them using current_options
1300 + $original_instruction = $current_options['triggered_phrase_response'] ?? __("Please provide your email address.", 'mxchat');
1301 + $this->current_action_instruction = $original_instruction;
1302 + }
1303 + }
1304 +
1305 + $intent_info = '';
1306 +
1307 + // Check chat mode
1308 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
1309 +
1310 + // Handle agent mode
1311 + // Handle agent mode
1312 + if ($chat_mode === 'agent') {
1313 + // First, check for switch intent before doing anything else
1314 + $intent_matched = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
1315 +
1316 + // Capture action analysis for testing panel after intent check
1317 + if ($testing_data !== null && isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
1318 + $testing_data['action_matches'] = $this->last_action_analysis;
1319 + }
1320 +
1321 + // Around line 506, in the agent mode handling section:
1322 + if ($intent_matched && !empty($this->fallbackResponse['text'])) {
1323 + // Update chat mode first
1324 + update_option("mxchat_mode_{$session_id}", 'ai');
1325 +
1326 + // Clear any existing PDF context to start fresh
1327 + $this->clear_pdf_transients($session_id);
1328 +
1329 + // Prepare clean switch response with explicit chat_mode
1330 + $response_data = [
1331 + 'text' => $this->fallbackResponse['text'],
1332 + 'html' => $this->fallbackResponse['html'] ?? '',
1333 + 'session_id' => $session_id,
1334 + 'chat_mode' => 'ai' // EXPLICITLY SET THIS
1335 + ];
1336 +
1337 + if ($testing_data !== null) {
1338 + $response_data['testing_data'] = $testing_data;
1339 + }
1340 +
1341 + // Save the mode switch message
1342 + $this->mxchat_save_chat_message($session_id, 'system', esc_html__('Switched to AI chat mode', 'mxchat'));
1343 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
1344 +
1345 + // Send response and exit
1346 + wp_send_json($response_data);
1347 + wp_die();
1348 + } elseif (!$intent_matched) {
1349 + // No intent matched, handle live agent message
1350 + try {
1351 + $this->mxchat_send_user_message_to_agent($message, $user_id, $session_id);
1352 +
1353 + $agent_response = [
1354 + 'status' => 'waiting_for_agent',
1355 + 'message' => esc_html__('Message sent to live agent.', 'mxchat')
1356 + ];
1357 +
1358 + if ($testing_data !== null) {
1359 + $agent_response['testing_data'] = $testing_data;
1360 + }
1361 +
1362 + wp_send_json_success($agent_response);
1363 + } catch (\Exception $e) {
1364 + wp_send_json_error(esc_html__('Failed to send message to agent', 'mxchat'));
1365 + }
1366 + wp_die();
1367 + }
1368 + }
1369 +
1370 + // Step 1: Check for new PDF URL in the message
1371 + if (!isset($_POST['vision_processed']) && preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
1372 + $new_pdf_url = $matches[0];
1373 +
1374 + // Check if this is likely a PDF-related request
1375 + $pdf_keywords = ['pdf', 'document', 'read', 'analyze'];
1376 + $is_pdf_request = false;
1377 +
1378 + foreach ($pdf_keywords as $keyword) {
1379 + if (stripos($message, $keyword) !== false) {
1380 + $is_pdf_request = true;
1381 + break;
1382 + }
1383 + }
1384 +
1385 + // If it looks like a PDF request or we're waiting for a PDF URL
1386 + if ($is_pdf_request || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
1387 + // Validate HTTPS
1388 + if (wp_http_validate_url($new_pdf_url) && parse_url($new_pdf_url, PHP_URL_SCHEME) === 'https') {
1389 + // Extract filename from URL
1390 + $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
1391 +
1392 + // Clear previous PDF transients
1393 + $this->clear_pdf_transients($session_id);
1394 +
1395 + // Process new PDF using current_options
1396 + $max_pages = $current_options['pdf_max_pages'] ?? 69;
1397 + $embeddings = $this->fetch_and_split_pdf_pages($new_pdf_url, $max_pages);
1398 +
1399 + if ($embeddings === 'too_many_pages') {
1400 + $error_text = sprintf(
1401 + $current_options['pdf_intent_error_text'] ??
1402 + esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
1403 + $max_pages
1404 + );
1405 + $this->fallbackResponse['text'] = $error_text;
1406 + } elseif ($embeddings) {
1407 + // Store new PDF information
1408 + $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
1409 +
1410 + // If the filename is generic, create a more descriptive one
1411 + if (in_array($pdf_filename, ['results_download.php', 'download.php', 'view.php', 'pdf.php']) ||
1412 + strpos($pdf_filename, '.php') !== false) {
1413 + $pdf_filename = 'Document_' . date('Y-m-d_H-i') . '.pdf';
1414 + }
1415 +
1416 + set_transient('mxchat_pdf_url_' . $session_id, $new_pdf_url, HOUR_IN_SECONDS);
1417 + set_transient('mxchat_pdf_filename_' . $session_id, $pdf_filename, HOUR_IN_SECONDS);
1418 + set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
1419 + set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
1420 +
1421 + $success_text = $current_options['pdf_intent_success_text'] ??
1422 + esc_html__("I've processed the new PDF '{$pdf_filename}'. What questions do you have about it?", 'mxchat');
1423 +
1424 + $pdf_response = [
1425 + 'success' => true,
1426 + 'message' => $success_text,
1427 + 'data' => [
1428 + 'filename' => $pdf_filename
1429 + ]
1430 + ];
1431 +
1432 + if ($testing_data !== null) {
1433 + $pdf_response['testing_data'] = $testing_data;
1434 + }
1435 +
1436 + wp_send_json($pdf_response);
1437 + wp_die();
1438 + } else {
1439 + $error_text = $current_options['pdf_intent_error_text'] ??
1440 + esc_html__("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
1441 + $this->fallbackResponse['text'] = $error_text;
1442 + }
1443 +
1444 + $pdf_error_response = [
1445 + 'success' => false,
1446 + 'message' => $this->fallbackResponse['text']
1447 + ];
1448 +
1449 + if ($testing_data !== null) {
1450 + $pdf_error_response['testing_data'] = $testing_data;
1451 + }
1452 +
1453 + wp_send_json($pdf_error_response);
1454 + wp_die();
1455 + }
1456 + }
1457 + }
1458 +
1459 +
1460 + // Step 2: Detect intent and handle intent-based responses
1461 + $intent_result = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
1462 +
1463 + // Capture action analysis for testing panel after intent check
1464 + if ($testing_data !== null && isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
1465 + $testing_data['action_matches'] = $this->last_action_analysis;
1466 + }
1467 +
1468 + // Step 3: Handle the intent result appropriately
1469 + if ($intent_result !== false) {
1470 + // Intent was matched - ALWAYS send as JSON response, never streaming
1471 +
1472 + if (is_array($intent_result) && (isset($intent_result['text']) || isset($intent_result['html']))) {
1473 + // Intent returned a direct response array
1474 + $response_data = [
1475 + 'text' => $intent_result['text'] ?? '',
1476 + 'html' => $intent_result['html'] ?? '',
1477 + 'session_id' => $session_id
1478 + ];
1479 +
1480 + // IMPORTANT: Include chat_mode if present (for WhatsApp, Slack, etc.)
1481 + if (isset($intent_result['chat_mode'])) {
1482 + $response_data['chat_mode'] = $intent_result['chat_mode'];
1483 + }
1484 +
1485 + if ($testing_data !== null) {
1486 + $response_data['testing_data'] = $testing_data;
1487 + }
1488 +
1489 + // Clear streaming headers if they were set
1490 + if ($is_streaming) {
1491 + header_remove('Content-Type');
1492 + header_remove('Cache-Control');
1493 + header_remove('Connection');
1494 + header_remove('X-Accel-Buffering');
1495 + header('Content-Type: application/json');
1496 + }
1497 +
1498 + wp_send_json($response_data);
1499 + wp_die();
1500 + } else if ($intent_result === true && (!empty($this->fallbackResponse['text']) || !empty($this->fallbackResponse['html']))) {
1501 + // Intent returned true and set fallbackResponse
1502 +
1503 + // SAVE TO TRANSCRIPT FIRST
1504 + if (!empty($this->fallbackResponse['text'])) {
1505 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
1506 + }
1507 + if (!empty($this->fallbackResponse['html'])) {
1508 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
1509 + }
1510 +
1511 + $response_data = [
1512 + 'text' => $this->fallbackResponse['text'] ?? '',
1513 + 'html' => $this->fallbackResponse['html'] ?? '',
1514 + 'session_id' => $session_id
1515 + ];
1516 +
1517 + if (isset($this->fallbackResponse['chat_mode'])) {
1518 + $response_data['chat_mode'] = $this->fallbackResponse['chat_mode'];
1519 + }
1520 +
1521 + if ($testing_data !== null) {
1522 + $response_data['testing_data'] = $testing_data;
1523 + }
1524 +
1525 + // Clear streaming headers if they were set
1526 + if ($is_streaming) {
1527 + header_remove('Content-Type');
1528 + header_remove('Cache-Control');
1529 + header_remove('Connection');
1530 + header_remove('X-Accel-Buffering');
1531 + header('Content-Type: application/json');
1532 + }
1533 +
1534 + wp_send_json($response_data);
1535 + wp_die();
1536 + }
1537 + }
1538 +
1539 + // If we get here, no intent matched OR the intent didn't provide a usable response
1540 +
1541 + // Step 4: Generate AI response
1542 + $conversation_history = $this->mxchat_fetch_conversation_history_for_ai($session_id);
1543 + $this->mxchat_increment_chat_count();
1544 +
1545 + // Generate embedding for the user's query - USE BOT-SPECIFIC API KEY
1546 + $api_key = $current_options['api_key'] ?? $this->options['api_key'];
1547 + $user_message_embedding = $this->mxchat_generate_embedding($message, $api_key);
1548 +
1549 + // Check if the embedding generation returned an error
1550 + if (is_array($user_message_embedding) && isset($user_message_embedding['error'])) {
1551 + $error_message = $user_message_embedding['error'];
1552 + $error_code = $user_message_embedding['error_code'] ?? 'embedding_error';
1553 +
1554 + // FIXED: Send error in appropriate format based on streaming mode
1555 + if ($is_streaming) {
1556 + echo "data: " . json_encode([
1557 + 'error' => true,
1558 + 'error_message' => $error_message,
1559 + 'error_code' => $error_code,
1560 + 'text' => $error_message,
1561 + 'message' => $error_message
1562 + ]) . "\n\n";
1563 + echo "data: [DONE]\n\n";
1564 + flush();
1565 + } else {
1566 + wp_send_json_error([
1567 + 'error_message' => $error_message,
1568 + 'error_code' => $error_code
1569 + ]);
1570 + }
1571 + wp_die();
1572 + }
1573 +
1574 + // Check if the embedding is valid
1575 + if (!is_array($user_message_embedding) || empty($user_message_embedding)) {
1576 + $error_message = esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat');
1577 +
1578 + // FIXED: Send error in appropriate format based on streaming mode
1579 + if ($is_streaming) {
1580 + echo "data: " . json_encode([
1581 + 'error' => true,
1582 + 'error_message' => $error_message,
1583 + 'error_code' => 'invalid_embedding',
1584 + 'text' => $error_message,
1585 + 'message' => $error_message
1586 + ]) . "\n\n";
1587 + echo "data: [DONE]\n\n";
1588 + flush();
1589 + } else {
1590 + wp_send_json_error([
1591 + 'error_message' => $error_message,
1592 + 'error_code' => 'invalid_embedding'
1593 + ]);
1594 + }
1595 + wp_die();
1596 + }
1597 +
1598 + // Build context with both knowledge base and PDF content if available
1599 + $context_content = "User asked: '{$message}'\n\n";
1600 +
1601 + // Add action instruction if present (add this right after the above line)
1602 + if (!empty($this->current_action_instruction)) {
1603 + $context_content .= "===== SPECIAL INSTRUCTION =====\n";
1604 + $context_content .= "IMPORTANT: " . $this->current_action_instruction . "\n";
1605 + $context_content .= "Respond naturally and conversationally while following this instruction.\n";
1606 + $context_content .= "===== END SPECIAL INSTRUCTION =====\n\n";
1607 +
1608 + // Clear the instruction after using it
1609 + $this->current_action_instruction = null;
1610 + }
1611 +
1612 +
1613 + // Add page context if available and contextual awareness is enabled using current_options
1614 + if ($page_context && isset($current_options['contextual_awareness_toggle']) && $current_options['contextual_awareness_toggle'] === 'on') {
1615 + $context_content .= "===== CURRENT PAGE CONTEXT =====\n";
1616 + $context_content .= "Page URL: " . $page_context['url'] . "\n";
1617 + $context_content .= "Page Title: " . $page_context['title'] . "\n";
1618 + $context_content .= "Page Content: " . $page_context['content'] . "\n";
1619 + $context_content .= "===== END CURRENT PAGE CONTEXT =====\n\n";
1620 + }
1621 +
1622 + // Get relevant content from knowledge base - PASS BOT_ID
1623 + $relevant_content = $this->mxchat_find_relevant_content($user_message_embedding, $bot_id);
1624 +
1625 + // NEW: Also extract URLs from system instructions
1626 + $system_instructions = $this->get_system_instructions($bot_id);
1627 + if (!empty($system_instructions)) {
1628 + preg_match_all(
1629 + '#\bhttps?://[^\s<>"\']+#i',
1630 + $system_instructions,
1631 + $system_instruction_urls
1632 + );
1633 +
1634 + if (!empty($system_instruction_urls[0])) {
1635 + // Merge with existing valid URLs
1636 + $this->current_valid_urls = array_merge(
1637 + $this->current_valid_urls,
1638 + $system_instruction_urls[0]
1639 + );
1640 + // Remove duplicates
1641 + $this->current_valid_urls = array_unique($this->current_valid_urls);
1642 +
1643 + error_log("Added " . count($system_instruction_urls[0]) . " URLs from system instructions");
1644 + }
1645 + }
1646 +
1647 +// ===== CAPTURE REAL SIMILARITY DATA FOR ADMINS =====
1648 +if ($testing_data !== null && $this->last_similarity_analysis !== null) {
1649 + // Update testing data with the REAL similarity analysis
1650 + $testing_data['top_matches'] = $this->last_similarity_analysis['top_matches'];
1651 + $testing_data['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
1652 + $testing_data['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'];
1653 +}
1654 +// ===== END SIMILARITY DATA CAPTURE =====
1655 +
1656 +// NEW: Add valid URLs to testing data for admin panel display (AFTER similarity data)
1657 +if ($testing_data !== null && !empty($this->current_valid_urls)) {
1658 + $testing_data['approved_urls'] = array_values($this->current_valid_urls);
1659 + error_log("Added " . count($this->current_valid_urls) . " approved URLs to testing data");
1660 +}
1661 +
1662 + if (!empty($relevant_content)) {
1663 + $context_content .= "===== OFFICIAL KNOWLEDGE DATABASE CONTENT =====\n" . $relevant_content . "\n===== END OF OFFICIAL KNOWLEDGE DATABASE CONTENT =====\n\n";
1664 + } else {
1665 + $context_content .= "===== NO RELEVANT CONTENT FOUND IN KNOWLEDGE DATABASE =====\n";
1666 + }
1667 +
1668 + // NEW: Add approved URLs list to context for AI
1669 + if (!empty($this->current_valid_urls)) {
1670 + $context_content .= "===== APPROVED URLS FOR CITATIONS =====\n";
1671 + $context_content .= "You may ONLY use these exact URLs in your response:\n";
1672 + foreach ($this->current_valid_urls as $url) {
1673 + $context_content .= "- " . $url . "\n";
1674 + }
1675 + $context_content .= "\nCRITICAL: Do NOT create, modify, extend, or invent any other URLs. ";
1676 + $context_content .= "===== END APPROVED URLS =====\n\n";
1677 + }
1678 +
1679 + // Check for and include PDF content
1680 + $pdf_url = get_transient('mxchat_pdf_url_' . $session_id);
1681 + $pdf_embeddings = get_transient('mxchat_pdf_embeddings_' . $session_id);
1682 + $pdf_filename = get_transient('mxchat_pdf_filename_' . $session_id);
1683 + if ($pdf_url && $pdf_embeddings && get_transient('mxchat_include_pdf_in_context_' . $session_id)) {
1684 + $relevant_pdf_pages = $this->find_relevant_pdf_pages($user_message_embedding, $pdf_embeddings);
1685 + if (!empty($relevant_pdf_pages)) {
1686 + $context_content .= "Relevant content from PDF document '{$pdf_filename}':\n";
1687 + foreach ($relevant_pdf_pages as $page_data) {
1688 + $context_content .= "Page {$page_data['page_number']} of '{$pdf_filename}': {$page_data['text']}\n";
1689 + }
1690 + $context_content .= "\n";
1691 + }
1692 + }
1693 +
1694 + // Check for and include Word content
1695 + $word_url = get_transient('mxchat_word_url_' . $session_id);
1696 + $word_embeddings = get_transient('mxchat_word_embeddings_' . $session_id);
1697 + $word_filename = get_transient('mxchat_word_filename_' . $session_id);
1698 + if ($word_url && $word_embeddings && get_transient('mxchat_include_word_in_context_' . $session_id)) {
1699 + $relevant_word_chunks = $this->word_handler->mxchat_find_relevant_word_chunks($user_message_embedding, $word_embeddings);
1700 + if (!empty($relevant_word_chunks)) {
1701 + $context_content .= "Relevant content from Word document '{$word_filename}':\n";
1702 + foreach ($relevant_word_chunks as $chunk_data) {
1703 + $context_content .= "Section {$chunk_data['chunk_number']} of '{$word_filename}': {$chunk_data['text']}\n";
1704 + }
1705 + $context_content .= "\n";
1706 + }
1707 + }
1708 +
1709 + $context_content = apply_filters('mxchat_prepare_context', $context_content, $session_id);
1710 +
1711 + // Extract model from current options for bot-specific model support
1712 + $selected_model = isset($current_options['model']) ? $current_options['model'] : 'gpt-4o';
1713 +
1714 + $response = $this->mxchat_generate_response(
1715 + $context_content,
1716 + $current_options['api_key'] ?? $this->options['api_key'],
1717 + $current_options['xai_api_key'] ?? $this->options['xai_api_key'],
1718 + $current_options['claude_api_key'] ?? $this->options['claude_api_key'],
1719 + $current_options['deepseek_api_key'] ?? $this->options['deepseek_api_key'],
1720 + $current_options['gemini_api_key'] ?? $this->options['gemini_api_key'],
1721 + $current_options['openrouter_api_key'] ?? $this->options['openrouter_api_key'],
1722 + $conversation_history,
1723 + $is_streaming,
1724 + $session_id,
1725 + $testing_data,
1726 + $selected_model
1727 + );
1728 +
1729 + // Handle streaming vs non-streaming responses
1730 + if ($is_streaming) {
1731 + // Check if streaming actually happened or if it fell back to regular response
1732 + if ($response === true) {
1733 + wp_die();
1734 + }
1735 + // If we get here, streaming fell back to regular response, continue
1736 + // But if there's an error, we need to send it as SSE format since headers are already set
1737 + if (is_array($response) && isset($response['error'])) {
1738 + $error_message = $response['error'];
1739 + $error_code = $response['error_code'] ?? 'api_error';
1740 + // Send error in SSE format that the client JS can handle
1741 + echo "data: " . json_encode([
1742 + 'error' => true,
1743 + 'error_message' => $error_message,
1744 + 'error_code' => $error_code,
1745 + 'text' => $error_message, // Also include as text for fallback handling
1746 + 'message' => $error_message
1747 + ]) . "\n\n";
1748 + echo "data: [DONE]\n\n";
1749 + flush();
1750 + wp_die();
1751 + }
1752 + }
1753 +
1754 + // Check if the response is an error array (non-streaming mode)
1755 + if (is_array($response) && isset($response['error'])) {
1756 + wp_send_json_error([
1757 + 'error_message' => $response['error'],
1758 + 'error_code' => $response['error_code'] ?? 'api_error'
1759 + ]);
1760 + wp_die();
1761 + }
1762 +
1763 + // DEBUG: Check what we have
1764 + error_log("=== BEFORE URL VALIDATION ===");
1765 + error_log("current_valid_urls is empty? " . (empty($this->current_valid_urls) ? 'YES' : 'NO'));
1766 + error_log("current_valid_urls count: " . count($this->current_valid_urls));
1767 + error_log("current_valid_urls content: " . print_r($this->current_valid_urls, true));
1768 +
1769 + // If we get here, the response is valid text - now validate URLs
1770 + if (!empty($this->current_valid_urls)) {
1771 + error_log("CALLING validate_and_clean_urls");
1772 + $response = $this->validate_and_clean_urls($response, $this->current_valid_urls);
1773 + } else {
1774 + error_log("SKIPPING validation - current_valid_urls is empty");
1775 + }
1776 + // ===== END URL VALIDATION =====
1777 +
1778 + // Prepare RAG context data for storage (only include documents used for context)
1779 + $rag_context_for_storage = null;
1780 + if ($this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches'])) {
1781 + $rag_context_for_storage = [
1782 + 'top_matches' => $this->last_similarity_analysis['top_matches'],
1783 + 'approved_urls' => $this->current_valid_urls ?? [],
1784 + 'similarity_threshold' => $this->last_similarity_analysis['threshold_used'] ?? 0.35,
1785 + 'knowledge_base_type' => $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database',
1786 + 'total_documents_checked' => $this->last_similarity_analysis['total_checked'] ?? 0
1787 + ];
1788 + }
1789 +
1790 + // Save the cleaned response with RAG context
1791 + $this->mxchat_save_chat_message($session_id, 'bot', $response, null, $rag_context_for_storage);
1792 +
1793 + // Step 5: Save additional content if available
1794 + if (!empty($this->productCardHtml)) {
1795 + $this->mxchat_save_chat_message($session_id, 'bot', $this->productCardHtml);
1796 + }
1797 +
1798 + if (!empty($this->fallbackResponse['html'])) {
1799 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
1800 + }
1801 +
1802 + // Step 6: Return the response
1803 + $response_data = [
1804 + 'text' => $response,
1805 + 'html' => !empty($this->productCardHtml) ? $this->productCardHtml : ($this->fallbackResponse['html'] ?? ''),
1806 + 'session_id' => $session_id
1807 + ];
1808 +
1809 + // Always add testing data for admins (no toggle needed)
1810 + if ($testing_data !== null) {
1811 + $response_data['testing_data'] = $testing_data;
1812 + }
1813 +
1814 + wp_send_json($response_data);
1815 + wp_die();
1816 +}
1817 +
1818 +/**
1819 + * Get bot-specific options for multi-bot functionality
1820 + * Falls back to default options if bot_id is 'default' or multi-bot add-on is not active
1821 + */
1822 +// Also debug the bot options retrieval
1823 +private function get_bot_options($bot_id = 'default') {
1824 + error_log("MXCHAT DEBUG: get_bot_options called for bot: " . $bot_id);
1825 +
1826 + if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
1827 + error_log("MXCHAT DEBUG: Using default options (no multi-bot or bot is 'default')");
1828 + return array();
1829 + }
1830 +
1831 + $bot_options = apply_filters('mxchat_get_bot_options', array(), $bot_id);
1832 +
1833 + if (!empty($bot_options)) {
1834 + error_log("MXCHAT DEBUG: Got bot-specific options from filter");
1835 + if (isset($bot_options['similarity_threshold'])) {
1836 + error_log(" - similarity_threshold: " . $bot_options['similarity_threshold']);
1837 + }
1838 + }
1839 +
1840 + return is_array($bot_options) ? $bot_options : array();
1841 +}
1842 +
1843 +/**
1844 + * Get bot-specific Pinecone configuration
1845 + * Used in the knowledge retrieval functions
1846 + */
1847 +// Also add debugging to your get_bot_pinecone_config function
1848 +private function get_bot_pinecone_config($bot_id = 'default') {
1849 + error_log("MXCHAT DEBUG: get_bot_pinecone_config called for bot: " . $bot_id);
1850 +
1851 + // If default bot or multi-bot add-on not active, use default Pinecone config
1852 + if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
1853 + error_log("MXCHAT DEBUG: Using default Pinecone config (no multi-bot or bot is 'default')");
1854 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
1855 + $config = array(
1856 + 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
1857 + 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
1858 + 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
1859 + 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
1860 + );
1861 + error_log("MXCHAT DEBUG: Default config - use_pinecone: " . ($config['use_pinecone'] ? 'true' : 'false'));
1862 + return $config;
1863 + }
1864 +
1865 + error_log("MXCHAT DEBUG: Calling filter 'mxchat_get_bot_pinecone_config' for bot: " . $bot_id);
1866 +
1867 + // Hook for multi-bot add-on to provide bot-specific Pinecone config
1868 + $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
1869 +
1870 + if (!empty($bot_pinecone_config)) {
1871 + error_log("MXCHAT DEBUG: Got bot-specific config from filter");
1872 + error_log(" - use_pinecone: " . (isset($bot_pinecone_config['use_pinecone']) ? ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false') : 'not set'));
1873 + error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'not set'));
1874 + error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'not set'));
1875 + } else {
1876 + error_log("MXCHAT DEBUG: Filter returned empty config!");
1877 + }
1878 +
1879 + return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
1880 +}
1881 +
1882 +
1883 +// Updated function to check intents and invoke the callback function
1884 +private function mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id) {
1885 + global $wpdb;
1886 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
1887 +
1888 + // Get the current bot_id
1889 + $current_bot_id = $this->get_current_bot_id($session_id);
1890 +
1891 + // Generate the user embedding
1892 + $user_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
1893 +
1894 + // Check if embedding generation returned an error
1895 + if (is_array($user_embedding) && isset($user_embedding['error'])) {
1896 + $error_message = $user_embedding['error'];
1897 + $error_code = $user_embedding['error_code'] ?? 'embedding_error';
1898 +
1899 + // FIXED: Send error in appropriate format based on streaming mode
1900 + if ($this->is_streaming) {
1901 + echo "data: " . json_encode([
1902 + 'error' => true,
1903 + 'error_message' => $error_message,
1904 + 'error_code' => $error_code,
1905 + 'text' => $error_message,
1906 + 'message' => $error_message
1907 + ]) . "\n\n";
1908 + echo "data: [DONE]\n\n";
1909 + flush();
1910 + } else {
1911 + wp_send_json_error([
1912 + 'error_message' => $error_message,
1913 + 'error_code' => $error_code
1914 + ]);
1915 + }
1916 + wp_die();
1917 + }
1918 +
1919 + // Check if embedding is valid
1920 + if (!is_array($user_embedding) || empty($user_embedding)) {
1921 + $error_message = esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat');
1922 +
1923 + // FIXED: Send error in appropriate format based on streaming mode
1924 + if ($this->is_streaming) {
1925 + echo "data: " . json_encode([
1926 + 'error' => true,
1927 + 'error_message' => $error_message,
1928 + 'error_code' => 'invalid_embedding',
1929 + 'text' => $error_message,
1930 + 'message' => $error_message
1931 + ]) . "\n\n";
1932 + echo "data: [DONE]\n\n";
1933 + flush();
1934 + } else {
1935 + wp_send_json_error([
1936 + 'error_message' => $error_message,
1937 + 'error_code' => 'invalid_embedding'
1938 + ]);
1939 + }
1940 + wp_die();
1941 + }
1942 +
1943 + // Fetch intents from the database
1944 + $table_name = $wpdb->prefix . 'mxchat_intents';
1945 + if ($chat_mode === 'agent') {
1946 + $query = $wpdb->prepare(
1947 + "SELECT * FROM $table_name WHERE callback_function = %s AND (enabled = 1 OR enabled IS NULL)",
1948 + 'mxchat_handle_switch_to_chatbot_intent'
1949 + );
1950 + $intents = $wpdb->get_results($query);
1951 + } else {
1952 + $intents = $wpdb->get_results("SELECT * FROM $table_name WHERE enabled = 1 OR enabled IS NULL");
1953 + }
1954 +
1955 + if (empty($intents)) {
1956 + return false;
1957 + }
1958 +
1959 + $highest_similarity = -INF;
1960 + $matched_intent = null;
1961 +
1962 + // Array to store action analysis for testing panel
1963 + $action_analysis = [];
1964 +
1965 + foreach ($intents as $intent) {
1966 + // Additional check for enabled state
1967 + $is_enabled = isset($intent->enabled) ? (bool)$intent->enabled : true;
1968 + if (!$is_enabled) {
1969 + continue;
1970 + }
1971 +
1972 + // Check if this action is enabled for the current bot
1973 + if (!$this->is_action_enabled_for_bot($intent, $current_bot_id)) {
1974 + continue;
1975 + }
1976 +
1977 + $intent_embedding_serialized = $intent->embedding_vector;
1978 + $intent_embedding = $intent_embedding_serialized
1979 + ? unserialize($intent_embedding_serialized, ['allowed_classes' => false])
1980 + : null;
1981 +
1982 + if (!is_array($intent_embedding)) {
1983 + continue;
1984 + }
1985 +
1986 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $intent_embedding);
1987 + $intent_threshold = isset($intent->similarity_threshold) ? $intent->similarity_threshold : 0.85;
1988 +
1989 + // Store action analysis data for testing panel
1990 + $action_analysis[] = [
1991 + 'intent_label' => $intent->intent_label,
1992 + 'callback_function' => $intent->callback_function,
1993 + 'similarity' => round($similarity, 4),
1994 + 'similarity_percentage' => round($similarity * 100, 2),
1995 + 'threshold' => $intent_threshold,
1996 + 'threshold_percentage' => round($intent_threshold * 100, 2),
1997 + 'above_threshold' => $similarity >= $intent_threshold,
1998 + 'triggered' => false // Will be updated below if this intent is triggered
1999 + ];
2000 +
2001 + if ($similarity >= $intent_threshold && $similarity > $highest_similarity) {
2002 + $highest_similarity = $similarity;
2003 + $matched_intent = $intent;
2004 + }
2005 + }
2006 +
2007 + // Mark the triggered action if any
2008 + if ($matched_intent) {
2009 + foreach ($action_analysis as &$action) {
2010 + if ($action['intent_label'] === $matched_intent->intent_label) {
2011 + $action['triggered'] = true;
2012 + break;
2013 + }
2014 + }
2015 + }
2016 +
2017 + // Sort actions by similarity (highest first) and store for testing panel
2018 + usort($action_analysis, function($a, $b) {
2019 + return $b['similarity'] <=> $a['similarity'];
2020 + });
2021 +
2022 + // Store action analysis for testing panel capture
2023 + $this->last_action_analysis = $action_analysis;
2024 +
2025 + // Around line 715 in your mxchat_check_intent_and_invoke_callback function
2026 + if ($matched_intent) {
2027 + // If the callback is a method on this instance (core callback), call it directly
2028 + if (method_exists($this, $matched_intent->callback_function)) {
2029 + $callback_result = call_user_func(
2030 + [$this, $matched_intent->callback_function],
2031 + $message,
2032 + $user_id,
2033 + $session_id,
2034 + $matched_intent,
2035 + $user_context ?? null
2036 + );
2037 + } else {
2038 + // Otherwise, use apply_filters for add-on callbacks
2039 + $callback_result = apply_filters(
2040 + $matched_intent->callback_function,
2041 + false,
2042 + $message,
2043 + $user_id,
2044 + $session_id,
2045 + $matched_intent
2046 + );
2047 + }
2048 +
2049 + // Handle the callback result properly
2050 + if ($callback_result !== false) {
2051 + // If callback returned an array with chat_mode, use it directly
2052 + if (is_array($callback_result) && isset($callback_result['chat_mode'])) {
2053 + $this->fallbackResponse = $callback_result;
2054 + return $callback_result; // Return the full array
2055 + } else {
2056 + $this->fallbackResponse = $callback_result;
2057 + return true;
2058 + }
2059 + }
2060 + }
2061 +
2062 + return false;
2063 +}
2064 +
2065 +/**
2066 + * Check if an action is enabled for a specific bot
2067 + */
2068 +private function is_action_enabled_for_bot($intent, $bot_id) {
2069 + // If enabled_bots column doesn't exist or is null, assume it's enabled for all bots (backward compatibility)
2070 + if (!isset($intent->enabled_bots) || empty($intent->enabled_bots)) {
2071 + return true;
2072 + }
2073 +
2074 + $enabled_bots = json_decode($intent->enabled_bots, true);
2075 +
2076 + // If JSON decode fails or returns empty array, assume enabled for all (backward compatibility)
2077 + if (!is_array($enabled_bots) || empty($enabled_bots)) {
2078 + return true;
2079 + }
2080 +
2081 + // Check if the current bot is in the enabled bots list
2082 + return in_array($bot_id, $enabled_bots);
2083 +}
2084 +
2085 +// Helper function to clear PDF and Word document related transients
2086 +private function clear_pdf_transients($session_id) {
2087 + // PDF transients
2088 + delete_transient('mxchat_pdf_url_' . $session_id);
2089 + delete_transient('mxchat_pdf_embeddings_' . $session_id);
2090 + delete_transient('mxchat_include_pdf_in_context_' . $session_id);
2091 + delete_transient('mxchat_waiting_for_pdf_url_' . $session_id);
2092 +
2093 + // Word document transients
2094 + delete_transient('mxchat_word_url_' . $session_id);
2095 + delete_transient('mxchat_word_filename_' . $session_id);
2096 + delete_transient('mxchat_word_embeddings_' . $session_id);
2097 + delete_transient('mxchat_include_word_in_context_' . $session_id);
2098 + delete_transient('mxchat_waiting_for_word_' . $session_id);
2099 +}
2100 +
2101 +
2102 +
2103 +//verified good
2104 +public function mxchat_handle_email_capture($message, $user_id, $session_id) {
2105 + // Get the user's original instruction/message
2106 + $user_instruction = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Please provide your email address.", 'mxchat'));
2107 +
2108 + // Set instruction for AI - just pass along what the user wanted to say
2109 + $this->current_action_instruction = $user_instruction;
2110 +
2111 + // Set the transient to track email capture flow
2112 + set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
2113 +
2114 + // Return false to let the AI generate the response
2115 + return false;
2116 +}
2117 +
2118 +public function mxchat_generate_image($message, $user_id, $session_id) {
2119 + //error_log("Starting image generation for message: " . $message);
2120 +
2121 + // Prepare a prompt for DALL-E
2122 + $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
2123 +
2124 + // Use the existing OpenAI API key
2125 + $openai_api_key = sanitize_text_field($this->options['api_key']);
2126 +
2127 + // Call DALL-E to generate an image
2128 + $image_response = $this->mxchat_generate_dalle_image($prompt, $openai_api_key);
2129 +
2130 + // Check if the response contains an image URL
2131 + if (isset($image_response['imageUrl'])) {
2132 + $image_url = esc_url_raw($image_response['imageUrl']);
2133 +
2134 + // Construct the HTML with a CSS class instead of inline styles
2135 + $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
2136 + $response_text = esc_html__('Here is the image I generated:', 'mxchat');
2137 +
2138 + // Save the bot message with both text and HTML
2139 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2140 + $this->mxchat_save_chat_message($session_id, 'bot', $response_html);
2141 +
2142 + // Set the fallback response for the chat handler
2143 + $this->fallbackResponse = [
2144 + 'text' => $response_text,
2145 + 'html' => $response_html,
2146 + 'images' => [$image_url]
2147 + ];
2148 +
2149 + // For debugging/verification - Use json_encode to verify what's being set
2150 + //error_log("Image generation successful - fallbackResponse set: " . json_encode($this->fallbackResponse));
2151 +
2152 + // Return the response directly instead of relying on the property
2153 + return $this->fallbackResponse;
2154 + } else {
2155 + $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
2156 +
2157 + // Save the error message
2158 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2159 +
2160 + // Set the fallback response for the chat handler
2161 + $this->fallbackResponse = [
2162 + 'text' => $response_text,
2163 + 'html' => '',
2164 + 'images' => []
2165 + ];
2166 +
2167 + //error_log("DALL-E image generation error: " . esc_html($image_response['error'] ?? 'Unknown error.'));
2168 + //error_log("Error fallbackResponse set: " . json_encode($this->fallbackResponse));
2169 +
2170 + // Return the response directly instead of relying on the property
2171 + return $this->fallbackResponse;
2172 + }
2173 +}
2174 +private function mxchat_generate_dalle_image($prompt, $api_key, $model = 'dall-e-3', $timeout = 60) {
2175 + $api_url = 'https://api.openai.com/v1/images/generations';
2176 + $body = json_encode([
2177 + 'prompt' => sanitize_text_field($prompt),
2178 + 'n' => 1,
2179 + 'size' => '1024x1024',
2180 + 'model' => sanitize_text_field($model),
2181 + ]);
2182 +
2183 + $args = [
2184 + 'body' => $body,
2185 + 'headers' => [
2186 + 'Content-Type' => 'application/json',
2187 + 'Authorization' => 'Bearer ' . sanitize_text_field($api_key),
2188 + ],
2189 + 'method' => 'POST',
2190 + 'timeout' => absint($timeout),
2191 + ];
2192 +
2193 + $response = wp_remote_post($api_url, $args);
2194 +
2195 + if (is_wp_error($response)) {
2196 + //error_log("DALL-E request failed: " . $response->get_error_message());
2197 + return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
2198 + }
2199 +
2200 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
2201 +
2202 + if (isset($response_body['data'][0]['url'])) {
2203 + return ['imageUrl' => esc_url_raw($response_body['data'][0]['url'])];
2204 + } else {
2205 + //error_log("DALL-E response error: " . wp_remote_retrieve_body($response));
2206 + return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
2207 + }
2208 +}
2209 +
2210 +/**
2211 + * Handle web search requests.
2212 + *
2213 + * Sends the refined search query to the Brave Search API and uses the
2214 + * results to generate a conversational response with the AI model.
2215 + *
2216 + * @since 1.0.0
2217 + * @param string $message The user's search query.
2218 + * @param string $user_id The user identifier.
2219 + * @param string $session_id The current session ID.
2220 + * @return array Response array containing text with embedded HTML links
2221 + */
2222 +public function mxchat_handle_search_request($message, $user_id, $session_id) {
2223 + // Step 1: Interpret and refine the search query
2224 + $refined_search_query = $this->mxchat_interpret_search_query($message);
2225 + if (empty($refined_search_query)) {
2226 + return array(
2227 + 'text' => esc_html__('I apologize, but could you please rephrase your search request?', 'mxchat'),
2228 + 'html' => ''
2229 + );
2230 + }
2231 +
2232 + // Retrieve and validate API settings
2233 + $options = get_option('mxchat_options');
2234 + $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
2235 + $results_count = isset($options['brave_results_count']) ? absint($options['brave_results_count']) : 5;
2236 +
2237 + if (empty($api_key)) {
2238 + return array(
2239 + 'text' => esc_html__('Search functionality is temporarily unavailable. Please try again later.', 'mxchat'),
2240 + 'html' => ''
2241 + );
2242 + }
2243 +
2244 + // Build the API request URL
2245 + $api_url = add_query_arg(
2246 + array(
2247 + 'q' => rawurlencode($refined_search_query),
2248 + 'count' => $results_count,
2249 + 'text_decorations' => 'true',
2250 + 'rich_data' => 'true',
2251 + ),
2252 + 'https://api.search.brave.com/res/v1/web/search'
2253 + );
2254 +
2255 + // Attempt to retrieve cached results first
2256 + $transient_key = 'mxchat_search_' . md5($refined_search_query);
2257 + $results = get_transient($transient_key);
2258 +
2259 + if (false === $results) {
2260 + // SECURITY FIX: Changed to wp_safe_remote_get
2261 + $response = wp_safe_remote_get(
2262 + $api_url,
2263 + array(
2264 + 'headers' => array(
2265 + 'Accept' => 'application/json',
2266 + 'Accept-Encoding' => 'gzip',
2267 + 'X-Subscription-Token'=> $api_key,
2268 + ),
2269 + 'timeout' => 10,
2270 + )
2271 + );
2272 +
2273 + if (is_wp_error($response)) {
2274 + return array(
2275 + 'text' => esc_html__('I encountered an error while searching. Please try again.', 'mxchat'),
2276 + 'html' => ''
2277 + );
2278 + }
2279 +
2280 + $results = json_decode(wp_remote_retrieve_body($response), true);
2281 +
2282 + if (json_last_error() !== JSON_ERROR_NONE) {
2283 + return array(
2284 + 'text' => esc_html__('I received an invalid response from the search service.', 'mxchat'),
2285 + 'html' => ''
2286 + );
2287 + }
2288 +
2289 + // Cache results for one hour
2290 + set_transient($transient_key, $results, HOUR_IN_SECONDS);
2291 + }
2292 +
2293 + // Process results
2294 + if (!empty($results['web']['results']) && is_array($results['web']['results'])) {
2295 + // Create a more straightforward summary with HTML links
2296 + $search_results_text = '';
2297 +
2298 + // Add a simple intro
2299 + $search_results_text .= sprintf(
2300 + esc_html__("Here's what I found about '%s':", 'mxchat'),
2301 + esc_html($refined_search_query)
2302 + );
2303 +
2304 + // Add the top results with HTML links
2305 + foreach (array_slice($results['web']['results'], 0, 5) as $result) {
2306 + $title = isset($result['title']) ? wp_strip_all_tags($result['title']) : '';
2307 + $url = isset($result['url']) ? esc_url($result['url']) : '';
2308 + $description = isset($result['description']) ? wp_strip_all_tags($result['description']) : '';
2309 +
2310 + // Add a line break after the intro
2311 + $search_results_text .= '<br><br>';
2312 +
2313 + // Add title as a link
2314 + $search_results_text .= sprintf(
2315 + '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a><br>',
2316 + $url,
2317 + $title
2318 + );
2319 +
2320 + // Add a condensed description
2321 + $search_results_text .= sprintf("%s", $description);
2322 + }
2323 +
2324 + // Save to chat history
2325 + $this->mxchat_save_chat_message($session_id, 'bot', $search_results_text);
2326 +
2327 + // Return the formatted text with embedded HTML links
2328 + return array(
2329 + 'text' => $search_results_text,
2330 + 'html' => ''
2331 + );
2332 + } else {
2333 + return array(
2334 + 'text' => sprintf(
2335 + esc_html__('I searched for "%s" but couldn\'t find any relevant results. Would you like to try different search terms?', 'mxchat'),
2336 + esc_html($refined_search_query)
2337 + ),
2338 + 'html' => ''
2339 + );
2340 + }
2341 +}
2342 +
2343 +//very good
2344 +/**
2345 + * Handle image search requests from the chatbot
2346 + *
2347 + * @param string $message The user's search query
2348 + * @param int $user_id The user's ID
2349 + * @param string $session_id The chat session ID
2350 + * @return array Response array with text and HTML content
2351 + */
2352 +public function mxchat_handle_image_search_request($message, $user_id, $session_id) {
2353 + // Step 1: Interpret the search query using the user's selected AI model
2354 + $refined_search_query = $this->mxchat_interpret_search_query($message);
2355 +
2356 + // If no query was interpreted, return a fallback message
2357 + if (empty($refined_search_query)) {
2358 + return array(
2359 + 'text' => __("I'm sorry, I couldn't interpret your search query. Please specify what you'd like to see images of.", 'mxchat'),
2360 + 'html' => "",
2361 + );
2362 + }
2363 +
2364 + // Brave API URL
2365 + $api_url = 'https://api.search.brave.com/res/v1/images/search';
2366 +
2367 + // Retrieve Brave API settings
2368 + $options = get_option('mxchat_options');
2369 + $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
2370 +
2371 + if (empty($api_key)) {
2372 + return array(
2373 + 'text' => __("API key is not configured. Please set it in the Brave Search Settings.", 'mxchat'),
2374 + 'html' => "",
2375 + );
2376 + }
2377 +
2378 + $image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
2379 + $safe_search = isset($options['brave_safe_search']) ? sanitize_text_field($options['brave_safe_search']) : 'strict';
2380 +
2381 + // Append query parameters based on settings
2382 + $api_url = add_query_arg([
2383 + 'q' => rawurlencode($refined_search_query),
2384 + 'count' => $image_count,
2385 + 'safesearch' => $safe_search,
2386 + ], $api_url);
2387 +
2388 + // Implement caching
2389 + $transient_key = 'mxchat_image_search_' . md5($refined_search_query);
2390 + $body = get_transient($transient_key);
2391 +
2392 + if (false === $body) {
2393 + $args = [
2394 + 'headers' => [
2395 + 'Accept' => 'application/json',
2396 + 'Accept-Encoding' => 'gzip',
2397 + 'X-Subscription-Token' => $api_key,
2398 + ],
2399 + 'timeout' => 10,
2400 + ];
2401 +
2402 + // SECURITY FIX: Changed to wp_safe_remote_get
2403 + $response = wp_safe_remote_get($api_url, $args);
2404 +
2405 + if (is_wp_error($response)) {
2406 + return array(
2407 + 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
2408 + 'html' => "",
2409 + );
2410 + }
2411 +
2412 + $body = json_decode(wp_remote_retrieve_body($response), true);
2413 + set_transient($transient_key, $body, HOUR_IN_SECONDS);
2414 + }
2415 +
2416 + // Process the API response
2417 + if (isset($body['results']) && is_array($body['results']) && count($body['results']) > 0) {
2418 + $html_output = '<div class="mxchat-image-gallery">';
2419 +
2420 + // Get the configured image count (1-6)
2421 + $display_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
2422 + $display_count = min($display_count, count($body['results'])); // Make sure we don't exceed available images
2423 +
2424 + // Use only the requested number of images
2425 + for ($i = 0; $i < $display_count; $i++) {
2426 + $image = $body['results'][$i];
2427 + $image_url = isset($image['url']) ? esc_url($image['url']) : '';
2428 + $thumbnail_url = isset($image['thumbnail']['src']) ? esc_url($image['thumbnail']['src']) : '';
2429 + $title = isset($image['title']) ? esc_html($image['title']) : esc_html__('Image', 'mxchat');
2430 +
2431 + if ($image_url && $thumbnail_url) {
2432 + $html_output .= '<div class="mxchat-image-item">';
2433 + $html_output .= '<strong class="mxchat-image-title">' . $title . '</strong>';
2434 + $html_output .= '<a href="' . $image_url . '" target="_blank" rel="noopener noreferrer" class="mxchat-image-link">';
2435 + $html_output .= '<img src="' . $thumbnail_url . '" alt="' . $title . '" class="mxchat-image-thumbnail">';
2436 + $html_output .= '</a></div>';
2437 + }
2438 + }
2439 +
2440 + $html_output .= '</div>';
2441 +
2442 + // Create response text
2443 + $response_text = sprintf(__("Here are some images of %s:", 'mxchat'), $refined_search_query);
2444 +
2445 + // Save both response text and HTML to chat history
2446 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2447 + $this->mxchat_save_chat_message($session_id, 'bot', $html_output);
2448 +
2449 + // Return the combined response
2450 + return array(
2451 + 'text' => $response_text,
2452 + 'html' => $html_output,
2453 + );
2454 + } else {
2455 + $response_text = __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat');
2456 +
2457 + // Save the error message to chat history
2458 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2459 +
2460 + return array(
2461 + 'text' => $response_text,
2462 + 'html' => "",
2463 + );
2464 + }
2465 +}
2466 +
2467 +/**
2468 + * Interpret the search query using the user's selected AI model
2469 + *
2470 + * @param string $user_query The original query from the user
2471 + * @return string The refined search query
2472 + */
2473 +public function mxchat_interpret_search_query($user_query) {
2474 + $system_prompt = esc_html__("Interpret the user's request to provide only the essential keywords or phrases for image searching. Remove conversational language, politeness, or extra context. Return a concise search query that doesn't lose any of the original meaning.", 'mxchat');
2475 +
2476 + // Get options and determine the selected model
2477 + $options = $this->options ?? get_option('mxchat_options');
2478 + $selected_model = isset($options['model']) ? $options['model'] : 'gpt-4o';
2479 +
2480 + // Extract model prefix to determine the provider
2481 + $model_parts = explode('-', $selected_model);
2482 + $provider = strtolower($model_parts[0]);
2483 +
2484 + // Determine which API key to use based on the provider
2485 + switch ($provider) {
2486 + case 'gemini':
2487 + $api_key = isset($options['gemini_api_key']) ? sanitize_text_field($options['gemini_api_key']) : '';
2488 + if (empty($api_key)) {
2489 + return sanitize_text_field($user_query); // Default to original query if API key missing
2490 + }
2491 + return $this->interpret_query_with_gemini($user_query, $system_prompt, $api_key, $selected_model);
2492 +
2493 + case 'claude':
2494 + $api_key = isset($options['claude_api_key']) ? sanitize_text_field($options['claude_api_key']) : '';
2495 + if (empty($api_key)) {
2496 + return sanitize_text_field($user_query);
2497 + }
2498 + return $this->interpret_query_with_claude($user_query, $system_prompt, $api_key, $selected_model);
2499 +
2500 + case 'grok':
2501 + $api_key = isset($options['xai_api_key']) ? sanitize_text_field($options['xai_api_key']) : '';
2502 + if (empty($api_key)) {
2503 + return sanitize_text_field($user_query);
2504 + }
2505 + return $this->interpret_query_with_xai($user_query, $system_prompt, $api_key, $selected_model);
2506 +
2507 + case 'deepseek':
2508 + $api_key = isset($options['deepseek_api_key']) ? sanitize_text_field($options['deepseek_api_key']) : '';
2509 + if (empty($api_key)) {
2510 + return sanitize_text_field($user_query);
2511 + }
2512 + return $this->interpret_query_with_deepseek($user_query, $system_prompt, $api_key, $selected_model);
2513 +
2514 + case 'gpt':
2515 + default:
2516 + // Default to OpenAI for custom models or unrecognized prefixes
2517 + $api_key = isset($options['api_key']) ? sanitize_text_field($options['api_key']) : '';
2518 + if (empty($api_key)) {
2519 + return sanitize_text_field($user_query);
2520 + }
2521 + return $this->interpret_query_with_openai($user_query, $system_prompt, $api_key, $selected_model);
2522 + }
2523 +}
2524 +
2525 +/**
2526 + * Interpret query using OpenAI models
2527 + */
2528 +private function interpret_query_with_openai($user_query, $system_prompt, $api_key, $model = 'gpt-4o') {
2529 + $url = 'https://api.openai.com/v1/chat/completions';
2530 + $args = [
2531 + 'headers' => [
2532 + 'Authorization' => 'Bearer ' . $api_key,
2533 + 'Content-Type' => 'application/json',
2534 + ],
2535 + 'body' => wp_json_encode([
2536 + 'model' => $model,
2537 + 'messages' => [
2538 + ['role' => 'system', 'content' => $system_prompt],
2539 + ['role' => 'user', 'content' => sanitize_text_field($user_query)],
2540 + ],
2541 + 'temperature' => 0.2,
2542 + 'max_tokens' => 20,
2543 + ]),
2544 + 'method' => 'POST',
2545 + 'timeout' => 15,
2546 + ];
2547 +
2548 + $response = wp_remote_post($url, $args);
2549 + if (is_wp_error($response)) {
2550 + return sanitize_text_field($user_query);
2551 + }
2552 +
2553 + $body = json_decode(wp_remote_retrieve_body($response), true);
2554 + return isset($body['choices'][0]['message']['content'])
2555 + ? sanitize_text_field(trim($body['choices'][0]['message']['content']))
2556 + : sanitize_text_field($user_query);
2557 +}
2558 +
2559 +/**
2560 + * Interpret query using Claude models
2561 + */
2562 +private function interpret_query_with_claude($user_query, $system_prompt, $api_key, $model) {
2563 + $url = 'https://api.anthropic.com/v1/messages';
2564 +
2565 + $args = [
2566 + 'headers' => [
2567 + 'Content-Type' => 'application/json',
2568 + 'x-api-key' => $api_key,
2569 + 'anthropic-version' => '2023-06-01',
2570 + ],
2571 + 'body' => wp_json_encode([
2572 + 'model' => $model,
2573 + 'system' => $system_prompt,
2574 + 'messages' => [
2575 + ['role' => 'user', 'content' => sanitize_text_field($user_query)]
2576 + ],
2577 + 'max_tokens' => 20,
2578 + 'temperature' => 0.2,
2579 + ]),
2580 + 'method' => 'POST',
2581 + 'timeout' => 15,
2582 + ];
2583 +
2584 + $response = wp_remote_post($url, $args);
2585 + if (is_wp_error($response)) {
2586 + return sanitize_text_field($user_query);
2587 + }
2588 +
2589 + $body = json_decode(wp_remote_retrieve_body($response), true);
2590 + if (!empty($body['content'][0]['text'])) {
2591 + return sanitize_text_field(trim($body['content'][0]['text']));
2592 + }
2593 +
2594 + return sanitize_text_field($user_query);
2595 +}
2596 +
2597 +/**
2598 + * Interpret query using Gemini models
2599 + */
2600 +private function interpret_query_with_gemini($user_query, $system_prompt, $api_key, $model) {
2601 + // Strip "gemini-" prefix for the API
2602 + $model_version = str_replace('gemini-', '', $model);
2603 +
2604 + $url = "https://generativelanguage.googleapis.com/v1/models/$model_version:generateContent?key=" . urlencode($api_key);
2605 +
2606 + $args = [
2607 + 'headers' => [
2608 + 'Content-Type' => 'application/json',
2609 + ],
2610 + 'body' => wp_json_encode([
2611 + 'contents' => [
2612 + [
2613 + 'role' => 'user',
2614 + 'parts' => [
2615 + ['text' => $system_prompt . "\n\nQuery: " . sanitize_text_field($user_query)]
2616 + ]
2617 + ]
2618 + ],
2619 + 'generationConfig' => [
2620 + 'temperature' => 0.2,
2621 + 'maxOutputTokens' => 20,
2622 + ],
2623 + ]),
2624 + 'method' => 'POST',
2625 + 'timeout' => 15,
2626 + ];
2627 +
2628 + $response = wp_remote_post($url, $args);
2629 + if (is_wp_error($response)) {
2630 + return sanitize_text_field($user_query);
2631 + }
2632 +
2633 + $body = json_decode(wp_remote_retrieve_body($response), true);
2634 + if (!empty($body['candidates'][0]['content']['parts'][0]['text'])) {
2635 + return sanitize_text_field(trim($body['candidates'][0]['content']['parts'][0]['text']));
2636 + }
2637 +
2638 + return sanitize_text_field($user_query);
2639 +}
2640 +
2641 +/**
2642 + * Interpret query using X.AI (Grok) models
2643 + */
2644 +private function interpret_query_with_xai($user_query, $system_prompt, $api_key, $model) {
2645 + $url = 'https://api.xai.com/v1/chat/completions';
2646 +
2647 + $args = [
2648 + 'headers' => [
2649 + 'Content-Type' => 'application/json',
2650 + 'Authorization' => 'Bearer ' . $api_key,
2651 + ],
2652 + 'body' => wp_json_encode([
2653 + 'model' => $model,
2654 + 'messages' => [
2655 + ['role' => 'system', 'content' => $system_prompt],
2656 + ['role' => 'user', 'content' => sanitize_text_field($user_query)],
2657 + ],
2658 + 'temperature' => 0.2,
2659 + 'max_tokens' => 20,
2660 + ]),
2661 + 'method' => 'POST',
2662 + 'timeout' => 15,
2663 + ];
2664 +
2665 + $response = wp_remote_post($url, $args);
2666 + if (is_wp_error($response)) {
2667 + return sanitize_text_field($user_query);
2668 + }
2669 +
2670 + $body = json_decode(wp_remote_retrieve_body($response), true);
2671 + if (isset($body['choices'][0]['message']['content'])) {
2672 + return sanitize_text_field(trim($body['choices'][0]['message']['content']));
2673 + }
2674 +
2675 + return sanitize_text_field($user_query);
2676 +}
2677 +
2678 +/**
2679 + * Interpret query using DeepSeek models
2680 + */
2681 +private function interpret_query_with_deepseek($user_query, $system_prompt, $api_key, $model) {
2682 + $url = 'https://api.deepseek.com/v1/chat/completions';
2683 +
2684 + $args = [
2685 + 'headers' => [
2686 + 'Content-Type' => 'application/json',
2687 + 'Authorization' => 'Bearer ' . $api_key,
2688 + ],
2689 + 'body' => wp_json_encode([
2690 + 'model' => $model,
2691 + 'messages' => [
2692 + ['role' => 'system', 'content' => $system_prompt],
2693 + ['role' => 'user', 'content' => sanitize_text_field($user_query)],
2694 + ],
2695 + 'temperature' => 0.2,
2696 + 'max_tokens' => 20,
2697 + ]),
2698 + 'method' => 'POST',
2699 + 'timeout' => 15,
2700 + ];
2701 +
2702 + $response = wp_remote_post($url, $args);
2703 + if (is_wp_error($response)) {
2704 + return sanitize_text_field($user_query);
2705 + }
2706 +
2707 + $body = json_decode(wp_remote_retrieve_body($response), true);
2708 + if (isset($body['choices'][0]['message']['content'])) {
2709 + return sanitize_text_field(trim($body['choices'][0]['message']['content']));
2710 + }
2711 +
2712 + return sanitize_text_field($user_query);
2713 +}
2714 +
2715 +//very good
2716 +private function add_email_to_loops($email) {
2717 + // Sanitize the email
2718 + $email = sanitize_email($email);
2719 +
2720 + // Retrieve and sanitize options
2721 + $api_key = isset($this->options['loops_api_key']) ? sanitize_text_field($this->options['loops_api_key']) : '';
2722 + $mailing_list_id = isset($this->options['loops_mailing_list']) ? sanitize_text_field($this->options['loops_mailing_list']) : '';
2723 +
2724 + // Check for missing API key or mailing list ID
2725 + if (empty($api_key) || empty($mailing_list_id)) {
2726 + //error_log(esc_html__('Loops API key or mailing list ID is missing.', 'mxchat'));
2727 + return;
2728 + }
2729 +
2730 + $data = array(
2731 + 'email' => $email,
2732 + 'subscribed' => true,
2733 + 'source' => __('MxChat AI Chatbot', 'mxchat'),
2734 + 'mailingLists' => array($mailing_list_id => true),
2735 + );
2736 +
2737 + $url = 'https://app.loops.so/api/v1/contacts/create';
2738 + $args = array(
2739 + 'body' => wp_json_encode($data),
2740 + 'headers' => array(
2741 + 'Authorization' => 'Bearer ' . $api_key,
2742 + 'Content-Type' => 'application/json',
2743 + ),
2744 + 'method' => 'POST',
2745 + 'timeout' => 45,
2746 + );
2747 +
2748 + $response = wp_remote_post($url, $args);
2749 +
2750 + // Handle errors in the API request
2751 + if (is_wp_error($response)) {
2752 + //error_log(esc_html__('Error adding email to Loops: ', 'mxchat') . $response->get_error_message());
2753 + return;
2754 + }
2755 +
2756 + // Check for non-200 HTTP responses
2757 + $response_code = wp_remote_retrieve_response_code($response);
2758 + if ($response_code != 200) {
2759 + $response_body = wp_remote_retrieve_body($response);
2760 + //error_log(esc_html__('Loops API responded with code ', 'mxchat') . $response_code . ': ' . $response_body);
2761 + }
2762 +}
2763 +
2764 +public function mxchat_handle_pdf_discussion($message, $user_id, $session_id) {
2765 + // Get the maximum number of pages allowed from admin settings
2766 + $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
2767 +
2768 + // Retrieve options for dynamic texts
2769 + $trigger_text = $this->options['pdf_intent_trigger_text'] ?? __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
2770 + $success_text = $this->options['pdf_intent_success_text'] ?? __("I've processed the PDF. What questions do you have about it?", 'mxchat');
2771 + $error_text = $this->options['pdf_intent_error_text'] ?? __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
2772 +
2773 + // Check for explicit request for new PDF
2774 + $new_pdf_requested = stripos($message, 'new') !== false ||
2775 + stripos($message, 'another') !== false ||
2776 + stripos($message, 'different') !== false;
2777 +
2778 + // If user mentions adding/reading a PDF, set waiting flag
2779 + if (stripos($message, 'pdf') !== false ||
2780 + stripos($message, 'document') !== false ||
2781 + stripos($message, 'read') !== false) {
2782 + set_transient('mxchat_waiting_for_pdf_url_' . $session_id, true, HOUR_IN_SECONDS);
2783 + $this->fallbackResponse['text'] = $trigger_text;
2784 + return;
2785 + }
2786 +
2787 + // If we're waiting for a URL or user requested new PDF
2788 + if ($new_pdf_requested || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
2789 + if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
2790 + // Process URL... (rest of your existing URL processing code)
2791 + } else {
2792 + $this->fallbackResponse['text'] = $trigger_text;
2793 + }
2794 + return;
2795 + }
2796 +
2797 + // Default to proceeding with conversation if no specific PDF action is needed
2798 + $this->fallbackResponse['text'] = '';
2799 +}
2800 +
2801 +
2802 +/**
2803 + * Enhanced fetch_and_split_pdf_pages with SSRF protection
2804 + */
2805 +private function fetch_and_split_pdf_pages($pdf_source, $max_pages) {
2806 + // CLEAR DEBUG LOGGING
2807 + //error_log("=== MXCHAT PDF PROCESSING START ===");
2808 + //error_log("PDF Source: " . $pdf_source);
2809 + //error_log("Max Pages: " . $max_pages);
2810 + //error_log("Session ID: " . ($this->session_id ?? 'not set'));
2811 +
2812 + // Check if Advanced Claude Toolbar is available and enabled
2813 + $claude_available = function_exists('mxchatACT_is_advanced_claude_enabled');
2814 + $claude_enabled = $claude_available ? mxchatACT_is_advanced_claude_enabled() : false;
2815 +
2816 + //error_log("Claude Function Available: " . ($claude_available ? 'YES' : 'NO'));
2817 + //error_log("Claude Enabled: " . ($claude_enabled ? 'YES' : 'NO'));
2818 +
2819 + if ($claude_available && $claude_enabled) {
2820 + //error_log("🚀 ATTEMPTING CLAUDE PROCESSING...");
2821 +
2822 + // Attempt Claude processing first
2823 + $claude_result = apply_filters('mxchat_process_pdf_advanced', false, $pdf_source, $max_pages, $this->session_id);
2824 +
2825 + if ($claude_result !== false && is_array($claude_result) && !empty($claude_result)) {
2826 + //error_log("✅ CLAUDE PROCESSING SUCCESSFUL!");
2827 + //error_log("Claude returned " . count($claude_result) . " processed pages");
2828 +
2829 + // Log first page details for verification
2830 + if (isset($claude_result[0])) {
2831 + $first_page = $claude_result[0];
2832 + //error_log("First page enhanced: " . (isset($first_page['enhanced']) && $first_page['enhanced'] ? 'YES' : 'NO'));
2833 + //error_log("Processing method: " . ($first_page['processing_method'] ?? 'not set'));
2834 + //error_log("First page text preview: " . substr($first_page['text'] ?? '', 0, 100) . "...");
2835 + }
2836 +
2837 + //error_log("=== MXCHAT PDF PROCESSING END (CLAUDE) ===");
2838 + return $claude_result;
2839 + } else {
2840 + //error_log("❌ CLAUDE PROCESSING FAILED or returned invalid result");
2841 + //error_log("Claude result type: " . gettype($claude_result));
2842 + if (is_array($claude_result)) {
2843 + //error_log("Claude result count: " . count($claude_result));
2844 + }
2845 + }
2846 + }
2847 +
2848 + // Fallback to basic processing
2849 + //error_log("🔄 FALLING BACK TO BASIC PDF PROCESSING...");
2850 +
2851 + $upload_dir = wp_upload_dir();
2852 + $temp_file = null;
2853 +
2854 + try {
2855 + // Your existing basic processing code here...
2856 + // (I'll include the key parts with debug logging)
2857 +
2858 + if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
2859 + //error_log("Downloading PDF from URL...");
2860 +
2861 + // SECURITY FIX: Validate URL before processing
2862 + if (!$this->mxchat_is_safe_pdf_url($pdf_source)) {
2863 + //error_log("❌ SECURITY: Blocked unsafe PDF URL");
2864 + return false;
2865 + }
2866 +
2867 + $temp_file = wp_tempnam($pdf_source);
2868 +
2869 + // SECURITY FIX: Changed from wp_remote_get to wp_safe_remote_get
2870 + $response = wp_safe_remote_get($pdf_source, [
2871 + 'timeout' => 60,
2872 + 'headers' => ['User-Agent' => 'MxChat PDF Processor']
2873 + ]);
2874 +
2875 + if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
2876 + $error_message = is_wp_error($response) ? $response->get_error_message() : 'HTTP ' . wp_remote_retrieve_response_code($response);
2877 + //error_log("❌ BASIC PROCESSING: Failed to download PDF: " . $error_message);
2878 + return false;
2879 + }
2880 +
2881 + file_put_contents($temp_file, wp_remote_retrieve_body($response));
2882 + //error_log("✅ PDF downloaded successfully");
2883 + } else {
2884 + $temp_file = $pdf_source;
2885 + //error_log("Using local PDF file: " . $temp_file);
2886 + }
2887 +
2888 + // Parse PDF
2889 + //error_log("Parsing PDF with basic parser...");
2890 + $parser = new \Smalot\PdfParser\Parser();
2891 + $pdf = $parser->parseFile($temp_file);
2892 + $pages = $pdf->getPages();
2893 +
2894 + //error_log("PDF contains " . count($pages) . " pages");
2895 +
2896 + if (count($pages) > $max_pages) {
2897 + //error_log("❌ BASIC PROCESSING: Too many pages (" . count($pages) . " > " . $max_pages . ")");
2898 + if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file) {
2899 + unlink($temp_file);
2900 + }
2901 + return 'too_many_pages';
2902 + }
2903 +
2904 + $embeddings = [];
2905 + $processed_pages = 0;
2906 +
2907 + foreach ($pages as $page_number => $page) {
2908 + $text = $page->getText();
2909 +
2910 + if (empty(trim($text))) {
2911 + //error_log("Skipping empty page: " . ($page_number + 1));
2912 + continue;
2913 + }
2914 +
2915 + $text = $this->mxchat_clean_text($text);
2916 +
2917 + $embedding = $this->mxchat_generate_embedding(
2918 + __("Page ", 'mxchat') . ($page_number + 1) . ": " . $text,
2919 + $this->options['api_key']
2920 + );
2921 +
2922 + if ($embedding) {
2923 + $embeddings[] = [
2924 + 'page_number' => $page_number + 1,
2925 + 'embedding' => $embedding,
2926 + 'text' => $text,
2927 + 'enhanced' => false, // CLEARLY MARK AS BASIC
2928 + 'processing_method' => 'basic_pdf_parser'
2929 + ];
2930 + $processed_pages++;
2931 + }
2932 + }
2933 +
2934 + //error_log("✅ BASIC PROCESSING COMPLETE: " . $processed_pages . " pages processed");
2935 +
2936 + // Cleanup
2937 + if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
2938 + unlink($temp_file);
2939 + }
2940 +
2941 + //error_log("=== MXCHAT PDF PROCESSING END (BASIC) ===");
2942 + return $embeddings;
2943 +
2944 + } catch (\Exception $e) {
2945 + //error_log("❌ BASIC PROCESSING ERROR: " . $e->getMessage());
2946 + if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
2947 + unlink($temp_file);
2948 + }
2949 + //error_log("=== MXCHAT PDF PROCESSING END (ERROR) ===");
2950 + return false;
2951 + }
2952 +}
2953 +
2954 +
2955 +/**
2956 + * Validate PDF URL for security
2957 + * Prevents SSRF attacks by blocking dangerous URLs
2958 + */
2959 +
2960 +private function mxchat_is_safe_pdf_url($url) {
2961 + // Use WordPress core function for comprehensive validation
2962 + // This blocks localhost, private IPs, and reserved IP ranges
2963 + $validated_url = wp_http_validate_url($url);
2964 +
2965 + if ($validated_url === false) {
2966 + return false;
2967 + }
2968 +
2969 + // Additional check: only allow HTTP/HTTPS schemes
2970 + $parsed = parse_url($url);
2971 + if (!isset($parsed['scheme']) || !in_array($parsed['scheme'], ['http', 'https'], true)) {
2972 + return false;
2973 + }
2974 +
2975 + return true;
2976 +}
2977 +
2978 +
2979 +private function mxchat_clean_text($text) {
2980 + // Remove excessive whitespace
2981 + $text = preg_replace('/\s+/', ' ', $text);
2982 +
2983 + // Remove control characters except newlines and tabs
2984 + $text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text);
2985 +
2986 + // Normalize line endings
2987 + $text = str_replace(["\r\n", "\r"], "\n", $text);
2988 +
2989 + // Trim whitespace
2990 + $text = trim($text);
2991 +
2992 + return $text;
2993 +}
2994 +
2995 +private function find_relevant_pdf_pages($query_embedding, $embeddings) {
2996 + //error_log(esc_html__("find_relevant_pdf_pages called.", 'mxchat'));
2997 +
2998 + $most_relevant = null;
2999 + $highest_similarity = -INF;
3000 +
3001 + foreach ($embeddings as $page_data) {
3002 + $similarity = $this->mxchat_calculate_cosine_similarity($query_embedding, $page_data['embedding']);
3003 +
3004 + if ($similarity > $highest_similarity) {
3005 + $highest_similarity = $similarity;
3006 + $most_relevant = $page_data['page_number'];
3007 + }
3008 + }
3009 +
3010 + if (!is_null($most_relevant)) {
3011 + $page_numbers = range(max(1, $most_relevant - 1), min(count($embeddings), $most_relevant + 1));
3012 + return array_filter($embeddings, function ($page) use ($page_numbers) {
3013 + return in_array($page['page_number'], $page_numbers);
3014 + });
3015 + }
3016 +
3017 + return [];
3018 +}
3019 +
3020 +
3021 +public function handle_pdf_upload() {
3022 + check_ajax_referer('mxchat_chat_nonce', 'nonce');
3023 +
3024 + if (!isset($_FILES['pdf_file']) || !isset($_POST['session_id'])) {
3025 + wp_send_json_error(esc_html__('Missing required parameters.', 'mxchat'));
3026 + return;
3027 + }
3028 +
3029 + // SECURITY FIX: Check if PDF uploads are enabled in settings
3030 + $options = get_option('mxchat_options', array());
3031 + $show_pdf_button = isset($options['show_pdf_upload_button']) ? $options['show_pdf_upload_button'] : 'on';
3032 +
3033 + if ($show_pdf_button !== 'on') {
3034 + wp_send_json_error(esc_html__('PDF uploads are currently disabled.', 'mxchat'));
3035 + return;
3036 + }
3037 +
3038 + $file = $_FILES['pdf_file'];
3039 + $session_id = sanitize_text_field($_POST['session_id']);
3040 + $original_filename = sanitize_text_field($file['name']);
3041 +
3042 + // SECURITY FIX: Verify session ownership before allowing upload
3043 + $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
3044 + $session_owner = get_option("mxchat_session_owner_{$session_id}");
3045 +
3046 + if ($session_owner && $session_owner !== $current_user_identifier) {
3047 + wp_send_json_error(esc_html__('Unauthorized access.', 'mxchat'));
3048 + return;
3049 + }
3050 +
3051 + $file_type = wp_check_filetype($file['name'], ['pdf' => 'application/pdf']);
3052 + if ($file_type['type'] !== 'application/pdf') {
3053 + wp_send_json_error(esc_html__('Invalid file type. Only PDF files are allowed.', 'mxchat'));
3054 + return;
3055 + }
3056 +
3057 + $upload_dir = wp_upload_dir();
3058 +
3059 + // SECURITY FIX: Generate random filename without exposing session_id
3060 + $random_string = wp_generate_password(20, false, false); // 20 char alphanumeric string
3061 + $pdf_filename = 'mxchat_' . $random_string . '_' . time() . '.pdf';
3062 + $pdf_path = $upload_dir['path'] . '/' . $pdf_filename;
3063 +
3064 + if (!move_uploaded_file($file['tmp_name'], $pdf_path)) {
3065 + wp_send_json_error(esc_html__('Failed to upload file.', 'mxchat'));
3066 + return;
3067 + }
3068 +
3069 + $this->clear_pdf_transients($session_id);
3070 +
3071 + $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
3072 + $embeddings = $this->fetch_and_split_pdf_pages($pdf_path, $max_pages);
3073 +
3074 + if ($embeddings === 'too_many_pages') {
3075 + unlink($pdf_path);
3076 + $error_message = sprintf(
3077 + $this->options['pdf_intent_error_text'] ??
3078 + esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
3079 + $max_pages
3080 + );
3081 + wp_send_json_error($error_message);
3082 + return;
3083 + }
3084 +
3085 + if ($embeddings === false || empty($embeddings)) {
3086 + unlink($pdf_path);
3087 + $error_message = $this->options['pdf_intent_error_text'] ??
3088 + esc_html__('The uploaded PDF appears to be empty or contains unsupported content.', 'mxchat');
3089 + wp_send_json_error($error_message);
3090 + return;
3091 + }
3092 +
3093 + if (!empty($embeddings)) {
3094 + // Store the mapping between session and the random filename
3095 + set_transient('mxchat_pdf_url_' . $session_id, $pdf_path, HOUR_IN_SECONDS);
3096 + set_transient('mxchat_pdf_filename_' . $session_id, $original_filename, HOUR_IN_SECONDS);
3097 + set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
3098 + set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
3099 +
3100 + $success_message = $this->options['pdf_intent_success_text'] ??
3101 + esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat');
3102 +
3103 + wp_send_json_success([
3104 + 'message' => $success_message,
3105 + 'filename' => $original_filename
3106 + ]);
3107 + return;
3108 + }
3109 +
3110 + unlink($pdf_path);
3111 + $error_message = $this->options['pdf_intent_error_text'] ??
3112 + esc_html__('Sorry, I couldn\'t process the PDF. Please ensure it\'s a valid file.', 'mxchat');
3113 + wp_send_json_error($error_message);
3114 + return;
3115 +}
3116 +public function handle_pdf_remove() {
3117 + check_ajax_referer('mxchat_chat_nonce', 'nonce');
3118 +
3119 + if (empty($_POST['session_id'])) {
3120 + wp_send_json_error(esc_html__('Session ID missing.', 'mxchat'));
3121 + wp_die();
3122 + }
3123 +
3124 + $session_id = sanitize_text_field($_POST['session_id']);
3125 + $pdf_path = get_transient('mxchat_pdf_url_' . $session_id);
3126 +
3127 + if ($pdf_path && file_exists($pdf_path)) {
3128 + unlink($pdf_path);
3129 + }
3130 +
3131 + $this->clear_pdf_transients($session_id);
3132 +
3133 + wp_send_json_success([
3134 + 'message' => esc_html__('PDF removed successfully.', 'mxchat')
3135 + ]);
3136 + wp_die();
3137 +}
3138 +
3139 +
3140 +function mxchat_fetch_new_messages() {
3141 + $session_id = sanitize_text_field($_POST['session_id']);
3142 + $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
3143 + $persistence_enabled = $_POST['persistence_enabled'] === 'true';
3144 + $initial_timestamp = isset($_POST['initial_timestamp']) ? intval($_POST['initial_timestamp']) : 0;
3145 +
3146 + if (empty($session_id)) {
3147 + //error_log(esc_html__('Fetch new messages error: Session ID missing.', 'mxchat'));
3148 + wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
3149 + wp_die();
3150 + }
3151 +
3152 + $history = get_option("mxchat_history_{$session_id}", []);
3153 +
3154 + error_log("MxChat WhatsApp DEBUG: Fetch new messages for session {$session_id}");
3155 + error_log("MxChat WhatsApp DEBUG: last_seen_id = " . var_export($last_seen_id, true));
3156 + error_log("MxChat WhatsApp DEBUG: History count = " . count($history));
3157 + error_log("MxChat WhatsApp DEBUG: Full history = " . print_r($history, true));
3158 +
3159 + $new_messages = array_filter($history, function ($message) use ($last_seen_id, $persistence_enabled, $initial_timestamp) {
3160 + error_log("MxChat WhatsApp DEBUG: Checking message - ID: " . ($message['id'] ?? 'NO_ID') . ", Role: " . ($message['role'] ?? 'NO_ROLE'));
3161 +
3162 + // If persistence is enabled, show all new messages
3163 + if ($persistence_enabled) {
3164 + $has_id = !empty($message['id']);
3165 + $is_agent = $message['role'] === 'agent';
3166 +
3167 + // If last_seen_id is empty, 'NaN', or invalid, show all agent messages
3168 + if (empty($last_seen_id) || $last_seen_id === 'NaN' || $last_seen_id === 'undefined') {
3169 + $is_newer = true;
3170 + } else {
3171 + $is_newer = strcmp($message['id'] ?? '', $last_seen_id) > 0;
3172 + }
3173 +
3174 + error_log("MxChat WhatsApp DEBUG: has_id={$has_id}, is_newer={$is_newer}, is_agent={$is_agent}");
3175 +
3176 + return $has_id && $is_newer && $is_agent;
3177 + }
3178 +
3179 + // If persistence is disabled, only show messages after initial timestamp
3180 + return !empty($message['id']) &&
3181 + $message['role'] === 'agent' &&
3182 + $message['timestamp'] > $initial_timestamp;
3183 + });
3184 +
3185 + error_log("MxChat WhatsApp DEBUG: Filtered messages count = " . count($new_messages));
3186 +
3187 + wp_send_json_success([
3188 + 'new_messages' => array_values($new_messages)
3189 + ]);
3190 + wp_die();
3191 +}
3192 +public function mxchat_live_agent_handover($message, $user_id, $session_id) {
3193 + // First check if live agents are available
3194 + $live_agent_available = $this->options['live_agent_status'] ?? 'off';
3195 + if ($live_agent_available !== 'on') {
3196 + $away_message = $this->options['live_agent_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
3197 + $this->fallbackResponse = [
3198 + 'text' => $away_message,
3199 + 'html' => '',
3200 + 'images' => [],
3201 + 'chat_mode' => 'ai'
3202 + ];
3203 + wp_send_json([
3204 + 'text' => $away_message,
3205 + 'html' => '',
3206 + 'chat_mode' => 'ai',
3207 + 'session_id' => $session_id
3208 + ]);
3209 + wp_die();
3210 + }
3211 +
3212 + $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
3213 +
3214 + if (empty($slack_bot_token)) {
3215 + return false;
3216 + }
3217 +
3218 + // Check if channel already exists for this session
3219 + $channel_id = get_option("mxchat_channel_{$session_id}", '');
3220 +
3221 + if (empty($channel_id)) {
3222 + // Create new channel with session ID as name
3223 + $channel_name = $this->generate_channel_name($session_id);
3224 +
3225 + //error_log("Attempting to create channel: $channel_name");
3226 +
3227 + $response = wp_remote_post('https://slack.com/api/conversations.create', [
3228 + 'headers' => [
3229 + 'Content-Type' => 'application/json',
3230 + 'Authorization' => 'Bearer ' . $slack_bot_token
3231 + ],
3232 + 'body' => json_encode([
3233 + 'name' => $channel_name,
3234 + 'is_private' => false // Public channel - anyone in workspace can join
3235 + ])
3236 + ]);
3237 +
3238 + if (!is_wp_error($response)) {
3239 + $response_body = wp_remote_retrieve_body($response);
3240 + $response_data = json_decode($response_body, true);
3241 +
3242 + //error_log("Channel creation response: " . $response_body);
3243 +
3244 + if (isset($response_data['ok']) && $response_data['ok']) {
3245 + $channel_id = $response_data['channel']['id'];
3246 + $actual_channel_name = $response_data['channel']['name'] ?? 'unknown';
3247 + //error_log("Channel created successfully: ID=$channel_id, Name=$actual_channel_name");
3248 + update_option("mxchat_channel_{$session_id}", $channel_id);
3249 +
3250 + // Auto-invite agents to the channel
3251 + $agent_user_ids = $this->options['live_agent_user_ids'] ?? '';
3252 +
3253 + if (!empty($agent_user_ids)) {
3254 + // Parse user IDs (one per line)
3255 + $user_ids = array_filter(array_map('trim', explode("\n", $agent_user_ids)));
3256 +
3257 + foreach ($user_ids as $user_id_to_invite) {
3258 + //error_log("Inviting user to channel: $user_id_to_invite");
3259 +
3260 + $invite_response = wp_remote_post('https://slack.com/api/conversations.invite', [
3261 + 'headers' => [
3262 + 'Content-Type' => 'application/json',
3263 + 'Authorization' => 'Bearer ' . $slack_bot_token
3264 + ],
3265 + 'body' => json_encode([
3266 + 'channel' => $channel_id,
3267 + 'users' => $user_id_to_invite
3268 + ])
3269 + ]);
3270 +
3271 + if (!is_wp_error($invite_response)) {
3272 + $invite_body = wp_remote_retrieve_body($invite_response);
3273 + $invite_data = json_decode($invite_body, true);
3274 + //error_log("Invite response for $user_id_to_invite: " . $invite_body);
3275 +
3276 + if (isset($invite_data['ok']) && $invite_data['ok']) {
3277 + //error_log("Successfully invited user $user_id_to_invite to channel");
3278 + } else {
3279 + //error_log("Failed to invite user $user_id_to_invite: " . ($invite_data['error'] ?? 'Unknown error'));
3280 + }
3281 + } else {
3282 + //error_log("WP Error inviting user $user_id_to_invite: " . $invite_response->get_error_message());
3283 + }
3284 + }
3285 + } else {
3286 + //error_log("No agent user IDs configured for auto-invite");
3287 + }
3288 + } else {
3289 + //error_log("Channel creation failed: " . ($response_data['error'] ?? 'Unknown error'));
3290 + }
3291 + } else {
3292 + //error_log("WP Error creating channel: " . $response->get_error_message());
3293 + }
3294 +
3295 + if (empty($channel_id)) {
3296 + return false; // Failed to create channel
3297 + }
3298 + }
3299 +
3300 + // Get recent chat history
3301 + $history = get_option("mxchat_history_{$session_id}", []);
3302 + $recent_history = array_slice($history, -5);
3303 +
3304 + // Format conversation context
3305 + $conversation_context = "";
3306 + if (!empty($recent_history)) {
3307 + $conversation_context = "*Recent Conversation:*\n";
3308 + foreach ($recent_history as $hist_message) {
3309 + $role_display = $hist_message['role'] === 'user' ? 'User' : 'AI';
3310 + $conversation_context .= ">{$role_display}: {$hist_message['content']}\n";
3311 + }
3312 + $conversation_context .= "\n";
3313 + }
3314 +
3315 + update_option("mxchat_mode_{$session_id}", 'agent');
3316 +
3317 + // Send message to channel
3318 + $channel_message = "🔔 *New Live Agent Request*\n\n";
3319 + $channel_message .= "*Session ID:* `{$session_id}`\n";
3320 + $channel_message .= "*User ID:* `{$user_id}`\n\n";
3321 +
3322 + if (!empty($conversation_context)) {
3323 + $channel_message .= $conversation_context;
3324 + }
3325 +
3326 + $channel_message .= "*Current Message:*\n{$message}\n\n";
3327 + $channel_message .= "_Reply directly in this channel - all messages will go to the user_";
3328 +
3329 + wp_remote_post('https://slack.com/api/chat.postMessage', [
3330 + 'headers' => [
3331 + 'Content-Type' => 'application/json',
3332 + 'Authorization' => 'Bearer ' . $slack_bot_token
3333 + ],
3334 + 'body' => json_encode([
3335 + 'channel' => $channel_id,
3336 + 'text' => $channel_message,
3337 + 'mrkdwn' => true
3338 + ])
3339 + ]);
3340 +
3341 + $success_message = $this->options['live_agent_notification_message'] ?? 'Live agent has been notified.';
3342 + $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
3343 +
3344 + $this->fallbackResponse = [
3345 + 'text' => $success_message,
3346 + 'html' => '',
3347 + 'images' => [],
3348 + 'chat_mode' => 'agent'
3349 + ];
3350 +
3351 + wp_send_json([
3352 + 'success' => true,
3353 + 'text' => $success_message,
3354 + 'html' => '',
3355 + 'chat_mode' => 'agent',
3356 + 'session_id' => $session_id,
3357 + 'fallbackResponse' => $this->fallbackResponse
3358 + ]);
3359 + wp_die();
3360 +}
3361 +
3362 +private function generate_channel_name($session_id) {
3363 + $email = null;
3364 + $name = null;
3365 +
3366 + // 1. First priority: Check if user is logged in and get their info
3367 + if (is_user_logged_in()) {
3368 + $current_user = wp_get_current_user();
3369 + if (!empty($current_user->user_email)) {
3370 + $email = $current_user->user_email;
3371 + //error_log("[DEBUG] Using logged-in user email for channel: {$email}");
3372 + }
3373 + if (!empty($current_user->display_name)) {
3374 + $name = $current_user->display_name;
3375 + //error_log("[DEBUG] Using logged-in user name for channel: {$name}");
3376 + }
3377 + }
3378 +
3379 + // 2. Second priority: Check for saved email/name from "require email to chat" option
3380 + if (empty($email)) {
3381 + $email_option_key = "mxchat_email_{$session_id}";
3382 + $saved_email = get_option($email_option_key);
3383 + if (!empty($saved_email)) {
3384 + $email = $saved_email;
3385 + //error_log("[DEBUG] Using saved email from session for channel: {$email}");
3386 + }
3387 + }
3388 +
3389 + if (empty($name)) {
3390 + $name_option_key = "mxchat_name_{$session_id}";
3391 + $saved_name = get_option($name_option_key);
3392 + if (!empty($saved_name)) {
3393 + $name = $saved_name;
3394 + //error_log("[DEBUG] Using saved name from session for channel: {$name}");
3395 + }
3396 + }
3397 +
3398 + // 3. Third priority: Check existing chat transcript for email/name
3399 + if (empty($email) || empty($name)) {
3400 + global $wpdb;
3401 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
3402 + $existing_data = $wpdb->get_row($wpdb->prepare(
3403 + "SELECT user_email, user_name FROM $table_name WHERE session_id = %s AND (user_email IS NOT NULL OR user_name IS NOT NULL) LIMIT 1",
3404 + $session_id
3405 + ));
3406 +
3407 + if ($existing_data) {
3408 + if (empty($email) && !empty($existing_data->user_email)) {
3409 + $email = $existing_data->user_email;
3410 + //error_log("[DEBUG] Using email from chat transcript for channel: {$email}");
3411 + }
3412 + if (empty($name) && !empty($existing_data->user_name)) {
3413 + $name = $existing_data->user_name;
3414 + //error_log("[DEBUG] Using name from chat transcript for channel: {$name}");
3415 + }
3416 + }
3417 + }
3418 +
3419 + // 4. Generate channel name based on priority: Name > Email > Session ID
3420 + $channel_name = '';
3421 +
3422 + if (!empty($name)) {
3423 + // Convert name to valid Slack channel name
3424 + $base_name = strtolower(trim($name));
3425 + // Replace spaces and invalid characters
3426 + $base_name = preg_replace('/[^a-z0-9\s]/', '', $base_name);
3427 + $base_name = preg_replace('/\s+/', '-', $base_name);
3428 + $base_name = trim($base_name, '-');
3429 +
3430 + // Get last 4 characters of session ID for uniqueness
3431 + $session_suffix = substr($session_id, -4);
3432 + $channel_name = 'chat-' . $base_name . '-' . strtolower($session_suffix);
3433 +
3434 + // Slack channel names have a 21 character limit
3435 + if (strlen($channel_name) > 21) {
3436 + // Calculate available space for name (21 - 'chat-' - '-' - session_suffix)
3437 + $available_space = 21 - 5 - 1 - strlen($session_suffix); // 'chat-' = 5, '-' = 1
3438 + $truncated_name = substr($base_name, 0, $available_space);
3439 + $truncated_name = rtrim($truncated_name, '-'); // Remove trailing hyphen
3440 + $channel_name = 'chat-' . $truncated_name . '-' . strtolower($session_suffix);
3441 + }
3442 +
3443 + //error_log("[DEBUG] Using name for channel: {$channel_name} (from name: {$name})");
3444 +
3445 + } elseif (!empty($email)) {
3446 + // Convert email to valid Slack channel name (your existing logic)
3447 + $channel_name = 'chat-' . strtolower(str_replace(['@', '.', '+', '_'], ['-at-', '-', '-plus-', '-'], $email));
3448 + // Remove any remaining invalid characters
3449 + $channel_name = preg_replace('/[^a-z0-9\-]/', '', $channel_name);
3450 + // Ensure it doesn't end with a hyphen
3451 + $channel_name = rtrim($channel_name, '-');
3452 + // Slack channel names have a 21 character limit, so truncate if needed
3453 + if (strlen($channel_name) > 21) {
3454 + $channel_name = substr($channel_name, 0, 21);
3455 + $channel_name = rtrim($channel_name, '-'); // Remove trailing hyphen if truncation created one
3456 + }
3457 +
3458 + //error_log("[DEBUG] Using email for channel: {$channel_name} (from email: {$email})");
3459 +
3460 + } else {
3461 + // Fallback to session ID if no name or email found
3462 + $channel_name = 'chat-' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $session_id));
3463 + //error_log("[DEBUG] No name or email found, using session ID for channel: {$channel_name}");
3464 + }
3465 +
3466 + // Final validation - ensure channel name meets Slack requirements
3467 + if (strlen($channel_name) > 21) {
3468 + $channel_name = substr($channel_name, 0, 21);
3469 + $channel_name = rtrim($channel_name, '-');
3470 + }
3471 +
3472 + //error_log("[DEBUG] Generated channel name: {$channel_name}");
3473 + return $channel_name;
3474 +}
3475 +public function mxchat_send_user_message_to_agent($message, $user_id, $session_id) {
3476 + $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
3477 + $channel_id = get_option("mxchat_channel_{$session_id}", '');
3478 +
3479 + if (empty($slack_bot_token) || empty($channel_id)) {
3480 + return false;
3481 + }
3482 +
3483 + $user_message = "💬 *User:* {$message}";
3484 +
3485 + $response = wp_remote_post('https://slack.com/api/chat.postMessage', [
3486 + 'headers' => [
3487 + 'Content-Type' => 'application/json',
3488 + 'Authorization' => 'Bearer ' . $slack_bot_token
3489 + ],
3490 + 'body' => json_encode([
3491 + 'channel' => $channel_id,
3492 + 'text' => $user_message,
3493 + 'mrkdwn' => true
3494 + ])
3495 + ]);
3496 +
3497 + return !is_wp_error($response);
3498 +}
3499 +public function handle_slack_interaction(WP_REST_Request $request) {
3500 + //error_log('Received Slack interaction');
3501 +
3502 + $payload = json_decode($request->get_param('payload'), true);
3503 + //error_log('Payload: ' . print_r($payload, true));
3504 +
3505 + // Handle button click
3506 + if ($payload['type'] === 'block_actions' && $payload['actions'][0]['action_id'] === 'reply_to_user') {
3507 + $session_id = $payload['actions'][0]['value'];
3508 + $trigger_id = $payload['trigger_id'];
3509 +
3510 + // Get Bot Token from settings
3511 + $slack_token = $this->options['live_agent_bot_token'] ?? '';
3512 +
3513 + if (empty($slack_token)) {
3514 + //error_log('Slack Bot Token not configured');
3515 + return new WP_REST_Response(['error' => esc_html__('Bot token not configured', 'mxchat')], 400);
3516 + }
3517 + $response = wp_remote_post('https://slack.com/api/views.open', [
3518 + 'headers' => [
3519 + 'Content-Type' => 'application/json',
3520 + 'Authorization' => 'Bearer ' . $slack_token
3521 + ],
3522 + 'body' => json_encode([
3523 + 'trigger_id' => $trigger_id,
3524 + 'view' => [
3525 + 'type' => 'modal',
3526 + 'callback_id' => 'reply_modal',
3527 + 'title' => [
3528 + 'type' => 'plain_text',
3529 + 'text' => __('Reply to User', 'mxchat')
3530 + ],
3531 + 'submit' => [
3532 + 'type' => 'plain_text',
3533 + 'text' => __('Send', 'mxchat')
3534 + ],
3535 + 'close' => [
3536 + 'type' => 'plain_text',
3537 + 'text' => __('Cancel', 'mxchat')
3538 + ],
3539 + 'blocks' => [
3540 + [
3541 + 'type' => 'input',
3542 + 'block_id' => 'reply_block',
3543 + 'label' => [
3544 + 'type' => 'plain_text',
3545 + 'text' => sprintf(__('Reply to session: %s', 'mxchat'), $session_id)
3546 + ],
3547 + 'element' => [
3548 + 'type' => 'plain_text_input',
3549 + 'action_id' => 'message',
3550 + 'multiline' => true,
3551 + 'placeholder' => [
3552 + 'type' => 'plain_text',
3553 + 'text' => __('Type your message here...', 'mxchat')
3554 + ]
3555 + ]
3556 + ]
3557 + ],
3558 + 'private_metadata' => $session_id
3559 + ]
3560 + ])
3561 + ]);
3562 +
3563 + //error_log('Views.open response: ' . print_r($response, true));
3564 +
3565 + // Return immediate acknowledgment
3566 + return new WP_REST_Response(['ok' => true]);
3567 + }
3568 +
3569 + // Handle modal submission
3570 +// Handle modal submission
3571 +if ($payload['type'] === 'view_submission') {
3572 + $session_id = $payload['view']['private_metadata'];
3573 + $message = $payload['view']['state']['values']['reply_block']['message']['value'];
3574 +
3575 + // Save the message (keep the message_id but don't include in response)
3576 + $this->mxchat_save_chat_message($session_id, 'agent', $message);
3577 +
3578 + // Keep the original response format for Slack
3579 + return new WP_REST_Response([
3580 + 'response_action' => 'clear'
3581 + ]);
3582 +}
3583 +
3584 + // Default acknowledgment
3585 + return new WP_REST_Response(['ok' => true]);
3586 +}
3587 +public function mxchat_handle_agent_response(WP_REST_Request $request) {
3588 + //error_log('Received agent response request');
3589 + //error_log('Request data: ' . print_r($request->get_params(), true));
3590 + // //error_log('Raw body: ' . file_get_contents('php://input'));
3591 +
3592 + // Get the data from Slack's slash command format
3593 + $command_text = $request->get_param('text');
3594 + // //error_log('Command text: ' . $command_text);
3595 +
3596 + if (empty($command_text)) {
3597 + //error_log(esc_html__('Agent response error: No command text received', 'mxchat'));
3598 + return new WP_REST_Response([
3599 + 'error' => esc_html__('Command text is required. Format: /reply session_id message', 'mxchat')
3600 + ], 400);
3601 + }
3602 +
3603 + // Split the command text into session_id and message
3604 + $parts = explode(' ', $command_text, 2);
3605 + if (count($parts) !== 2) {
3606 + //error_log('Agent response error: Invalid command format');
3607 + return new WP_REST_Response([
3608 + 'error' => esc_html__('Invalid format. Use: /reply session_id message', 'mxchat')
3609 + ], 400);
3610 + }
3611 +
3612 + $session_id = sanitize_text_field($parts[0]);
3613 + $message = sanitize_text_field($parts[1]);
3614 +
3615 + //error_log("Processing agent response - Session ID: $session_id, Message: $message");
3616 +
3617 + // Save the message
3618 + $message_id = $this->mxchat_save_chat_message($session_id, 'agent', $message);
3619 +
3620 + if (!$message_id) {
3621 + // //error_log('Failed to save agent message');
3622 + return new WP_REST_Response([
3623 + 'error' => esc_html__('Failed to save message', 'mxchat')
3624 + ], 500);
3625 + }
3626 +
3627 + // Return success response in Slack's expected format
3628 + return new WP_REST_Response([
3629 + 'response_type' => 'in_channel',
3630 + 'text' => esc_html__("Message sent successfully to session $session_id", 'mxchat')
3631 + ], 200);
3632 +}
3633 +public function mxchat_handle_switch_to_chatbot_intent($message, $user_id, $session_id) {
3634 + // Update mode to AI
3635 + update_option("mxchat_mode_{$session_id}", 'ai');
3636 +
3637 + // Clear any existing PDF context to start fresh
3638 + $this->clear_pdf_transients($session_id);
3639 +
3640 + // Set the response with explicit chat_mode
3641 + $this->fallbackResponse = [
3642 + 'text' => esc_html__('You are now chatting with the AI chatbot.', 'mxchat'),
3643 + 'html' => '',
3644 + 'images' => [],
3645 + 'chat_mode' => 'ai' // Ensure this is set
3646 + ];
3647 +
3648 + // Return the complete response array instead of just true
3649 + return $this->fallbackResponse;
3650 +}
3651 +
3652 +public function handle_slack_messages(WP_REST_Request $request) {
3653 + // Log the incoming request for debugging
3654 + //error_log('Slack events request received: ' . $request->get_body());
3655 +
3656 + $body = $request->get_body();
3657 + $data = json_decode($body, true);
3658 +
3659 + // Handle Slack URL verification
3660 + if (isset($data['type']) && $data['type'] === 'url_verification') {
3661 + //error_log('Slack URL verification challenge: ' . $data['challenge']);
3662 + return new WP_REST_Response($data['challenge'], 200, ['Content-Type' => 'text/plain']);
3663 + }
3664 +
3665 + // IMPORTANT: Handle Slack's event deduplication
3666 + if (isset($data['event_id'])) {
3667 + $event_id = $data['event_id'];
3668 + $processed_events = get_transient('mxchat_slack_events') ?: [];
3669 +
3670 + // Check if we've already processed this event
3671 + if (in_array($event_id, $processed_events)) {
3672 + //error_log("Duplicate event detected: $event_id");
3673 + return new WP_REST_Response(['ok' => true]);
3674 + }
3675 +
3676 + // Add this event to processed list
3677 + $processed_events[] = $event_id;
3678 + // Keep only last 100 events to prevent memory issues
3679 + if (count($processed_events) > 100) {
3680 + $processed_events = array_slice($processed_events, -100);
3681 + }
3682 + // Store for 1 hour
3683 + set_transient('mxchat_slack_events', $processed_events, HOUR_IN_SECONDS);
3684 + }
3685 +
3686 + // Handle message events
3687 + if (isset($data['event']) && $data['event']['type'] === 'message') {
3688 + $event = $data['event'];
3689 +
3690 + // Skip bot messages and messages with subtypes (like bot_message)
3691 + if (isset($event['bot_id']) || isset($event['subtype'])) {
3692 + return new WP_REST_Response(['ok' => true]);
3693 + }
3694 +
3695 + // Additional check: Skip if this is a threaded reply to our confirmation
3696 + if (isset($event['thread_ts']) && $event['thread_ts'] !== $event['ts']) {
3697 + return new WP_REST_Response(['ok' => true]);
3698 + }
3699 +
3700 + $channel_id = $event['channel'];
3701 + $message_text = $event['text'] ?? '';
3702 + $message_ts = $event['ts'] ?? '';
3703 +
3704 + // Find session ID by looking for matching channel
3705 + global $wpdb;
3706 + $session_option = $wpdb->get_var(
3707 + $wpdb->prepare(
3708 + "SELECT option_name FROM {$wpdb->options}
3709 + WHERE option_name LIKE 'mxchat_channel_%'
3710 + AND option_value = %s",
3711 + $channel_id
3712 + )
3713 + );
3714 +
3715 + if ($session_option) {
3716 + $session_id = str_replace('mxchat_channel_', '', $session_option);
3717 +
3718 + // Create a unique key for this specific message
3719 + $message_key = md5($session_id . $message_ts . $message_text);
3720 + $processed_messages = get_transient('mxchat_processed_messages_' . $session_id) ?: [];
3721 +
3722 + // Check if we've already processed this exact message
3723 + if (in_array($message_key, $processed_messages)) {
3724 + //error_log("Duplicate message detected for session $session_id");
3725 + return new WP_REST_Response(['ok' => true]);
3726 + }
3727 +
3728 + // Add to processed messages
3729 + $processed_messages[] = $message_key;
3730 + // Keep only last 50 messages per session
3731 + if (count($processed_messages) > 50) {
3732 + $processed_messages = array_slice($processed_messages, -50);
3733 + }
3734 + set_transient('mxchat_processed_messages_' . $session_id, $processed_messages, HOUR_IN_SECONDS);
3735 +
3736 + // Save the agent message
3737 + $this->mxchat_save_chat_message($session_id, 'agent', $message_text);
3738 +
3739 + // Send confirmation back to Slack (only once)
3740 + $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
3741 + if (!empty($slack_bot_token)) {
3742 + // Use a transient to prevent duplicate confirmations
3743 + $confirm_key = 'mxchat_confirm_' . $message_key;
3744 + if (!get_transient($confirm_key)) {
3745 + wp_remote_post('https://slack.com/api/chat.postMessage', [
3746 + 'headers' => [
3747 + 'Content-Type' => 'application/json',
3748 + 'Authorization' => 'Bearer ' . $slack_bot_token
3749 + ],
3750 + 'body' => json_encode([
3751 + 'channel' => $channel_id,
3752 + 'text' => "✅ _Message sent to user_",
3753 + 'thread_ts' => $event['ts'] // Reply in thread
3754 + ])
3755 + ]);
3756 + // Set transient to prevent duplicate confirmations
3757 + set_transient($confirm_key, true, 300); // 5 minutes
3758 + }
3759 + }
3760 + }
3761 + }
3762 +
3763 + return new WP_REST_Response(['ok' => true]);
3764 +}
3765 +
3766 +// For the word upload handler
3767 +public function mxchat_handle_word_upload() {
3768 + // Delegate to word handler
3769 + $this->word_handler->mxchat_handle_word_upload();
3770 +}
3771 +
3772 +// For the word removal handler
3773 +public function mxchat_handle_word_remove() {
3774 + // Delegate to word handler
3775 + $this->word_handler->mxchat_handle_word_remove();
3776 +}
3777 +
3778 +// For the word status check
3779 +public function mxchat_check_word_status() {
3780 + // Delegate to word handler
3781 + $this->word_handler->mxchat_check_word_status();
3782 +}
3783 +
3784 +
3785 +private function mxchat_get_user_identifier() {
3786 + return MxChat_User::mxchat_get_user_identifier();
3787 +}
3788 +
3789 +private function mxchat_generate_embedding($text, $api_key) {
3790 + try {
3791 + // Get options and selected model
3792 + $options = get_option('mxchat_options');
3793 + $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
3794 +
3795 + // Determine endpoint and API key based on model
3796 + if (strpos($selected_model, 'voyage') === 0) {
3797 + $endpoint = 'https://api.voyageai.com/v1/embeddings';
3798 + $api_key = $options['voyage_api_key'] ?? '';
3799 +
3800 + // Check if Voyage API key is missing
3801 + if (empty($api_key)) {
3802 + //error_log('Voyage API key is missing');
3803 + return [
3804 + 'error' => esc_html__('Voyage AI API key is not configured', 'mxchat'),
3805 + 'error_code' => 'missing_voyage_api_key'
3806 + ];
3807 + }
3808 + } elseif (strpos($selected_model, 'gemini-embedding') === 0) {
3809 + $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $selected_model . ':embedContent';
3810 + $api_key = $options['gemini_api_key'] ?? '';
3811 +
3812 + // Check if Gemini API key is missing
3813 + if (empty($api_key)) {
3814 + //error_log('Gemini API key is missing');
3815 + return [
3816 + 'error' => esc_html__('Google Gemini API key is not configured', 'mxchat'),
3817 + 'error_code' => 'missing_gemini_api_key'
3818 + ];
3819 + }
3820 + } else {
3821 + $endpoint = 'https://api.openai.com/v1/embeddings';
3822 + // Use the passed API key for OpenAI
3823 +
3824 + // Check if OpenAI API key is missing
3825 + if (empty($api_key)) {
3826 + //error_log('OpenAI API key is missing');
3827 + return [
3828 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
3829 + 'error_code' => 'missing_openai_api_key'
3830 + ];
3831 + }
3832 + }
3833 +
3834 + // Check if text is empty
3835 + if (empty($text)) {
3836 + //error_log('Empty text provided for embedding generation');
3837 + return [
3838 + 'error' => esc_html__('No text provided for embedding generation', 'mxchat'),
3839 + 'error_code' => 'empty_embedding_text'
3840 + ];
3841 + }
3842 +
3843 + // Prepare request body based on provider
3844 + if (strpos($selected_model, 'gemini-embedding') === 0) {
3845 + // Gemini API format
3846 + $request_body = [
3847 + 'model' => 'models/' . $selected_model,
3848 + 'content' => [
3849 + 'parts' => [
3850 + ['text' => $text]
3851 + ]
3852 + ],
3853 + 'outputDimensionality' => 1536
3854 + ];
3855 +
3856 + // Prepare headers for Gemini (API key as query parameter)
3857 + $endpoint .= '?key=' . $api_key;
3858 + $headers = [
3859 + 'Content-Type' => 'application/json'
3860 + ];
3861 + } else {
3862 + // OpenAI/Voyage API format
3863 + $request_body = [
3864 + 'input' => $text,
3865 + 'model' => $selected_model
3866 + ];
3867 +
3868 + // Add output_dimension for voyage-3-large
3869 + if ($selected_model === 'voyage-3-large') {
3870 + $request_body['output_dimension'] = 2048;
3871 + }
3872 +
3873 + // Prepare headers for OpenAI/Voyage
3874 + $headers = [
3875 + 'Content-Type' => 'application/json',
3876 + 'Authorization' => 'Bearer ' . $api_key
3877 + ];
3878 + }
3879 +
3880 + // Prepare request arguments
3881 + $args = [
3882 + 'body' => wp_json_encode($request_body),
3883 + 'headers' => $headers,
3884 + 'timeout' => 60,
3885 + 'redirection' => 5,
3886 + 'blocking' => true,
3887 + 'httpversion' => '1.0',
3888 + 'sslverify' => true,
3889 + ];
3890 +
3891 + // Make the request
3892 + $response = wp_remote_post($endpoint, $args);
3893 +
3894 + // Handle WordPress errors
3895 + if (is_wp_error($response)) {
3896 + $error_message = $response->get_error_message();
3897 + //error_log('Embedding Generation Error: ' . $error_message);
3898 + return [
3899 + 'error' => esc_html__('Connection error when generating embeddings: ', 'mxchat') . esc_html($error_message),
3900 + 'error_code' => 'embedding_connection_error'
3901 + ];
3902 + }
3903 +
3904 + // Check HTTP status code
3905 + $status_code = wp_remote_retrieve_response_code($response);
3906 + if ($status_code !== 200) {
3907 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
3908 +
3909 + $error_message = isset($response_body['error']['message'])
3910 + ? $response_body['error']['message']
3911 + : 'HTTP Error ' . $status_code;
3912 +
3913 + $error_type = isset($response_body['error']['type'])
3914 + ? $response_body['error']['type']
3915 + : 'unknown';
3916 +
3917 + //error_log('Embedding API HTTP Error: ' . $status_code . ' - ' . $error_message);
3918 +
3919 + // Handle specific error types
3920 + switch ($error_type) {
3921 + case 'invalid_request_error':
3922 + if (strpos($error_message, 'API key') !== false) {
3923 + return [
3924 + 'error' => esc_html__('Invalid API key for embedding generation. Please check your API key configuration.', 'mxchat'),
3925 + 'error_code' => 'embedding_invalid_api_key'
3926 + ];
3927 + }
3928 + break;
3929 +
3930 + case 'authentication_error':
3931 + return [
3932 + 'error' => esc_html__('Authentication failed for embedding generation. Please check your API key.', 'mxchat'),
3933 + 'error_code' => 'embedding_auth_error'
3934 + ];
3935 +
3936 + case 'rate_limit_exceeded':
3937 + return [
3938 + 'error' => esc_html__('Rate limit exceeded for embedding generation. Please try again later.', 'mxchat'),
3939 + 'error_code' => 'embedding_rate_limit'
3940 + ];
3941 +
3942 + case 'quota_exceeded':
3943 + return [
3944 + 'error' => esc_html__('API quota exceeded for embedding generation. Please check your billing details.', 'mxchat'),
3945 + 'error_code' => 'embedding_quota_exceeded'
3946 + ];
3947 + }
3948 +
3949 + // Generic error fallback
3950 + return [
3951 + 'error' => esc_html__('Embedding API error - check embedding API key.: ', 'mxchat') . esc_html($error_message),
3952 + 'error_code' => 'embedding_api_error',
3953 + 'status_code' => $status_code
3954 + ];
3955 + }
3956 +
3957 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
3958 +
3959 + // Handle different response formats based on provider
3960 + if (strpos($selected_model, 'gemini-embedding') === 0) {
3961 + // Gemini API response format
3962 + if (isset($response_body['embedding']['values']) && is_array($response_body['embedding']['values'])) {
3963 + return $response_body['embedding']['values'];
3964 + } else {
3965 + //error_log('Invalid Gemini embedding response: ' . wp_json_encode($response_body));
3966 + return [
3967 + 'error' => esc_html__('Received invalid embedding data from the Gemini API.', 'mxchat'),
3968 + 'error_code' => 'invalid_gemini_embedding_response'
3969 + ];
3970 + }
3971 + } else {
3972 + // OpenAI/Voyage API response format
3973 + if (isset($response_body['data'][0]['embedding']) && is_array($response_body['data'][0]['embedding'])) {
3974 + return $response_body['data'][0]['embedding'];
3975 + } else {
3976 + //error_log('Invalid embedding response: ' . wp_json_encode($response_body));
3977 + return [
3978 + 'error' => esc_html__('Received invalid embedding data from the API.', 'mxchat'),
3979 + 'error_code' => 'invalid_embedding_response'
3980 + ];
3981 + }
3982 + }
3983 + } catch (Exception $e) {
3984 + //error_log('Embedding Exception: ' . $e->getMessage());
3985 + return [
3986 + 'error' => esc_html__('System error when generating embeddings: ', 'mxchat') . esc_html($e->getMessage()),
3987 + 'error_code' => 'embedding_exception'
3988 + ];
3989 + }
3990 +}
3991 +
3992 +
3993 +private function mxchat_find_relevant_content($user_embedding, $bot_id = 'default') {
3994 + error_log("MXCHAT DEBUG: find_relevant_content called with bot_id: " . $bot_id);
3995 +
3996 + // Get bot-specific Pinecone configuration
3997 + $bot_pinecone_config = $this->get_bot_pinecone_config($bot_id);
3998 +
3999 + // Debug: Log the Pinecone configuration
4000 + error_log("MXCHAT DEBUG: Pinecone config for bot '$bot_id':");
4001 + error_log(" - use_pinecone: " . ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false'));
4002 + error_log(" - api_key: " . (empty($bot_pinecone_config['api_key']) ? 'EMPTY' : 'SET (hidden)'));
4003 + error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'NOT SET'));
4004 + error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'NOT SET'));
4005 +
4006 + // Determine whether to use Pinecone based on bot configuration
4007 + $use_pinecone = isset($bot_pinecone_config['use_pinecone']) ? $bot_pinecone_config['use_pinecone'] : false;
4008 +
4009 + error_log("MXCHAT DEBUG: Using " . ($use_pinecone ? "Pinecone" : "WordPress Database") . " for knowledge retrieval");
4010 +
4011 + if ($use_pinecone) {
4012 + return $this->find_relevant_content_pinecone($user_embedding, $bot_id, $bot_pinecone_config);
4013 + } else {
4014 + return $this->find_relevant_content_wordpress($user_embedding, $bot_id);
4015 + }
4016 +}
4017 +
4018 +private function find_relevant_content_wordpress($user_embedding, $bot_id = 'default') {
4019 + global $wpdb;
4020 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
4021 + $cache_key = 'mxchat_system_prompt_embeddings_' . $bot_id;
4022 + $batch_size = 500;
4023 +
4024 + // Initialize similarity analysis storage
4025 + $this->last_similarity_analysis = [
4026 + 'knowledge_base_type' => 'WordPress Database',
4027 + 'bot_id' => $bot_id,
4028 + 'top_matches' => [],
4029 + 'threshold_used' => 0,
4030 + 'total_checked' => 0
4031 + ];
4032 +
4033 + // NEW: Initialize valid URLs array
4034 + $valid_urls = [];
4035 +
4036 + // Get bot-specific options for similarity threshold
4037 + $bot_options = $this->get_bot_options($bot_id);
4038 + $current_options = !empty($bot_options) ? $bot_options : $this->options;
4039 +
4040 + // Retrieve embeddings from cache or database
4041 + $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
4042 + if ($embeddings === false) {
4043 + // Cache miss - load embeddings from database WITH CONTENT and ROLE RESTRICTION for testing
4044 + $embeddings = [];
4045 + $offset = 0;
4046 +
4047 + do {
4048 + // Add bot_id filter if not default and if bot_metadata column exists
4049 + $bot_filter = '';
4050 + if ($bot_id !== 'default') {
4051 + // Check if bot_metadata column exists
4052 + $column_exists = $wpdb->get_var("SHOW COLUMNS FROM {$system_prompt_table} LIKE 'bot_metadata'");
4053 + if ($column_exists) {
4054 + $bot_filter = $wpdb->prepare(" AND (bot_metadata = %s OR bot_metadata IS NULL OR bot_metadata = '')", $bot_id);
4055 + }
4056 + }
4057 +
4058 + $query = $wpdb->prepare(
4059 + "SELECT id, embedding_vector, article_content, source_url, role_restriction
4060 + FROM {$system_prompt_table}
4061 + WHERE 1=1 {$bot_filter}
4062 + LIMIT %d OFFSET %d",
4063 + $batch_size,
4064 + $offset
4065 + );
4066 +
4067 + $batch = $wpdb->get_results($query);
4068 + if (empty($batch)) {
4069 + break;
4070 + }
4071 +
4072 + $embeddings = array_merge($embeddings, $batch);
4073 + $offset += $batch_size;
4074 + unset($batch);
4075 + } while (true);
4076 +
4077 + if (empty($embeddings)) {
4078 + // Store empty array for valid URLs since no content found
4079 + $this->current_valid_urls = [];
4080 + return '';
4081 + }
4082 +
4083 + // Cache embeddings for future use (but note: this now includes content and role restrictions)
4084 + wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
4085 + }
4086 +
4087 + // Get knowledge manager instance for role checking
4088 + $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
4089 +
4090 + // Get base similarity threshold from bot options or default options
4091 + $similarity_threshold = isset($current_options['similarity_threshold'])
4092 + ? ((int) $current_options['similarity_threshold']) / 100
4093 + : 0.35;
4094 +
4095 + $this->last_similarity_analysis['threshold_used'] = $similarity_threshold;
4096 +
4097 + // Calculate similarities and build results array
4098 + $all_similarities = [];
4099 + $relevant_results = [];
4100 +
4101 + foreach ($embeddings as $embedding) {
4102 + $database_embedding = $embedding->embedding_vector
4103 + ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
4104 + : null;
4105 +
4106 + if (is_array($database_embedding) && is_array($user_embedding)) {
4107 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
4108 +
4109 + // Check role access
4110 + $role_restriction = $embedding->role_restriction ?? 'public';
4111 + $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
4112 +
4113 + // Store ALL similarities for testing (top 10)
4114 + $source_display = '';
4115 + if (!empty($embedding->source_url) && $embedding->source_url !== '#') {
4116 + $source_display = $embedding->source_url;
4117 + } else {
4118 + $content_preview = strip_tags($embedding->article_content ?? '');
4119 + $content_preview = preg_replace('/\s+/', ' ', $content_preview);
4120 + $source_display = substr(trim($content_preview), 0, 50) . '...';
4121 + }
4122 +
4123 + $all_similarities[] = [
4124 + 'document_id' => $embedding->id,
4125 + 'similarity' => $similarity,
4126 + 'similarity_percentage' => round($similarity * 100, 2),
4127 + 'above_threshold' => $similarity >= $similarity_threshold,
4128 + 'source_display' => $source_display,
4129 + 'content_preview' => substr(strip_tags($embedding->article_content ?? ''), 0, 100) . '...',
4130 + 'used_for_context' => false, // Initialize as false, we'll update this later
4131 + 'role_restriction' => $role_restriction,
4132 + 'has_access' => $has_access,
4133 + 'filtered_out' => !$has_access
4134 + ];
4135 +
4136 + // Only consider results above threshold AND with access for actual content retrieval
4137 + if ($similarity >= $similarity_threshold && $has_access) {
4138 + $relevant_results[] = [
4139 + 'id' => $embedding->id,
4140 + 'similarity' => $similarity
4141 + ];
4142 + }
4143 + }
4144 +
4145 + unset($database_embedding);
4146 + }
4147 +
4148 + // Sort ALL similarities for testing display (highest first)
4149 + usort($all_similarities, function ($a, $b) {
4150 + return $b['similarity'] <=> $a['similarity'];
4151 + });
4152 +
4153 + // Sort relevant results by similarity (highest first)
4154 + usort($relevant_results, function ($a, $b) {
4155 + return $b['similarity'] <=> $a['similarity'];
4156 + });
4157 +
4158 + // Get top 5 results for actual content (standard approach)
4159 + $top_results = array_slice($relevant_results, 0, 3);
4160 +
4161 + // NOW mark which documents are actually used for context
4162 + $used_document_ids = [];
4163 + foreach ($top_results as $result) {
4164 + $used_document_ids[] = $result['id'];
4165 + }
4166 +
4167 + // Update the all_similarities array to mark which were actually used
4168 + foreach ($all_similarities as &$similarity_item) {
4169 + $similarity_item['used_for_context'] = in_array($similarity_item['document_id'], $used_document_ids);
4170 + }
4171 +
4172 + // Store top 10 for testing panel (now with correct used_for_context flags and role info)
4173 + $this->last_similarity_analysis['top_matches'] = array_slice($all_similarities, 0, 10);
4174 + $this->last_similarity_analysis['total_checked'] = count($embeddings);
4175 +
4176 + // Initialize final content
4177 + $content = '';
4178 +
4179 + // Track document IDs to avoid duplicates
4180 + $added_document_ids = [];
4181 +
4182 + // Fetch and format content for each selected result
4183 + foreach ($top_results as $index => $result) {
4184 + if (in_array($result['id'], $added_document_ids)) {
4185 + continue;
4186 + }
4187 +
4188 + $chunk_content = $this->fetch_content_with_product_links($result['id']);
4189 + $added_document_ids[] = $result['id'];
4190 +
4191 + // NEW: Extract source_url from database for this result
4192 + $source_url = $wpdb->get_var($wpdb->prepare(
4193 + "SELECT source_url FROM {$system_prompt_table} WHERE id = %d",
4194 + $result['id']
4195 + ));
4196 +
4197 + // NEW: Add source_url to valid URLs list if it exists and is not empty/placeholder
4198 + if (!empty($source_url) && $source_url !== '#') {
4199 + $valid_urls[] = $source_url;
4200 + }
4201 +
4202 + // NEW: Extract any URLs from the article content itself
4203 + preg_match_all(
4204 + '#\bhttps?://[^\s<>"\']+#i',
4205 + $chunk_content,
4206 + $content_urls
4207 + );
4208 + if (!empty($content_urls[0])) {
4209 + $valid_urls = array_merge($valid_urls, $content_urls[0]);
4210 + }
4211 +
4212 + $content .= "## Reference " . ($index + 1) . " ##\n";
4213 + $content .= $chunk_content . "\n\n";
4214 +
4215 + // PDF surrounding pages logic (unchanged)
4216 + if (strpos($chunk_content, '{"document_type":"pdf"') !== false) {
4217 + $surrounding_content = $wpdb->get_results($wpdb->prepare(
4218 + "SELECT id, article_content, role_restriction FROM {$system_prompt_table}
4219 + WHERE id IN (
4220 + (SELECT id FROM {$system_prompt_table} WHERE id < %d ORDER BY id DESC LIMIT 1),
4221 + (SELECT id FROM {$system_prompt_table} WHERE id > %d ORDER BY id ASC LIMIT 1)
4222 + )",
4223 + $result['id'],
4224 + $result['id']
4225 + ));
4226 +
4227 + // Check role access for surrounding content too
4228 + if (!empty($surrounding_content[0])) {
4229 + $surrounding_role = $surrounding_content[0]->role_restriction ?? 'public';
4230 + if ($knowledge_manager->mxchat_user_has_content_access($surrounding_role)) {
4231 + // NEW: Extract URLs from surrounding content too
4232 + preg_match_all(
4233 + '#\bhttps?://[^\s<>"\']+#i',
4234 + $surrounding_content[0]->article_content,
4235 + $surrounding_urls
4236 + );
4237 + if (!empty($surrounding_urls[0])) {
4238 + $valid_urls = array_merge($valid_urls, $surrounding_urls[0]);
4239 + }
4240 +
4241 + $content .= "## Related Content ##\n";
4242 + $content .= $surrounding_content[0]->article_content . "\n\n";
4243 + $added_document_ids[] = $surrounding_content[0]->id;
4244 + }
4245 + }
4246 +
4247 + if (!empty($surrounding_content[1])) {
4248 + $surrounding_role = $surrounding_content[1]->role_restriction ?? 'public';
4249 + if ($knowledge_manager->mxchat_user_has_content_access($surrounding_role)) {
4250 + // NEW: Extract URLs from surrounding content too
4251 + preg_match_all(
4252 + '#\bhttps?://[^\s<>"\']+#i',
4253 + $surrounding_content[1]->article_content,
4254 + $surrounding_urls
4255 + );
4256 + if (!empty($surrounding_urls[0])) {
4257 + $valid_urls = array_merge($valid_urls, $surrounding_urls[0]);
4258 + }
4259 +
4260 + $content .= "## Related Content ##\n";
4261 + $content .= $surrounding_content[1]->article_content . "\n\n";
4262 + $added_document_ids[] = $surrounding_content[1]->id;
4263 + }
4264 + }
4265 + }
4266 + }
4267 +
4268 + // NEW: Store unique valid URLs for validation
4269 + $this->current_valid_urls = array_unique($valid_urls);
4270 +
4271 + // Add response guidelines
4272 + if (empty($top_results)) {
4273 + $content = "No reference information was found for this query.\n\n";
4274 + } else {
4275 + $content .= "\n## Response Guidelines ##\n" .
4276 + "You are an AI Chatbot. Answer naturally and helpfully using only the information from the references above. " .
4277 + "Be conversational and friendly, but never mention your knowledge base or training data. " .
4278 + "If you don't have specific information or are uncertain about any details, it's always " .
4279 + "better to honestly say you don't know rather than making up or guessing at answers. " .
4280 + "When information is incomplete, let them know you are unsure.\n\n" .
4281 + "CRITICAL: When creating hyperlinks, always use proper markdown format with descriptive text: " .
4282 + "[descriptive text](url). NEVER use empty brackets like [](url). The text in brackets must describe what the link is about.";
4283 + }
4284 +
4285 + return trim($content);
4286 +}
4287 +
4288 +private function find_relevant_content_pinecone($user_embedding, $bot_id = 'default', $bot_config = null) {
4289 + global $wpdb;
4290 +
4291 + error_log("MXCHAT DEBUG: find_relevant_content_pinecone called");
4292 + error_log(" - bot_id: " . $bot_id);
4293 + error_log(" - user_embedding is array: " . (is_array($user_embedding) ? 'yes' : 'no'));
4294 + error_log(" - user_embedding count: " . (is_array($user_embedding) ? count($user_embedding) : 'N/A'));
4295 +
4296 + // Use bot-specific config or fall back to default
4297 + if ($bot_config === null) {
4298 + $bot_config = $this->get_bot_pinecone_config($bot_id);
4299 + }
4300 +
4301 + $api_key = $bot_config['api_key'] ?? '';
4302 + $host = $bot_config['host'] ?? '';
4303 + $namespace = $bot_config['namespace'] ?? '';
4304 +
4305 + error_log("MXCHAT DEBUG: Pinecone query parameters:");
4306 + error_log(" - API Key: " . (empty($api_key) ? 'EMPTY - ERROR!' : 'Present (length: ' . strlen($api_key) . ')'));
4307 + error_log(" - Host: " . (empty($host) ? 'EMPTY - ERROR!' : $host));
4308 + error_log(" - Namespace: " . (empty($namespace) ? 'EMPTY (will use default)' : $namespace));
4309 +
4310 + // Initialize similarity analysis storage
4311 + $this->last_similarity_analysis = [
4312 + 'knowledge_base_type' => 'Pinecone',
4313 + 'bot_id' => $bot_id,
4314 + 'namespace' => $namespace,
4315 + 'top_matches' => [],
4316 + 'threshold_used' => 0,
4317 + 'total_checked' => 0
4318 + ];
4319 +
4320 + // NEW: Initialize valid URLs array
4321 + $valid_urls = [];
4322 +
4323 + if (empty($host) || empty($api_key)) {
4324 + error_log("MXCHAT DEBUG ERROR: Missing Pinecone host or API key!");
4325 + error_log(" - Host empty: " . (empty($host) ? 'YES' : 'NO'));
4326 + error_log(" - API key empty: " . (empty($api_key) ? 'YES' : 'NO'));
4327 + // Store empty array for valid URLs since we can't proceed
4328 + $this->current_valid_urls = [];
4329 + return '';
4330 + }
4331 +
4332 + // Get knowledge manager instance for role checking
4333 + $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
4334 +
4335 + // Get the similarity threshold from the bot options or main options
4336 + $bot_options = $this->get_bot_options($bot_id);
4337 + $current_options = !empty($bot_options) ? $bot_options : get_option('mxchat_options', []);
4338 +
4339 + $similarity_threshold = isset($current_options['similarity_threshold'])
4340 + ? ((int) $current_options['similarity_threshold']) / 100
4341 + : 0.35;
4342 +
4343 + $this->last_similarity_analysis['threshold_used'] = $similarity_threshold;
4344 +
4345 + // Prepare the query request for Pinecone
4346 + $api_endpoint = "https://{$host}/query";
4347 +
4348 + $request_body = array(
4349 + 'vector' => $user_embedding,
4350 + 'topK' => 20, // Request more to get good testing data
4351 + 'includeMetadata' => true,
4352 + 'includeValues' => true
4353 + );
4354 +
4355 + // Add namespace if specified for this bot
4356 + if (!empty($namespace)) {
4357 + $request_body['namespace'] = $namespace;
4358 + }
4359 +
4360 + error_log("MXCHAT DEBUG: About to call Pinecone API");
4361 + error_log(" - Endpoint: " . $api_endpoint);
4362 + error_log(" - Namespace in request: " . (!empty($namespace) ? $namespace : 'NOT SET'));
4363 +
4364 + $response = wp_remote_post($api_endpoint, array(
4365 + 'headers' => array(
4366 + 'Api-Key' => $api_key,
4367 + 'accept' => 'application/json',
4368 + 'content-type' => 'application/json'
4369 + ),
4370 + 'body' => wp_json_encode($request_body),
4371 + 'timeout' => 30
4372 + ));
4373 +
4374 + if (is_wp_error($response)) {
4375 + error_log("MXCHAT DEBUG ERROR: WP Error in Pinecone request: " . $response->get_error_message());
4376 + // Store empty array for valid URLs
4377 + $this->current_valid_urls = [];
4378 + return '';
4379 + }
4380 +
4381 + $response_code = wp_remote_retrieve_response_code($response);
4382 + error_log("MXCHAT DEBUG: Pinecone response code: " . $response_code);
4383 +
4384 + if ($response_code !== 200) {
4385 + $response_body = wp_remote_retrieve_body($response);
4386 + error_log("MXCHAT DEBUG ERROR: Pinecone API error response: " . substr($response_body, 0, 500));
4387 + // Store empty array for valid URLs
4388 + $this->current_valid_urls = [];
4389 + return '';
4390 + }
4391 +
4392 + // ADD DETAILED DEBUG SECTION HERE
4393 + $response_body = wp_remote_retrieve_body($response);
4394 + error_log("MXCHAT DEBUG: Raw Pinecone response length: " . strlen($response_body));
4395 +
4396 + $results = json_decode($response_body, true);
4397 +
4398 + if (json_last_error() !== JSON_ERROR_NONE) {
4399 + error_log("MXCHAT DEBUG ERROR: JSON decode error: " . json_last_error_msg());
4400 + error_log("MXCHAT DEBUG: First 500 chars of response: " . substr($response_body, 0, 500));
4401 + // Store empty array for valid URLs
4402 + $this->current_valid_urls = [];
4403 + return '';
4404 + }
4405 +
4406 + error_log("MXCHAT DEBUG: Pinecone response structure:");
4407 + error_log(" - Has 'matches' key: " . (isset($results['matches']) ? 'yes' : 'no'));
4408 + error_log(" - Has 'namespace' key: " . (isset($results['namespace']) ? 'yes (' . $results['namespace'] . ')' : 'no'));
4409 +
4410 + if (empty($results['matches'])) {
4411 + error_log("MXCHAT DEBUG: No matches found in Pinecone response");
4412 + error_log("MXCHAT DEBUG: Response keys: " . implode(', ', array_keys($results)));
4413 + // Store empty array for valid URLs
4414 + $this->current_valid_urls = [];
4415 + return '';
4416 + }
4417 +
4418 + error_log("MXCHAT DEBUG: Found " . count($results['matches']) . " matches in Pinecone");
4419 +
4420 + // Log first match details for debugging
4421 + if (!empty($results['matches'][0])) {
4422 + $first_match = $results['matches'][0];
4423 + error_log("MXCHAT DEBUG: First match details:");
4424 + error_log(" - Score: " . ($first_match['score'] ?? 'no score'));
4425 + error_log(" - Has metadata: " . (isset($first_match['metadata']) ? 'yes' : 'no'));
4426 + if (isset($first_match['metadata'])) {
4427 + error_log(" - Metadata keys: " . implode(', ', array_keys($first_match['metadata'])));
4428 + }
4429 + }
4430 +
4431 + // Initialize the final content
4432 + $content = '';
4433 + $matches_used = 0;
4434 + $matches_used_for_context = [];
4435 +
4436 + // Process each match for actual content generation (lazy role checking)
4437 + foreach ($results['matches'] as $index => $match) {
4438 + // Skip if similarity is below threshold
4439 + if ($match['score'] < $similarity_threshold) {
4440 + continue;
4441 + }
4442 +
4443 + // Limit to top 3 matches above threshold
4444 + if ($matches_used >= 3) {
4445 + break;
4446 + }
4447 +
4448 + if (!empty($match['metadata']['text'])) {
4449 + // LAZY ROLE CHECK: Only check role for content we're actually considering
4450 + $match_id = $match['id'] ?? '';
4451 + $role_restriction = $this->get_single_vector_role($match_id, $match['metadata']);
4452 + $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
4453 +
4454 + // Skip if user doesn't have access
4455 + if (!$has_access) {
4456 + continue;
4457 + }
4458 +
4459 + // User has access - add to content
4460 + $content .= "## Reference " . ($matches_used + 1) . " ##\n";
4461 + $content .= $match['metadata']['text'] . "\n\n";
4462 +
4463 + // NEW: Extract source_url from metadata if it exists
4464 + if (!empty($match['metadata']['source_url']) && $match['metadata']['source_url'] !== '#') {
4465 + $valid_urls[] = $match['metadata']['source_url'];
4466 + $content .= "URL: " . $match['metadata']['source_url'] . "\n\n";
4467 + }
4468 +
4469 + // NEW: Extract any URLs from the text content itself
4470 + preg_match_all(
4471 + '#\bhttps?://[^\s<>"\']+#i',
4472 + $match['metadata']['text'],
4473 + $content_urls
4474 + );
4475 + if (!empty($content_urls[0])) {
4476 + $valid_urls = array_merge($valid_urls, $content_urls[0]);
4477 + }
4478 +
4479 + $matches_used_for_context[] = $match['id'] ?? $index;
4480 + $matches_used++;
4481 + }
4482 + }
4483 +
4484 + // Process ALL matches for testing data (top 10) - with role checking for testing display
4485 + $all_matches = [];
4486 + foreach ($results['matches'] as $index => $match) {
4487 + if ($index >= 10) break; // Limit to top 10 for testing
4488 +
4489 + $match_id = $match['id'] ?? '';
4490 +
4491 + // Check role access for testing display (use cache if available)
4492 + $role_restriction = $this->get_single_vector_role($match_id, $match['metadata']);
4493 + $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
4494 +
4495 + $source_display = '';
4496 + if (!empty($match['metadata']['source_url'])) {
4497 + $source_display = $match['metadata']['source_url'];
4498 + } else {
4499 + $content_preview = strip_tags($match['metadata']['text'] ?? '');
4500 + $content_preview = preg_replace('/\s+/', ' ', $content_preview);
4501 + $source_display = substr(trim($content_preview), 0, 50) . '...';
4502 + }
4503 +
4504 + $match_id_for_display = $match['id'] ?? $index;
4505 +
4506 + $all_matches[] = [
4507 + 'document_id' => $match_id_for_display,
4508 + 'similarity' => $match['score'],
4509 + 'similarity_percentage' => round($match['score'] * 100, 2),
4510 + 'above_threshold' => $match['score'] >= $similarity_threshold,
4511 + 'source_display' => $source_display,
4512 + 'content_preview' => substr(strip_tags($match['metadata']['text'] ?? ''), 0, 100) . '...',
4513 + 'used_for_context' => in_array($match_id_for_display, $matches_used_for_context),
4514 + 'role_restriction' => $role_restriction,
4515 + 'has_access' => $has_access,
4516 + 'filtered_out' => !$has_access
4517 + ];
4518 + }
4519 +
4520 + // Store for testing panel
4521 + $this->last_similarity_analysis['top_matches'] = $all_matches;
4522 + $this->last_similarity_analysis['total_checked'] = count($results['matches']);
4523 +
4524 + // NEW: Store unique valid URLs for validation
4525 + $this->current_valid_urls = array_unique($valid_urls);
4526 +
4527 + // Add response guidelines
4528 + if ($matches_used === 0) {
4529 + $content = "No reference information was found for this query.\n\n";
4530 + } else {
4531 + $content .= "\n## Response Guidelines ##\n" .
4532 + "You are an AI Chatbot. Answer naturally and helpfully using only the information from the references above. " .
4533 + "Be conversational and friendly, but never mention your knowledge base or training data. " .
4534 + "If you don't have specific information or are uncertain about any details, it's always " .
4535 + "better to honestly say you don't know rather than making up or guessing at answers. " .
4536 + "When information is incomplete, let them know you are unsure.\n\n" .
4537 + "CRITICAL: When creating hyperlinks, always use proper markdown format with descriptive text: " .
4538 + "[descriptive text](url). NEVER use empty brackets like [](url). The text in brackets must describe what the link is about.";
4539 + }
4540 +
4541 + return trim($content);
4542 +}
4543 +
4544 +/**
4545 + * Get role restriction for a single vector (with caching)
4546 + */
4547 +private function get_single_vector_role($vector_id, $metadata = array()) {
4548 + global $wpdb;
4549 +
4550 + if (empty($vector_id)) {
4551 + return 'public';
4552 + }
4553 +
4554 + // Check cache first
4555 + $cache_key = 'mxchat_vector_role_' . $vector_id;
4556 + $cached_role = wp_cache_get($cache_key, 'mxchat_vector_roles');
4557 +
4558 + if ($cached_role !== false) {
4559 + return $cached_role;
4560 + }
4561 +
4562 + $role_restriction = 'public';
4563 +
4564 + // First try Pinecone metadata
4565 + if (!empty($metadata['role_restriction'])) {
4566 + $role_restriction = $metadata['role_restriction'];
4567 + } else {
4568 + // Check WordPress table for user-modified roles
4569 + $roles_table = $wpdb->prefix . 'mxchat_pinecone_roles';
4570 + $stored_role = $wpdb->get_var($wpdb->prepare(
4571 + "SELECT role_restriction FROM {$roles_table} WHERE vector_id = %s",
4572 + $vector_id
4573 + ));
4574 +
4575 + if ($stored_role) {
4576 + $role_restriction = $stored_role;
4577 + }
4578 + }
4579 +
4580 + // Cache individual role for 1 hour
4581 + wp_cache_set($cache_key, $role_restriction, 'mxchat_vector_roles', 3600);
4582 +
4583 + return $role_restriction;
4584 +}
4585 +
4586 +private function mxchat_find_relevant_products($user_embedding) {
4587 + //error_log('MXChat Vector Search: Starting product search...');
4588 +
4589 + // Retrieve the add-on settings from the database
4590 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
4591 +
4592 + // Determine whether Pinecone is enabled
4593 + $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
4594 +
4595 + //error_log('Pinecone enabled flag: ' . $use_pinecone);
4596 +
4597 + if ($use_pinecone === 1) {
4598 + //error_log('MXChat Vector Search: Using Pinecone database for products');
4599 + return $this->find_relevant_products_pinecone($user_embedding);
4600 + } else {
4601 + //error_log('MXChat Vector Search: Using WordPress database for products');
4602 + return $this->find_relevant_products_wordpress($user_embedding);
4603 + }
4604 +}
4605 +private function find_relevant_products_wordpress($user_embedding) {
4606 + global $wpdb;
4607 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
4608 + $cache_key = 'mxchat_system_prompt_embeddings';
4609 + $batch_size = 500;
4610 +
4611 + // Original WordPress database search logic
4612 + // [Previous implementation remains the same]
4613 + $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
4614 + if ($embeddings === false) {
4615 + $embeddings = [];
4616 + $offset = 0;
4617 +
4618 + do {
4619 + $query = $wpdb->prepare(
4620 + "SELECT id, embedding_vector
4621 + FROM {$system_prompt_table}
4622 + LIMIT %d OFFSET %d",
4623 + $batch_size,
4624 + $offset
4625 + );
4626 +
4627 + $batch = $wpdb->get_results($query);
4628 + if (empty($batch)) {
4629 + break;
4630 + }
4631 +
4632 + $embeddings = array_merge($embeddings, $batch);
4633 + $offset += $batch_size;
4634 +
4635 + unset($batch);
4636 +
4637 + } while (true);
4638 +
4639 + if (empty($embeddings)) {
4640 + return '';
4641 + }
4642 + wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
4643 + }
4644 +
4645 + $relevant_results = [];
4646 + foreach ($embeddings as $embedding) {
4647 + $database_embedding = $embedding->embedding_vector
4648 + ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
4649 + : null;
4650 + if (is_array($database_embedding) && is_array($user_embedding)) {
4651 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
4652 + $relevant_results[] = [
4653 + 'id' => $embedding->id,
4654 + 'similarity' => $similarity
4655 + ];
4656 + }
4657 + unset($database_embedding);
4658 + }
4659 +
4660 + // Use fixed threshold for products
4661 + $similarity_threshold = 0.85;
4662 +
4663 + $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
4664 + return $result['similarity'] >= $similarity_threshold;
4665 + });
4666 + usort($relevant_results, function ($a, $b) {
4667 + return $b['similarity'] <=> $a['similarity'];
4668 + });
4669 +
4670 + $top_results = array_slice($relevant_results, 0, 3);
4671 + $content = '';
4672 +
4673 + foreach ($top_results as $result) {
4674 + $chunk_content = $this->fetch_content_with_product_links($result['id']);
4675 + $content .= $chunk_content . "\n\n";
4676 + }
4677 +
4678 + return trim($content);
4679 +}
4680 +
4681 +
4682 +private function find_relevant_products_pinecone($user_embedding) {
4683 + //error_log('Starting Pinecone product search...');
4684 +
4685 + $options = get_option('mxchat_pinecone_addon_options', array());
4686 + $api_key = $options['mxchat_pinecone_api_key'] ?? '';
4687 + $host = $options['mxchat_pinecone_host'] ?? '';
4688 +
4689 + if (empty($host) || empty($api_key)) {
4690 + //error_log('Pinecone credentials not properly configured for product search');
4691 + return '';
4692 + }
4693 +
4694 + $similarity_threshold = 0.85;
4695 + $api_endpoint = "https://{$host}/query";
4696 +
4697 + $request_body = array(
4698 + 'vector' => $user_embedding,
4699 + 'topK' => 5,
4700 + 'includeMetadata' => true,
4701 + 'includeValues' => true,
4702 + 'filter' => array(
4703 + 'type' => 'product'
4704 + )
4705 + );
4706 +
4707 + //error_log('Sending request to Pinecone with body: ' . wp_json_encode($request_body));
4708 +
4709 + $response = wp_remote_post($api_endpoint, array(
4710 + 'headers' => array(
4711 + 'Api-Key' => $api_key,
4712 + 'accept' => 'application/json',
4713 + 'content-type' => 'application/json'
4714 + ),
4715 + 'body' => wp_json_encode($request_body),
4716 + 'timeout' => 30
4717 + ));
4718 +
4719 + if (is_wp_error($response)) {
4720 + //error_log('Pinecone product query error: ' . $response->get_error_message());
4721 + return '';
4722 + }
4723 +
4724 + $response_code = wp_remote_retrieve_response_code($response);
4725 + //error_log('Pinecone response code: ' . $response_code);
4726 +
4727 + if ($response_code !== 200) {
4728 + //error_log('Pinecone API error during product search: ' . wp_remote_retrieve_body($response));
4729 + return '';
4730 + }
4731 +
4732 + $results = json_decode(wp_remote_retrieve_body($response), true);
4733 + //error_log('Pinecone raw response: ' . wp_remote_retrieve_body($response));
4734 +
4735 + if (empty($results['matches'])) {
4736 + //error_log('No matches found in Pinecone response');
4737 + return '';
4738 + }
4739 +
4740 + $content = '';
4741 + foreach ($results['matches'] as $match) {
4742 + if ($match['score'] < $similarity_threshold) {
4743 + //error_log("Match below threshold: " . $match['score']);
4744 + continue;
4745 + }
4746 +
4747 + if (!empty($match['metadata']['text'])) {
4748 + $content .= $match['metadata']['text'];
4749 + if (!empty($match['metadata']['source_url'])) {
4750 + $content .= "\n\nFor more details, check out this product: " . esc_url($match['metadata']['source_url']);
4751 + }
4752 + $content .= "\n\n";
4753 + }
4754 + }
4755 +
4756 + return trim($content);
4757 +}
4758 +
4759 +
4760 +private function fetch_content_with_product_links($most_relevant_id) {
4761 + global $wpdb;
4762 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
4763 +
4764 + // Fetch the article content and associated product URL
4765 + $query = $wpdb->prepare("SELECT article_content, source_url FROM {$system_prompt_table} WHERE id = %d", $most_relevant_id);
4766 + $result = $wpdb->get_row($query);
4767 +
4768 + if ($result) {
4769 + // Append the product link to the content if available
4770 + $content = $result->article_content;
4771 + if (!empty($result->source_url)) {
4772 + $content .= "\n\nFor more details, check out this product: " . esc_url($result->source_url);
4773 + }
4774 + return $content;
4775 + }
4776 +
4777 + return null;
4778 +}
4779 +
4780 +/**
4781 + * Get system instructions for a specific bot or default
4782 + * Checks for multi-bot add-on and uses bot-specific instructions if available
4783 + */
4784 +private function get_system_instructions($bot_id = 'default') {
4785 + // Check if multi-bot add-on is active
4786 + if (class_exists('MxChat_Multi_Bot_Core_Manager') && $bot_id !== 'default') {
4787 + // Get bot-specific options from multi-bot add-on
4788 + $bot_options = apply_filters('mxchat_get_bot_options', array(), $bot_id);
4789 +
4790 + // If bot has custom system instructions, use those
4791 + if (!empty($bot_options['system_prompt_instructions'])) {
4792 + return $bot_options['system_prompt_instructions'];
4793 + }
4794 + }
4795 +
4796 + // Fall back to default system instructions
4797 + return isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
4798 +}
4799 +/**
4800 + * Get the current bot ID from session or request context
4801 + */
4802 +private function get_current_bot_id($session_id = '') {
4803 + // First, check if bot_id is passed in the current request
4804 + if (isset($_POST['bot_id']) && !empty($_POST['bot_id'])) {
4805 + return sanitize_key($_POST['bot_id']);
4806 + }
4807 +
4808 + // If not in POST, try to get it from session data
4809 + if (!empty($session_id)) {
4810 + $bot_id = get_option("mxchat_session_bot_{$session_id}", '');
4811 + if (!empty($bot_id)) {
4812 + return $bot_id;
4813 + }
4814 + }
4815 +
4816 + // Fall back to default
4817 + return 'default';
4818 +}
4819 +private function mxchat_generate_response($relevant_content, $api_key, $xai_api_key, $claude_api_key, $deepseek_api_key, $gemini_api_key, $openrouter_api_key, $conversation_history, $streaming = false, $session_id = '', $testing_data = null, $selected_model = 'gpt-4o') {
4820 + try {
4821 + if (!$relevant_content) {
4822 + $error_response = [
4823 + 'error' => esc_html__("I couldn't find relevant information on that topic.", 'mxchat'),
4824 + 'error_code' => 'no_relevant_content'
4825 + ];
4826 +
4827 + if ($testing_data !== null) {
4828 + $error_response['testing_data'] = $testing_data;
4829 + }
4830 +
4831 + return $error_response;
4832 + }
4833 +
4834 + if (!is_array($conversation_history)) {
4835 + $conversation_history = array();
4836 + }
4837 +
4838 + // Check if this is an OpenRouter model
4839 + if ($selected_model === 'openrouter') {
4840 + // Get the actual OpenRouter model from options
4841 + $openrouter_selected_model = $this->options['openrouter_selected_model'] ?? '';
4842 +
4843 + if (empty($openrouter_selected_model)) {
4844 + $error_response = [
4845 + 'error' => esc_html__('No OpenRouter model selected. Please select a model in settings.', 'mxchat'),
4846 + 'error_code' => 'no_openrouter_model_selected'
4847 + ];
4848 + if ($testing_data !== null) {
4849 + $error_response['testing_data'] = $testing_data;
4850 + }
4851 + return $error_response;
4852 + }
4853 +
4854 + if (empty($openrouter_api_key)) {
4855 + $error_response = [
4856 + 'error' => esc_html__('OpenRouter API key is not configured', 'mxchat'),
4857 + 'error_code' => 'missing_openrouter_api_key'
4858 + ];
4859 + if ($testing_data !== null) {
4860 + $error_response['testing_data'] = $testing_data;
4861 + }
4862 + return $error_response;
4863 + }
4864 +
4865 + if ($streaming) {
4866 + return $this->mxchat_generate_response_openrouter_stream(
4867 + $openrouter_selected_model,
4868 + $openrouter_api_key,
4869 + $conversation_history,
4870 + $relevant_content,
4871 + $session_id,
4872 + $testing_data
4873 + );
4874 + } else {
4875 + $response = $this->mxchat_generate_response_openrouter(
4876 + $openrouter_selected_model,
4877 + $openrouter_api_key,
4878 + $conversation_history,
4879 + $relevant_content
4880 + );
4881 + }
4882 +
4883 + if (is_array($response) && isset($response['error'])) {
4884 + if ($testing_data !== null) {
4885 + $response['testing_data'] = $testing_data;
4886 + }
4887 + return $response;
4888 + }
4889 +
4890 + return $response;
4891 + }
4892 +
4893 + // Extract model prefix to determine the provider
4894 + $model_parts = explode('-', $selected_model);
4895 + $provider = strtolower($model_parts[0]);
4896 +
4897 + // Handle model selection based on provider prefix
4898 + switch ($provider) {
4899 + case 'gemini':
4900 + if (empty($gemini_api_key)) {
4901 + $error_response = [
4902 + 'error' => esc_html__('Google Gemini API key is not configured', 'mxchat'),
4903 + 'error_code' => 'missing_gemini_api_key'
4904 + ];
4905 + if ($testing_data !== null) {
4906 + $error_response['testing_data'] = $testing_data;
4907 + }
4908 + return $error_response;
4909 + }
4910 + $response = $this->mxchat_generate_response_gemini(
4911 + $selected_model,
4912 + $gemini_api_key,
4913 + $conversation_history,
4914 + $relevant_content
4915 + );
4916 + break;
4917 +
4918 + case 'claude':
4919 + if (empty($claude_api_key)) {
4920 + $error_response = [
4921 + 'error' => esc_html__('Claude API key is not configured', 'mxchat'),
4922 + 'error_code' => 'missing_claude_api_key'
4923 + ];
4924 + if ($testing_data !== null) {
4925 + $error_response['testing_data'] = $testing_data;
4926 + }
4927 + return $error_response;
4928 + }
4929 + if ($streaming) {
4930 + return $this->mxchat_generate_response_claude_stream(
4931 + $selected_model,
4932 + $claude_api_key,
4933 + $conversation_history,
4934 + $relevant_content,
4935 + $session_id,
4936 + $testing_data
4937 + );
4938 + } else {
4939 + $response = $this->mxchat_generate_response_claude(
4940 + $selected_model,
4941 + $claude_api_key,
4942 + $conversation_history,
4943 + $relevant_content
4944 + );
4945 + }
4946 + break;
4947 +
4948 + case 'grok':
4949 + if (empty($xai_api_key)) {
4950 + $error_response = [
4951 + 'error' => esc_html__('X.AI API key is not configured', 'mxchat'),
4952 + 'error_code' => 'missing_xai_api_key'
4953 + ];
4954 + if ($testing_data !== null) {
4955 + $error_response['testing_data'] = $testing_data;
4956 + }
4957 + return $error_response;
4958 + }
4959 + if ($streaming) {
4960 + return $this->mxchat_generate_response_xai_stream(
4961 + $selected_model,
4962 + $xai_api_key,
4963 + $conversation_history,
4964 + $relevant_content,
4965 + $session_id,
4966 + $testing_data
4967 + );
4968 + } else {
4969 + $response = $this->mxchat_generate_response_xai(
4970 + $selected_model,
4971 + $xai_api_key,
4972 + $conversation_history,
4973 + $relevant_content
4974 + );
4975 + }
4976 + break;
4977 +
4978 + case 'deepseek':
4979 + if (empty($deepseek_api_key)) {
4980 + $error_response = [
4981 + 'error' => esc_html__('DeepSeek API key is not configured', 'mxchat'),
4982 + 'error_code' => 'missing_deepseek_api_key'
4983 + ];
4984 + if ($testing_data !== null) {
4985 + $error_response['testing_data'] = $testing_data;
4986 + }
4987 + return $error_response;
4988 + }
4989 + if ($streaming) {
4990 + return $this->mxchat_generate_response_deepseek_stream(
4991 + $selected_model,
4992 + $deepseek_api_key,
4993 + $conversation_history,
4994 + $relevant_content,
4995 + $session_id,
4996 + $testing_data
4997 + );
4998 + } else {
4999 + $response = $this->mxchat_generate_response_deepseek(
5000 + $selected_model,
5001 + $deepseek_api_key,
5002 + $conversation_history,
5003 + $relevant_content
5004 + );
5005 + }
5006 + break;
5007 +
5008 + case 'gpt':
5009 + case 'o1':
5010 + if (empty($api_key)) {
5011 + $error_response = [
5012 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
5013 + 'error_code' => 'missing_openai_api_key'
5014 + ];
5015 + if ($testing_data !== null) {
5016 + $error_response['testing_data'] = $testing_data;
5017 + }
5018 + return $error_response;
5019 + }
5020 + if ($streaming) {
5021 + return $this->mxchat_generate_response_openai_stream(
5022 + $selected_model,
5023 + $api_key,
5024 + $conversation_history,
5025 + $relevant_content,
5026 + $session_id,
5027 + $testing_data
5028 + );
5029 + } else {
5030 + $response = $this->mxchat_generate_response_openai(
5031 + $selected_model,
5032 + $api_key,
5033 + $conversation_history,
5034 + $relevant_content
5035 + );
5036 + }
5037 + break;
5038 +
5039 + default:
5040 + if (empty($api_key)) {
5041 + $error_response = [
5042 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
5043 + 'error_code' => 'missing_openai_api_key'
5044 + ];
5045 + if ($testing_data !== null) {
5046 + $error_response['testing_data'] = $testing_data;
5047 + }
5048 + return $error_response;
5049 + }
5050 + if ($streaming) {
5051 + return $this->mxchat_generate_response_openai_stream(
5052 + $selected_model,
5053 + $api_key,
5054 + $conversation_history,
5055 + $relevant_content,
5056 + $session_id,
5057 + $testing_data
5058 + );
5059 + } else {
5060 + $response = $this->mxchat_generate_response_openai(
5061 + $selected_model,
5062 + $api_key,
5063 + $conversation_history,
5064 + $relevant_content
5065 + );
5066 + }
5067 + break;
5068 + }
5069 +
5070 + if (is_array($response) && isset($response['error'])) {
5071 + if ($testing_data !== null) {
5072 + $response['testing_data'] = $testing_data;
5073 + }
5074 + return $response;
5075 + }
5076 +
5077 + return $response;
5078 +
5079 + } catch (Exception $e) {
5080 + $error_response = [
5081 + 'error' => sprintf(esc_html__('An error occurred: %s', 'mxchat'), esc_html($e->getMessage())),
5082 + 'error_code' => 'system_exception',
5083 + 'exception_details' => $e->getMessage()
5084 + ];
5085 +
5086 + if ($testing_data !== null) {
5087 + $error_response['testing_data'] = $testing_data;
5088 + }
5089 +
5090 + return $error_response;
5091 + }
5092 +}
5093 +private function mxchat_generate_response_openrouter_stream($selected_model, $openrouter_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
5094 + try {
5095 + $bot_id = $this->get_current_bot_id($session_id);
5096 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
5097 +
5098 + if (!is_array($conversation_history)) {
5099 + $conversation_history = array();
5100 + }
5101 +
5102 + $formatted_conversation = array();
5103 +
5104 + $formatted_conversation[] = array(
5105 + 'role' => 'system',
5106 + 'content' => $system_prompt_instructions . " " . $relevant_content
5107 + );
5108 +
5109 + foreach ($conversation_history as $message) {
5110 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
5111 + $role = $message['role'];
5112 + if ($role === 'bot' || $role === 'agent') {
5113 + $role = 'assistant';
5114 + }
5115 + if (!in_array($role, ['system', 'assistant', 'user'])) {
5116 + $role = 'user';
5117 + }
5118 + $formatted_conversation[] = array(
5119 + 'role' => $role,
5120 + 'content' => $message['content']
5121 + );
5122 + }
5123 + }
5124 +
5125 + if (headers_sent() || !function_exists('curl_init')) {
5126 + $regular_response = $this->mxchat_generate_response_openrouter(
5127 + $selected_model,
5128 + $openrouter_api_key,
5129 + $conversation_history,
5130 + $relevant_content
5131 + );
5132 +
5133 + // Save bot response to transcript
5134 + if (!empty($regular_response) && !empty($session_id)) {
5135 + $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
5136 + }
5137 +
5138 + $response_data = [
5139 + 'text' => $regular_response,
5140 + 'html' => '',
5141 + 'session_id' => $session_id
5142 + ];
5143 +
5144 + if ($testing_data !== null) {
5145 + $response_data['testing_data'] = $testing_data;
5146 + }
5147 +
5148 + header('Content-Type: application/json');
5149 + echo json_encode($response_data);
5150 + return true;
5151 + }
5152 +
5153 + $body = json_encode([
5154 + 'model' => $selected_model,
5155 + 'messages' => $formatted_conversation,
5156 + 'temperature' => 1,
5157 + 'stream' => true
5158 + ]);
5159 +
5160 + $ch = curl_init();
5161 + curl_setopt($ch, CURLOPT_URL, 'https://openrouter.ai/api/v1/chat/completions');
5162 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
5163 + curl_setopt($ch, CURLOPT_POST, true);
5164 + curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
5165 + curl_setopt($ch, CURLOPT_HTTPHEADER, array(
5166 + 'Content-Type: application/json',
5167 + 'Authorization: Bearer ' . $openrouter_api_key,
5168 + 'HTTP-Referer: ' . home_url(),
5169 + 'X-Title: ' . get_bloginfo('name')
5170 + ));
5171 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
5172 + curl_setopt($ch, CURLOPT_TIMEOUT, 60);
5173 +
5174 + $full_response = '';
5175 + $stream_started = false;
5176 + $buffer = '';
5177 +
5178 + curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, $testing_data) {
5179 + if (!$stream_started && $testing_data !== null) {
5180 + echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
5181 + flush();
5182 + $stream_started = true;
5183 + }
5184 +
5185 + $buffer .= $data;
5186 + $lines = explode("\n", $buffer);
5187 + $buffer = array_pop($lines);
5188 +
5189 + foreach ($lines as $line) {
5190 + if (trim($line) === '') {
5191 + continue;
5192 + }
5193 +
5194 + if (strpos($line, 'data: ') !== 0) {
5195 + continue;
5196 + }
5197 +
5198 + $json_str = substr($line, 6);
5199 +
5200 + if (trim($json_str) === '[DONE]') {
5201 + echo "data: [DONE]\n\n";
5202 + flush();
5203 + continue;
5204 + }
5205 +
5206 + $json = json_decode(trim($json_str), true);
5207 + if ($json && isset($json['choices'][0]['delta']['content'])) {
5208 + $content = $json['choices'][0]['delta']['content'];
5209 + $full_response .= $content;
5210 +
5211 + echo "data: " . json_encode(['content' => $content]) . "\n\n";
5212 + flush();
5213 + }
5214 + }
5215 +
5216 + return strlen($data);
5217 + });
5218 +
5219 + $response = curl_exec($ch);
5220 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
5221 +
5222 + if (curl_errno($ch) || $http_code !== 200) {
5223 + curl_close($ch);
5224 +
5225 + $regular_response = $this->mxchat_generate_response_openrouter(
5226 + $selected_model,
5227 + $openrouter_api_key,
5228 + $conversation_history,
5229 + $relevant_content
5230 + );
5231 +
5232 + $response_data = [
5233 + 'text' => $regular_response,
5234 + 'html' => '',
5235 + 'session_id' => $session_id
5236 + ];
5237 +
5238 + if ($testing_data !== null) {
5239 + $response_data['testing_data'] = $testing_data;
5240 + }
5241 +
5242 + header('Content-Type: application/json');
5243 + echo json_encode($response_data);
5244 + return true;
5245 + }
5246 +
5247 + curl_close($ch);
5248 +
5249 + if (!empty($full_response) && !empty($session_id)) {
5250 + // Prepare RAG context for streaming response
5251 + $rag_context_for_storage = null;
5252 + if ($this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches'])) {
5253 + $rag_context_for_storage = [
5254 + 'top_matches' => $this->last_similarity_analysis['top_matches'],
5255 + 'approved_urls' => $this->current_valid_urls ?? [],
5256 + 'similarity_threshold' => $this->last_similarity_analysis['threshold_used'] ?? 0.35,
5257 + 'knowledge_base_type' => $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database',
5258 + 'total_documents_checked' => $this->last_similarity_analysis['total_checked'] ?? 0
5259 + ];
5260 + }
5261 + $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
5262 + }
5263 +
5264 + return true;
5265 +
5266 + } catch (Exception $e) {
5267 + $regular_response = $this->mxchat_generate_response_openrouter(
5268 + $selected_model,
5269 + $openrouter_api_key,
5270 + $conversation_history,
5271 + $relevant_content
5272 + );
5273 +
5274 + $response_data = [
5275 + 'text' => $regular_response,
5276 + 'html' => '',
5277 + 'session_id' => $session_id
5278 + ];
5279 +
5280 + if ($testing_data !== null) {
5281 + $response_data['testing_data'] = $testing_data;
5282 + }
5283 +
5284 + header('Content-Type: application/json');
5285 + echo json_encode($response_data);
5286 + return true;
5287 + }
5288 +}
5289 +private function mxchat_generate_response_openai_stream($selected_model, $api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
5290 + try {
5291 + $bot_id = $this->get_current_bot_id($session_id);
5292 +
5293 + // Get system prompt instructions using centralized function
5294 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
5295 +
5296 + // Ensure conversation_history is an array
5297 + if (!is_array($conversation_history)) {
5298 + $conversation_history = array();
5299 + }
5300 +
5301 + // Format conversation history for OpenAI
5302 + $formatted_conversation = array();
5303 +
5304 + $formatted_conversation[] = array(
5305 + 'role' => 'system',
5306 + 'content' => $system_prompt_instructions . " " . $relevant_content
5307 + );
5308 +
5309 + foreach ($conversation_history as $message) {
5310 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
5311 + $role = $message['role'];
5312 + if ($role === 'bot' || $role === 'agent') {
5313 + $role = 'assistant';
5314 + }
5315 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
5316 + $role = 'user';
5317 + }
5318 + $formatted_conversation[] = array(
5319 + 'role' => $role,
5320 + 'content' => $message['content']
5321 + );
5322 + }
5323 + }
5324 +
5325 + // Check if we can actually stream
5326 + if (headers_sent() || !function_exists('curl_init')) {
5327 + // Fallback to regular response with testing data
5328 + $regular_response = $this->mxchat_generate_response_openai(
5329 + $selected_model,
5330 + $api_key,
5331 + $conversation_history,
5332 + $relevant_content
5333 + );
5334 +
5335 + // Save bot response to transcript
5336 + if (!empty($regular_response) && !empty($session_id)) {
5337 + $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
5338 + }
5339 +
5340 + $response_data = [
5341 + 'text' => $regular_response,
5342 + 'html' => '',
5343 + 'session_id' => $session_id
5344 + ];
5345 +
5346 + if ($testing_data !== null) {
5347 + $response_data['testing_data'] = $testing_data;
5348 + }
5349 +
5350 + header('Content-Type: application/json');
5351 + echo json_encode($response_data);
5352 + return true;
5353 + }
5354 +
5355 + // Check if this is a GPT-5 model (supports reasoning_effort parameter)
5356 + $is_gpt5_model = (
5357 + strpos($selected_model, 'gpt-5') === 0 ||
5358 + $selected_model === 'gpt-5.2' ||
5359 + $selected_model === 'gpt-5.1-2025-11-13' ||
5360 + $selected_model === 'gpt-5' ||
5361 + $selected_model === 'gpt-5-mini' ||
5362 + $selected_model === 'gpt-5-nano'
5363 + );
5364 +
5365 + // Build request body with optimal settings for fast streaming
5366 + $request_body = [
5367 + 'model' => $selected_model,
5368 + 'messages' => $formatted_conversation,
5369 + 'temperature' => 1,
5370 + 'stream' => true
5371 + ];
5372 +
5373 + // Add reasoning_effort only for GPT-5 models (not GPT-5.2 which doesn't support it)
5374 + if ($is_gpt5_model && $selected_model !== 'gpt-5.2') {
5375 + // GPT-5.1 uses 'low' instead of 'minimal'
5376 + if ($selected_model === 'gpt-5.1-2025-11-13') {
5377 + $request_body['reasoning_effort'] = 'low';
5378 + } else {
5379 + $request_body['reasoning_effort'] = 'minimal'; // For other GPT-5 models
5380 + }
5381 + }
5382 +
5383 + $body = json_encode($request_body);
5384 +
5385 + // Use cURL for streaming support
5386 + $ch = curl_init();
5387 + curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
5388 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
5389 + curl_setopt($ch, CURLOPT_POST, true);
5390 + curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
5391 + curl_setopt($ch, CURLOPT_HTTPHEADER, array(
5392 + 'Content-Type: application/json',
5393 + 'Authorization: Bearer ' . $api_key
5394 + ));
5395 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
5396 + curl_setopt($ch, CURLOPT_TIMEOUT, 60);
5397 +
5398 + $full_response = ''; // Accumulate full response for saving
5399 + $stream_started = false;
5400 + $buffer = ''; // CRITICAL: Add persistent buffer for incomplete chunks
5401 +
5402 + // Buffer control for real-time streaming
5403 + curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, $testing_data) {
5404 + // Send testing data as the first event if available
5405 + if (!$stream_started && $testing_data !== null) {
5406 + echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
5407 + flush();
5408 + $stream_started = true;
5409 + }
5410 +
5411 + // CRITICAL FIX: Append new data to buffer
5412 + $buffer .= $data;
5413 +
5414 + // Process complete lines only
5415 + $lines = explode("\n", $buffer);
5416 +
5417 + // CRITICAL FIX: Keep the last incomplete line in the buffer
5418 + // The last element might be incomplete, so keep it in buffer
5419 + $buffer = array_pop($lines);
5420 +
5421 + foreach ($lines as $line) {
5422 + // Skip empty lines
5423 + if (trim($line) === '') {
5424 + continue;
5425 + }
5426 +
5427 + // Only process lines that start with "data: "
5428 + if (strpos($line, 'data: ') !== 0) {
5429 + continue;
5430 + }
5431 +
5432 + $json_str = substr($line, 6); // Remove 'data: ' prefix
5433 +
5434 + if (trim($json_str) === '[DONE]') {
5435 + echo "data: [DONE]\n\n";
5436 + flush();
5437 + continue;
5438 + }
5439 +
5440 + // Try to decode JSON
5441 + $json = json_decode(trim($json_str), true);
5442 + if ($json && isset($json['choices'][0]['delta']['content'])) {
5443 + $content = $json['choices'][0]['delta']['content'];
5444 + $full_response .= $content; // Accumulate the full response
5445 +
5446 + // Send as SSE format
5447 + echo "data: " . json_encode(['content' => $content]) . "\n\n";
5448 + flush();
5449 + }
5450 + }
5451 +
5452 + return strlen($data);
5453 + });
5454 +
5455 + $response = curl_exec($ch);
5456 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
5457 +
5458 + if (curl_errno($ch) || $http_code !== 200) {
5459 + $curl_error = curl_error($ch);
5460 + curl_close($ch);
5461 +
5462 + // Fallback to regular response
5463 + $regular_response = $this->mxchat_generate_response_openai(
5464 + $selected_model,
5465 + $api_key,
5466 + $conversation_history,
5467 + $relevant_content
5468 + );
5469 +
5470 + // FIXED: Check if regular response returned an error
5471 + if (is_array($regular_response) && isset($regular_response['error'])) {
5472 + // Send error in SSE format since we're in streaming mode
5473 + echo "data: " . json_encode([
5474 + 'error' => true,
5475 + 'error_message' => $regular_response['error'],
5476 + 'error_code' => $regular_response['error_code'] ?? 'api_error',
5477 + 'text' => $regular_response['error'],
5478 + 'message' => $regular_response['error']
5479 + ]) . "\n\n";
5480 + echo "data: [DONE]\n\n";
5481 + flush();
5482 + return true;
5483 + }
5484 +
5485 + $response_data = [
5486 + 'text' => $regular_response,
5487 + 'html' => '',
5488 + 'session_id' => $session_id
5489 + ];
5490 +
5491 + if ($testing_data !== null) {
5492 + $response_data['testing_data'] = $testing_data;
5493 + }
5494 +
5495 + header('Content-Type: application/json');
5496 + echo json_encode($response_data);
5497 + return true;
5498 + }
5499 +
5500 + curl_close($ch);
5501 +
5502 + // Save the complete response to maintain chat persistence
5503 + if (!empty($full_response) && !empty($session_id)) {
5504 + // Prepare RAG context for streaming response
5505 + $rag_context_for_storage = null;
5506 + if ($this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches'])) {
5507 + $rag_context_for_storage = [
5508 + 'top_matches' => $this->last_similarity_analysis['top_matches'],
5509 + 'approved_urls' => $this->current_valid_urls ?? [],
5510 + 'similarity_threshold' => $this->last_similarity_analysis['threshold_used'] ?? 0.35,
5511 + 'knowledge_base_type' => $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database',
5512 + 'total_documents_checked' => $this->last_similarity_analysis['total_checked'] ?? 0
5513 + ];
5514 + }
5515 + $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
5516 + }
5517 +
5518 + return true; // Indicate streaming completed successfully
5519 +
5520 + } catch (Exception $e) {
5521 + // Fallback to regular response
5522 + $regular_response = $this->mxchat_generate_response_openai(
5523 + $selected_model,
5524 + $api_key,
5525 + $conversation_history,
5526 + $relevant_content
5527 + );
5528 +
5529 + // FIXED: Check if regular response returned an error
5530 + if (is_array($regular_response) && isset($regular_response['error'])) {
5531 + // Send error in SSE format since we're in streaming mode
5532 + echo "data: " . json_encode([
5533 + 'error' => true,
5534 + 'error_message' => $regular_response['error'],
5535 + 'error_code' => $regular_response['error_code'] ?? 'api_error',
5536 + 'text' => $regular_response['error'],
5537 + 'message' => $regular_response['error']
5538 + ]) . "\n\n";
5539 + echo "data: [DONE]\n\n";
5540 + flush();
5541 + return true;
5542 + }
5543 +
5544 + $response_data = [
5545 + 'text' => $regular_response,
5546 + 'html' => '',
5547 + 'session_id' => $session_id
5548 + ];
5549 +
5550 + if ($testing_data !== null) {
5551 + $response_data['testing_data'] = $testing_data;
5552 + }
5553 +
5554 + header('Content-Type: application/json');
5555 + echo json_encode($response_data);
5556 + return true;
5557 + }
5558 +}
5559 +private function mxchat_generate_response_claude_stream($selected_model, $claude_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
5560 + try {
5561 + // Get bot ID from session or request
5562 + $bot_id = $this->get_current_bot_id($session_id);
5563 +
5564 + // Get system prompt instructions using centralized function
5565 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
5566 + // Ensure conversation_history is an array
5567 + if (!is_array($conversation_history)) {
5568 + $conversation_history = array();
5569 + }
5570 +
5571 + // Clean and validate conversation history
5572 + foreach ($conversation_history as &$message) {
5573 + // Convert bot and agent roles to assistant
5574 + if ($message['role'] === 'bot' || $message['role'] === 'agent') {
5575 + $message['role'] = 'assistant';
5576 + }
5577 +
5578 + // Remove unsupported roles - Claude only supports 'assistant' and 'user'
5579 + if (!in_array($message['role'], ['assistant', 'user'])) {
5580 + $message['role'] = 'user';
5581 + }
5582 +
5583 + // Ensure content field exists
5584 + if (!isset($message['content']) || empty($message['content'])) {
5585 + $message['content'] = '';
5586 + }
5587 +
5588 + // Remove any unsupported fields
5589 + $message = array_intersect_key($message, array_flip(['role', 'content']));
5590 + }
5591 +
5592 + // Add relevant content as the latest user message
5593 + $conversation_history[] = [
5594 + 'role' => 'user',
5595 + 'content' => $relevant_content
5596 + ];
5597 +
5598 + // Prepare the request body with stream: true
5599 + $body = json_encode([
5600 + 'model' => $selected_model,
5601 + 'messages' => $conversation_history,
5602 + 'max_tokens' => 1000,
5603 + 'temperature' => 0.8,
5604 + 'system' => $system_prompt_instructions,
5605 + 'stream' => true
5606 + ]);
5607 +
5608 + // Check if we can actually stream (headers not sent, etc.)
5609 + if (headers_sent() || !function_exists('curl_init')) {
5610 + // Fallback to regular response with testing data
5611 + //error_log("MxChat: Streaming not possible, falling back to regular response");
5612 + $regular_response = $this->mxchat_generate_response_claude(
5613 + $selected_model,
5614 + $claude_api_key,
5615 + array_slice($conversation_history, 0, -1), // Remove the added content
5616 + $relevant_content
5617 + );
5618 +
5619 + // Save bot response to transcript
5620 + if (!empty($regular_response) && !empty($session_id)) {
5621 + $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
5622 + }
5623 +
5624 + // Return as JSON with testing data
5625 + $response_data = [
5626 + 'text' => $regular_response,
5627 + 'html' => '',
5628 + 'session_id' => $session_id
5629 + ];
5630 +
5631 + if ($testing_data !== null) {
5632 + $response_data['testing_data'] = $testing_data;
5633 + //error_log("MxChat Testing: Added testing data to Claude fallback response");
5634 + }
5635 +
5636 + // Clear any streaming headers and send JSON
5637 + if (headers_sent() === false) {
5638 + header('Content-Type: application/json');
5639 + }
5640 + echo json_encode($response_data);
5641 + return true; // Indicate we handled the response
5642 + }
5643 +
5644 + // Use cURL for streaming support
5645 + $ch = curl_init();
5646 + curl_setopt($ch, CURLOPT_URL, 'https://api.anthropic.com/v1/messages');
5647 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
5648 + curl_setopt($ch, CURLOPT_POST, true);
5649 + curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
5650 + curl_setopt($ch, CURLOPT_HTTPHEADER, array(
5651 + 'Content-Type: application/json',
5652 + 'x-api-key: ' . $claude_api_key,
5653 + 'anthropic-version: 2023-06-01'
5654 + ));
5655 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
5656 + curl_setopt($ch, CURLOPT_TIMEOUT, 60);
5657 +
5658 + $full_response = ''; // Accumulate full response for saving
5659 + $stream_started = false;
5660 + $buffer = ''; // CRITICAL: Add persistent buffer for incomplete chunks
5661 +
5662 + // Buffer control for real-time streaming
5663 + curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, $testing_data) {
5664 + // Send testing data as the first event if available
5665 + if (!$stream_started && $testing_data !== null) {
5666 + echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
5667 + flush();
5668 + $stream_started = true;
5669 + //error_log("MxChat Testing: Sent testing data in Claude stream");
5670 + }
5671 +
5672 + // CRITICAL FIX: Append new data to buffer
5673 + $buffer .= $data;
5674 +
5675 + // Process complete lines only
5676 + $lines = explode("\n", $buffer);
5677 +
5678 + // CRITICAL FIX: Keep the last incomplete line in the buffer
5679 + // The last element might be incomplete, so keep it in buffer
5680 + $buffer = array_pop($lines);
5681 +
5682 + foreach ($lines as $line) {
5683 + if (trim($line) === '') {
5684 + continue;
5685 + }
5686 +
5687 + // Claude uses event: and data: format
5688 + if (strpos($line, 'event: ') === 0) {
5689 + // Store the event type for the next data line
5690 + continue;
5691 + }
5692 +
5693 + if (strpos($line, 'data: ') === 0) {
5694 + $json_str = substr($line, 6); // Remove 'data: ' prefix
5695 +
5696 + $json = json_decode(trim($json_str), true);
5697 + if (json_last_error() !== JSON_ERROR_NONE) {
5698 + continue;
5699 + }
5700 +
5701 + // Handle different event types
5702 + if (isset($json['type'])) {
5703 + switch ($json['type']) {
5704 + case 'content_block_delta':
5705 + if (isset($json['delta']['text'])) {
5706 + $content = $json['delta']['text'];
5707 + $full_response .= $content; // Accumulate
5708 + // Send as SSE format compatible with your frontend
5709 + echo "data: " . json_encode(['content' => $content]) . "\n\n";
5710 + flush();
5711 + }
5712 + break;
5713 +
5714 + case 'message_stop':
5715 + echo "data: [DONE]\n\n";
5716 + flush();
5717 + break;
5718 +
5719 + case 'error':
5720 + echo "data: " . json_encode(['error' => $json['error']['message'] ?? 'Unknown error']) . "\n\n";
5721 + flush();
5722 + break;
5723 + }
5724 + }
5725 + }
5726 + }
5727 +
5728 + return strlen($data);
5729 + });
5730 +
5731 + $response = curl_exec($ch);
5732 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
5733 +
5734 + if (curl_errno($ch)) {
5735 + curl_close($ch);
5736 + throw new Exception('cURL Error: ' . curl_error($ch));
5737 + }
5738 +
5739 + curl_close($ch);
5740 +
5741 + if ($http_code !== 200) {
5742 + // Fallback to regular response
5743 + //error_log("MxChat: Claude streaming failed with HTTP $http_code, falling back");
5744 + $regular_response = $this->mxchat_generate_response_claude(
5745 + $selected_model,
5746 + $claude_api_key,
5747 + array_slice($conversation_history, 0, -1), // Remove the added content
5748 + $relevant_content
5749 + );
5750 +
5751 + // FIXED: Check if regular response returned an error
5752 + if (is_array($regular_response) && isset($regular_response['error'])) {
5753 + // Send error in SSE format since we're in streaming mode
5754 + echo "data: " . json_encode([
5755 + 'error' => true,
5756 + 'error_message' => $regular_response['error'],
5757 + 'error_code' => $regular_response['error_code'] ?? 'api_error',
5758 + 'text' => $regular_response['error'],
5759 + 'message' => $regular_response['error']
5760 + ]) . "\n\n";
5761 + echo "data: [DONE]\n\n";
5762 + flush();
5763 + return true;
5764 + }
5765 +
5766 + $response_data = [
5767 + 'text' => $regular_response,
5768 + 'html' => '',
5769 + 'session_id' => $session_id
5770 + ];
5771 +
5772 + if ($testing_data !== null) {
5773 + $response_data['testing_data'] = $testing_data;
5774 + //error_log("MxChat Testing: Added testing data to Claude error fallback");
5775 + }
5776 +
5777 + header('Content-Type: application/json');
5778 + echo json_encode($response_data);
5779 + return true;
5780 + }
5781 +
5782 + // Save the complete response to maintain chat persistence
5783 + if (!empty($full_response) && !empty($session_id)) {
5784 + // Prepare RAG context for streaming response
5785 + $rag_context_for_storage = null;
5786 + if ($this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches'])) {
5787 + $rag_context_for_storage = [
5788 + 'top_matches' => $this->last_similarity_analysis['top_matches'],
5789 + 'approved_urls' => $this->current_valid_urls ?? [],
5790 + 'similarity_threshold' => $this->last_similarity_analysis['threshold_used'] ?? 0.35,
5791 + 'knowledge_base_type' => $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database',
5792 + 'total_documents_checked' => $this->last_similarity_analysis['total_checked'] ?? 0
5793 + ];
5794 + }
5795 + $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
5796 + }
5797 +
5798 + return true; // Indicate streaming completed successfully
5799 +
5800 + } catch (Exception $e) {
5801 + //error_log("MxChat Claude streaming exception: " . $e->getMessage());
5802 +
5803 + // Fallback to regular response on exception
5804 + $regular_response = $this->mxchat_generate_response_claude(
5805 + $selected_model,
5806 + $claude_api_key,
5807 + $conversation_history,
5808 + $relevant_content
5809 + );
5810 +
5811 + // FIXED: Check if regular response returned an error
5812 + if (is_array($regular_response) && isset($regular_response['error'])) {
5813 + // Send error in SSE format since we're in streaming mode
5814 + echo "data: " . json_encode([
5815 + 'error' => true,
5816 + 'error_message' => $regular_response['error'],
5817 + 'error_code' => $regular_response['error_code'] ?? 'api_error',
5818 + 'text' => $regular_response['error'],
5819 + 'message' => $regular_response['error']
5820 + ]) . "\n\n";
5821 + echo "data: [DONE]\n\n";
5822 + flush();
5823 + return true;
5824 + }
5825 +
5826 + $response_data = [
5827 + 'text' => $regular_response,
5828 + 'html' => '',
5829 + 'session_id' => $session_id
5830 + ];
5831 +
5832 + if ($testing_data !== null) {
5833 + $response_data['testing_data'] = $testing_data;
5834 + //error_log("MxChat Testing: Added testing data to Claude exception fallback");
5835 + }
5836 +
5837 + header('Content-Type: application/json');
5838 + echo json_encode($response_data);
5839 + return true;
5840 + }
5841 +}
5842 +private function mxchat_generate_response_xai_stream($selected_model, $xai_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
5843 + try {
5844 + // Get bot ID from session or request
5845 + $bot_id = $this->get_current_bot_id($session_id);
5846 +
5847 + // Get system prompt instructions using centralized function
5848 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
5849 +
5850 + // Ensure conversation_history is an array
5851 + if (!is_array($conversation_history)) {
5852 + $conversation_history = array();
5853 + }
5854 +
5855 + // Format conversation history for X.AI (same as OpenAI format)
5856 + $formatted_conversation = array();
5857 +
5858 + $formatted_conversation[] = array(
5859 + 'role' => 'system',
5860 + 'content' => $system_prompt_instructions . " " . $relevant_content
5861 + );
5862 +
5863 + foreach ($conversation_history as $message) {
5864 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
5865 + $role = $message['role'];
5866 + if ($role === 'bot' || $role === 'agent') {
5867 + $role = 'assistant';
5868 + }
5869 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
5870 + $role = 'user';
5871 + }
5872 + $formatted_conversation[] = array(
5873 + 'role' => $role,
5874 + 'content' => $message['content']
5875 + );
5876 + }
5877 + }
5878 +
5879 + // Check if we can actually stream
5880 + if (headers_sent() || !function_exists('curl_init')) {
5881 + // Fallback to regular response with testing data
5882 + //error_log("MxChat: X.AI streaming not possible, falling back to regular response");
5883 + $regular_response = $this->mxchat_generate_response_xai(
5884 + $selected_model,
5885 + $xai_api_key,
5886 + $conversation_history,
5887 + $relevant_content
5888 + );
5889 +
5890 + // Save bot response to transcript
5891 + if (!empty($regular_response) && !empty($session_id)) {
5892 + $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
5893 + }
5894 +
5895 + $response_data = [
5896 + 'text' => $regular_response,
5897 + 'html' => '',
5898 + 'session_id' => $session_id
5899 + ];
5900 +
5901 + if ($testing_data !== null) {
5902 + $response_data['testing_data'] = $testing_data;
5903 + //error_log("MxChat Testing: Added testing data to X.AI fallback response");
5904 + }
5905 +
5906 + header('Content-Type: application/json');
5907 + echo json_encode($response_data);
5908 + return true;
5909 + }
5910 +
5911 + // Prepare the request body with stream: true
5912 + $body = json_encode([
5913 + 'model' => $selected_model,
5914 + 'messages' => $formatted_conversation,
5915 + 'temperature' => 0.8,
5916 + 'stream' => true
5917 + ]);
5918 +
5919 + // Use cURL for streaming support
5920 + $ch = curl_init();
5921 + curl_setopt($ch, CURLOPT_URL, 'https://api.x.ai/v1/chat/completions');
5922 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
5923 + curl_setopt($ch, CURLOPT_POST, true);
5924 + curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
5925 + curl_setopt($ch, CURLOPT_HTTPHEADER, array(
5926 + 'Content-Type: application/json',
5927 + 'Authorization: Bearer ' . $xai_api_key
5928 + ));
5929 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
5930 + curl_setopt($ch, CURLOPT_TIMEOUT, 60);
5931 +
5932 + $full_response = ''; // Accumulate full response for saving
5933 + $stream_started = false;
5934 + $buffer = ''; // CRITICAL: Add persistent buffer for incomplete chunks
5935 +
5936 + // Buffer control for real-time streaming
5937 + curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, $testing_data) {
5938 + // Send testing data as the first event if available
5939 + if (!$stream_started && $testing_data !== null) {
5940 + echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
5941 + flush();
5942 + $stream_started = true;
5943 + //error_log("MxChat Testing: Sent testing data in X.AI stream");
5944 + }
5945 +
5946 + // CRITICAL FIX: Append new data to buffer
5947 + $buffer .= $data;
5948 +
5949 + // Process complete lines only
5950 + $lines = explode("\n", $buffer);
5951 +
5952 + // CRITICAL FIX: Keep the last incomplete line in the buffer
5953 + // The last element might be incomplete, so keep it in buffer
5954 + $buffer = array_pop($lines);
5955 +
5956 + foreach ($lines as $line) {
5957 + // Skip empty lines
5958 + if (trim($line) === '') {
5959 + continue;
5960 + }
5961 +
5962 + // Only process lines that start with "data: "
5963 + if (strpos($line, 'data: ') !== 0) {
5964 + continue;
5965 + }
5966 +
5967 + $json_str = substr($line, 6); // Remove 'data: ' prefix
5968 +
5969 + if (trim($json_str) === '[DONE]') {
5970 + echo "data: [DONE]\n\n";
5971 + flush();
5972 + continue;
5973 + }
5974 +
5975 + // Try to decode JSON
5976 + $json = json_decode(trim($json_str), true);
5977 + if ($json && isset($json['choices'][0]['delta']['content'])) {
5978 + $content = $json['choices'][0]['delta']['content'];
5979 + $full_response .= $content; // Accumulate
5980 + // Send as SSE format
5981 + echo "data: " . json_encode(['content' => $content]) . "\n\n";
5982 + flush();
5983 + }
5984 + }
5985 +
5986 + return strlen($data);
5987 + });
5988 +
5989 + $response = curl_exec($ch);
5990 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
5991 +
5992 + if (curl_errno($ch) || $http_code !== 200) {
5993 + curl_close($ch);
5994 +
5995 + // Fallback to regular response
5996 + //error_log("MxChat: X.AI streaming failed, falling back");
5997 + $regular_response = $this->mxchat_generate_response_xai(
5998 + $selected_model,
5999 + $xai_api_key,
6000 + $conversation_history,
6001 + $relevant_content
6002 + );
6003 +
6004 + $response_data = [
6005 + 'text' => $regular_response,
6006 + 'html' => '',
6007 + 'session_id' => $session_id
6008 + ];
6009 +
6010 + if ($testing_data !== null) {
6011 + $response_data['testing_data'] = $testing_data;
6012 + //error_log("MxChat Testing: Added testing data to X.AI error fallback");
6013 + }
6014 +
6015 + header('Content-Type: application/json');
6016 + echo json_encode($response_data);
6017 + return true;
6018 + }
6019 +
6020 + curl_close($ch);
6021 +
6022 + // Save the complete response to maintain chat persistence
6023 + if (!empty($full_response) && !empty($session_id)) {
6024 + // Prepare RAG context for streaming response
6025 + $rag_context_for_storage = null;
6026 + if ($this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches'])) {
6027 + $rag_context_for_storage = [
6028 + 'top_matches' => $this->last_similarity_analysis['top_matches'],
6029 + 'approved_urls' => $this->current_valid_urls ?? [],
6030 + 'similarity_threshold' => $this->last_similarity_analysis['threshold_used'] ?? 0.35,
6031 + 'knowledge_base_type' => $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database',
6032 + 'total_documents_checked' => $this->last_similarity_analysis['total_checked'] ?? 0
6033 + ];
6034 + }
6035 + $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
6036 + }
6037 +
6038 + return true; // Indicate streaming completed successfully
6039 +
6040 + } catch (Exception $e) {
6041 + //error_log("MxChat X.AI streaming exception: " . $e->getMessage());
6042 +
6043 + // Fallback to regular response
6044 + $regular_response = $this->mxchat_generate_response_xai(
6045 + $selected_model,
6046 + $xai_api_key,
6047 + $conversation_history,
6048 + $relevant_content
6049 + );
6050 +
6051 + $response_data = [
6052 + 'text' => $regular_response,
6053 + 'html' => '',
6054 + 'session_id' => $session_id
6055 + ];
6056 +
6057 + if ($testing_data !== null) {
6058 + $response_data['testing_data'] = $testing_data;
6059 + //error_log("MxChat Testing: Added testing data to X.AI exception fallback");
6060 + }
6061 +
6062 + header('Content-Type: application/json');
6063 + echo json_encode($response_data);
6064 + return true;
6065 + }
6066 +}
6067 +private function mxchat_generate_response_deepseek_stream($selected_model, $deepseek_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
6068 + try {
6069 + // Get bot ID from session or request
6070 + $bot_id = $this->get_current_bot_id($session_id);
6071 +
6072 + // Get system prompt instructions using centralized function
6073 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6074 +
6075 + // Ensure conversation_history is an array
6076 + if (!is_array($conversation_history)) {
6077 + $conversation_history = array();
6078 + }
6079 +
6080 + // Format conversation history for DeepSeek
6081 + $formatted_conversation = array();
6082 +
6083 + $formatted_conversation[] = array(
6084 + 'role' => 'system',
6085 + 'content' => $system_prompt_instructions . " " . $relevant_content
6086 + );
6087 +
6088 + foreach ($conversation_history as $message) {
6089 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
6090 + $role = $message['role'];
6091 + if ($role === 'bot' || $role === 'agent') {
6092 + $role = 'assistant';
6093 + }
6094 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
6095 + $role = 'user';
6096 + }
6097 + $formatted_conversation[] = array(
6098 + 'role' => $role,
6099 + 'content' => $message['content']
6100 + );
6101 + }
6102 + }
6103 +
6104 + // Check if we can actually stream
6105 + if (headers_sent() || !function_exists('curl_init')) {
6106 + // Fallback to regular response with testing data
6107 + //error_log("MxChat: DeepSeek streaming not possible, falling back to regular response");
6108 + $regular_response = $this->mxchat_generate_response_deepseek(
6109 + $selected_model,
6110 + $deepseek_api_key,
6111 + $conversation_history,
6112 + $relevant_content
6113 + );
6114 +
6115 + // Save bot response to transcript
6116 + if (!empty($regular_response) && !empty($session_id)) {
6117 + $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
6118 + }
6119 +
6120 + $response_data = [
6121 + 'text' => $regular_response,
6122 + 'html' => '',
6123 + 'session_id' => $session_id
6124 + ];
6125 +
6126 + if ($testing_data !== null) {
6127 + $response_data['testing_data'] = $testing_data;
6128 + //error_log("MxChat Testing: Added testing data to DeepSeek fallback response");
6129 + }
6130 +
6131 + header('Content-Type: application/json');
6132 + echo json_encode($response_data);
6133 + return true;
6134 + }
6135 +
6136 + // Prepare the request body with stream: true
6137 + $body = json_encode([
6138 + 'model' => $selected_model,
6139 + 'messages' => $formatted_conversation,
6140 + 'temperature' => 0.8,
6141 + 'stream' => true
6142 + ]);
6143 +
6144 + // Use cURL for streaming support
6145 + $ch = curl_init();
6146 + curl_setopt($ch, CURLOPT_URL, 'https://api.deepseek.com/v1/chat/completions');
6147 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
6148 + curl_setopt($ch, CURLOPT_POST, true);
6149 + curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
6150 + curl_setopt($ch, CURLOPT_HTTPHEADER, array(
6151 + 'Content-Type: application/json',
6152 + 'Authorization: Bearer ' . $deepseek_api_key
6153 + ));
6154 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
6155 + curl_setopt($ch, CURLOPT_TIMEOUT, 60);
6156 +
6157 + $full_response = ''; // Accumulate full response for saving
6158 + $stream_started = false;
6159 + $buffer = ''; // CRITICAL: Add persistent buffer for incomplete chunks
6160 +
6161 + // Buffer control for real-time streaming
6162 + curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, $testing_data) {
6163 + // Send testing data as the first event if available
6164 + if (!$stream_started && $testing_data !== null) {
6165 + echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
6166 + flush();
6167 + $stream_started = true;
6168 + //error_log("MxChat Testing: Sent testing data in DeepSeek stream");
6169 + }
6170 +
6171 + // CRITICAL FIX: Append new data to buffer
6172 + $buffer .= $data;
6173 +
6174 + // Process complete lines only
6175 + $lines = explode("\n", $buffer);
6176 +
6177 + // CRITICAL FIX: Keep the last incomplete line in the buffer
6178 + // The last element might be incomplete, so keep it in buffer
6179 + $buffer = array_pop($lines);
6180 +
6181 + foreach ($lines as $line) {
6182 + // Skip empty lines
6183 + if (trim($line) === '') {
6184 + continue;
6185 + }
6186 +
6187 + // Only process lines that start with "data: "
6188 + if (strpos($line, 'data: ') !== 0) {
6189 + continue;
6190 + }
6191 +
6192 + $json_str = substr($line, 6); // Remove 'data: ' prefix
6193 +
6194 + if (trim($json_str) === '[DONE]') {
6195 + echo "data: [DONE]\n\n";
6196 + flush();
6197 + continue;
6198 + }
6199 +
6200 + // Try to decode JSON
6201 + $json = json_decode(trim($json_str), true);
6202 + if ($json && isset($json['choices'][0]['delta']['content'])) {
6203 + $content = $json['choices'][0]['delta']['content'];
6204 + $full_response .= $content; // Accumulate the full response
6205 +
6206 + // Send as SSE format
6207 + echo "data: " . json_encode(['content' => $content]) . "\n\n";
6208 + flush();
6209 + }
6210 + }
6211 +
6212 + return strlen($data);
6213 + });
6214 +
6215 + $response = curl_exec($ch);
6216 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
6217 +
6218 + if (curl_errno($ch) || $http_code !== 200) {
6219 + $curl_error = curl_error($ch);
6220 + curl_close($ch);
6221 +
6222 + // Log the specific error for debugging
6223 + //error_log("MxChat: DeepSeek streaming failed - HTTP: $http_code, cURL: $curl_error");
6224 +
6225 + // Fallback to regular response
6226 + $regular_response = $this->mxchat_generate_response_deepseek(
6227 + $selected_model,
6228 + $deepseek_api_key,
6229 + $conversation_history,
6230 + $relevant_content
6231 + );
6232 +
6233 + // Handle error response from regular function
6234 + if (is_array($regular_response) && isset($regular_response['error'])) {
6235 + if ($testing_data !== null) {
6236 + $regular_response['testing_data'] = $testing_data;
6237 + }
6238 + header('Content-Type: application/json');
6239 + echo json_encode($regular_response);
6240 + return true;
6241 + }
6242 +
6243 + $response_data = [
6244 + 'text' => $regular_response,
6245 + 'html' => '',
6246 + 'session_id' => $session_id
6247 + ];
6248 +
6249 + if ($testing_data !== null) {
6250 + $response_data['testing_data'] = $testing_data;
6251 + //error_log("MxChat Testing: Added testing data to DeepSeek error fallback");
6252 + }
6253 +
6254 + header('Content-Type: application/json');
6255 + echo json_encode($response_data);
6256 + return true;
6257 + }
6258 +
6259 + curl_close($ch);
6260 +
6261 + // Save the complete response to maintain chat persistence
6262 + if (!empty($full_response) && !empty($session_id)) {
6263 + // Prepare RAG context for streaming response
6264 + $rag_context_for_storage = null;
6265 + if ($this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches'])) {
6266 + $rag_context_for_storage = [
6267 + 'top_matches' => $this->last_similarity_analysis['top_matches'],
6268 + 'approved_urls' => $this->current_valid_urls ?? [],
6269 + 'similarity_threshold' => $this->last_similarity_analysis['threshold_used'] ?? 0.35,
6270 + 'knowledge_base_type' => $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database',
6271 + 'total_documents_checked' => $this->last_similarity_analysis['total_checked'] ?? 0
6272 + ];
6273 + }
6274 + $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
6275 + }
6276 +
6277 + return true; // Indicate streaming completed successfully
6278 +
6279 + } catch (Exception $e) {
6280 + //error_log("MxChat DeepSeek streaming exception: " . $e->getMessage());
6281 +
6282 + // Fallback to regular response
6283 + $regular_response = $this->mxchat_generate_response_deepseek(
6284 + $selected_model,
6285 + $deepseek_api_key,
6286 + $conversation_history,
6287 + $relevant_content
6288 + );
6289 +
6290 + // Handle error response from regular function
6291 + if (is_array($regular_response) && isset($regular_response['error'])) {
6292 + if ($testing_data !== null) {
6293 + $regular_response['testing_data'] = $testing_data;
6294 + }
6295 + header('Content-Type: application/json');
6296 + echo json_encode($regular_response);
6297 + return true;
6298 + }
6299 +
6300 + $response_data = [
6301 + 'text' => $regular_response,
6302 + 'html' => '',
6303 + 'session_id' => $session_id
6304 + ];
6305 +
6306 + if ($testing_data !== null) {
6307 + $response_data['testing_data'] = $testing_data;
6308 + //error_log("MxChat Testing: Added testing data to DeepSeek exception fallback");
6309 + }
6310 +
6311 + header('Content-Type: application/json');
6312 + echo json_encode($response_data);
6313 + return true;
6314 + }
6315 +}
6316 +
6317 +
6318 +private function mxchat_generate_response_openrouter($selected_model, $openrouter_api_key, $conversation_history, $relevant_content) {
6319 + try {
6320 + if (!is_array($conversation_history)) {
6321 + $conversation_history = array();
6322 + }
6323 +
6324 + $bot_id = $this->get_current_bot_id('');
6325 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6326 +
6327 + $formatted_conversation = array();
6328 +
6329 + $formatted_conversation[] = array(
6330 + 'role' => 'system',
6331 + 'content' => $system_prompt_instructions . " " . $relevant_content
6332 + );
6333 +
6334 + foreach ($conversation_history as $message) {
6335 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
6336 + $role = $message['role'];
6337 +
6338 + if ($role === 'bot' || $role === 'agent') {
6339 + $role = 'assistant';
6340 + }
6341 + if (!in_array($role, ['system', 'assistant', 'user'])) {
6342 + $role = 'user';
6343 + }
6344 +
6345 + $formatted_conversation[] = array(
6346 + 'role' => $role,
6347 + 'content' => $message['content']
6348 + );
6349 + }
6350 + }
6351 +
6352 + $body = json_encode([
6353 + 'model' => $selected_model,
6354 + 'messages' => $formatted_conversation,
6355 + 'temperature' => 1,
6356 + ]);
6357 +
6358 + $args = [
6359 + 'body' => $body,
6360 + 'headers' => [
6361 + 'Content-Type' => 'application/json',
6362 + 'Authorization' => 'Bearer ' . $openrouter_api_key,
6363 + 'HTTP-Referer' => home_url(),
6364 + 'X-Title' => get_bloginfo('name'),
6365 + ],
6366 + 'timeout' => 60,
6367 + 'redirection' => 5,
6368 + 'blocking' => true,
6369 + 'httpversion' => '1.0',
6370 + 'sslverify' => true,
6371 + ];
6372 +
6373 + $response = wp_remote_post('https://openrouter.ai/api/v1/chat/completions', $args);
6374 +
6375 + if (is_wp_error($response)) {
6376 + $error_message = $response->get_error_message();
6377 + return [
6378 + 'error' => esc_html__('Connection error when contacting OpenRouter: ', 'mxchat') . esc_html($error_message),
6379 + 'error_code' => 'openrouter_connection_error',
6380 + 'provider' => 'openrouter'
6381 + ];
6382 + }
6383 +
6384 + $status_code = wp_remote_retrieve_response_code($response);
6385 + if ($status_code !== 200) {
6386 + $response_body = wp_remote_retrieve_body($response);
6387 + $decoded_response = json_decode($response_body, true);
6388 +
6389 + $error_message = isset($decoded_response['error']['message'])
6390 + ? $decoded_response['error']['message']
6391 + : 'HTTP Error ' . $status_code;
6392 +
6393 + return [
6394 + 'error' => esc_html__('OpenRouter API error: ', 'mxchat') . esc_html($error_message),
6395 + 'error_code' => 'openrouter_api_error',
6396 + 'provider' => 'openrouter',
6397 + 'status_code' => $status_code
6398 + ];
6399 + }
6400 +
6401 + $response_body = wp_remote_retrieve_body($response);
6402 + $decoded_response = json_decode($response_body, true);
6403 +
6404 + if (isset($decoded_response['choices'][0]['message']['content'])) {
6405 + return trim($decoded_response['choices'][0]['message']['content']);
6406 + } else {
6407 + return [
6408 + 'error' => esc_html__('Unexpected response format from OpenRouter.', 'mxchat'),
6409 + 'error_code' => 'openrouter_response_format_error',
6410 + 'provider' => 'openrouter'
6411 + ];
6412 + }
6413 + } catch (Exception $e) {
6414 + return [
6415 + 'error' => esc_html__('System error when processing OpenRouter request: ', 'mxchat') . esc_html($e->getMessage()),
6416 + 'error_code' => 'openrouter_exception',
6417 + 'provider' => 'openrouter'
6418 + ];
6419 + }
6420 +}
6421 +private function mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content) {
6422 +
6423 + // Get bot ID from session or request
6424 + $bot_id = $this->get_current_bot_id($session_id);
6425 +
6426 + // Get system prompt instructions using centralized function
6427 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6428 +
6429 + // Clean and validate conversation history
6430 + foreach ($conversation_history as &$message) {
6431 + // Convert bot and agent roles to assistant
6432 + if ($message['role'] === 'bot' || $message['role'] === 'agent') {
6433 + $message['role'] = 'assistant';
6434 + }
6435 +
6436 + // Remove unsupported roles - Claude only supports 'assistant' and 'user'
6437 + if (!in_array($message['role'], ['assistant', 'user'])) {
6438 + $message['role'] = 'user';
6439 + }
6440 +
6441 + // Ensure content field exists
6442 + if (!isset($message['content']) || empty($message['content'])) {
6443 + $message['content'] = '';
6444 + }
6445 +
6446 + // Remove any unsupported fields
6447 + $message = array_intersect_key($message, array_flip(['role', 'content']));
6448 + }
6449 +
6450 + // Add relevant content as the latest user message
6451 + $conversation_history[] = [
6452 + 'role' => 'user',
6453 + 'content' => $relevant_content
6454 + ];
6455 +
6456 + // Build request body
6457 + $body = json_encode([
6458 + 'model' => $selected_model,
6459 + 'max_tokens' => 1000,
6460 + 'temperature' => 0.8,
6461 + 'messages' => $conversation_history,
6462 + 'system' => $system_prompt_instructions
6463 + ]);
6464 +
6465 + // Set up API request
6466 + $args = [
6467 + 'body' => $body,
6468 + 'headers' => [
6469 + 'Content-Type' => 'application/json',
6470 + 'x-api-key' => $claude_api_key,
6471 + 'anthropic-version' => '2023-06-01'
6472 + ],
6473 + 'timeout' => 60,
6474 + 'redirection' => 5,
6475 + 'blocking' => true,
6476 + 'httpversion' => '1.0',
6477 + 'sslverify' => true,
6478 + ];
6479 +
6480 + // Make API request
6481 + $response = wp_remote_post('https://api.anthropic.com/v1/messages', $args);
6482 +
6483 + // Check for WordPress errors
6484 + if (is_wp_error($response)) {
6485 + //error_log("Claude API request error: " . $response->get_error_message());
6486 + return "Sorry, there was an error connecting to the API.";
6487 + }
6488 +
6489 + // Check HTTP response code
6490 + $http_code = wp_remote_retrieve_response_code($response);
6491 + if ($http_code !== 200) {
6492 + $error_body = wp_remote_retrieve_body($response);
6493 + //error_log("Claude API HTTP error: " . $http_code . " - " . $error_body);
6494 +
6495 + // Try to extract error message from response
6496 + $error_data = json_decode($error_body, true);
6497 + $error_message = isset($error_data['error']['message']) ?
6498 + $error_data['error']['message'] :
6499 + "HTTP error " . $http_code;
6500 +
6501 + return "Sorry, the API returned an error: " . $error_message;
6502 + }
6503 +
6504 + // Parse response
6505 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
6506 +
6507 + // Check for JSON decode errors
6508 + if (json_last_error() !== JSON_ERROR_NONE) {
6509 + //error_log("Claude API JSON decode error: " . json_last_error_msg());
6510 + return "Sorry, there was an error processing the API response.";
6511 + }
6512 +
6513 + // Extract and validate response content
6514 + if (isset($response_body['content']) &&
6515 + is_array($response_body['content']) &&
6516 + !empty($response_body['content']) &&
6517 + isset($response_body['content'][0]['text'])) {
6518 + return trim($response_body['content'][0]['text']);
6519 + }
6520 +
6521 + // Log unexpected response format
6522 + //error_log("Claude API unexpected response format: " . print_r($response_body, true));
6523 + return "Sorry, I received an unexpected response format from the API.";
6524 +}
6525 +private function mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content) {
6526 + try {
6527 + // Ensure conversation_history is an array
6528 + if (!is_array($conversation_history)) {
6529 + $conversation_history = array();
6530 + }
6531 +
6532 + // Get bot ID from session or request
6533 + $bot_id = $this->get_current_bot_id('');
6534 +
6535 + // Get system prompt instructions using centralized function
6536 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6537 +
6538 + // Create a new array for the formatted conversation
6539 + $formatted_conversation = array();
6540 +
6541 + // Add system message first
6542 + $formatted_conversation[] = array(
6543 + 'role' => 'system',
6544 + 'content' => $system_prompt_instructions . " " . $relevant_content
6545 + );
6546 +
6547 + // Add the rest of the conversation history
6548 + foreach ($conversation_history as $message) {
6549 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
6550 + $role = $message['role'];
6551 +
6552 + // Convert roles to supported format
6553 + if ($role === 'bot' || $role === 'agent') {
6554 + $role = 'assistant';
6555 + }
6556 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
6557 + $role = 'user';
6558 + }
6559 +
6560 + $formatted_conversation[] = array(
6561 + 'role' => $role,
6562 + 'content' => $message['content']
6563 + );
6564 + }
6565 + }
6566 +
6567 + // Check if this is a GPT-5 model (supports reasoning_effort parameter)
6568 + $is_gpt5_model = (
6569 + strpos($selected_model, 'gpt-5') === 0 ||
6570 + $selected_model === 'gpt-5.2' ||
6571 + $selected_model === 'gpt-5.1-2025-11-13' ||
6572 + $selected_model === 'gpt-5' ||
6573 + $selected_model === 'gpt-5-mini' ||
6574 + $selected_model === 'gpt-5-nano'
6575 + );
6576 +
6577 + // Build request body with optimal settings for fast responses
6578 + $request_body = [
6579 + 'model' => $selected_model,
6580 + 'messages' => $formatted_conversation,
6581 + 'temperature' => 1,
6582 + 'stream' => false
6583 + ];
6584 +
6585 + // Add reasoning_effort only for GPT-5 models (not GPT-5.2 which doesn't support it)
6586 + if ($is_gpt5_model && $selected_model !== 'gpt-5.2') {
6587 + // GPT-5.1 uses 'low' instead of 'minimal'
6588 + if ($selected_model === 'gpt-5.1-2025-11-13') {
6589 + $request_body['reasoning_effort'] = 'low';
6590 + } else {
6591 + $request_body['reasoning_effort'] = 'minimal'; // For other GPT-5 models
6592 + }
6593 + }
6594 +
6595 + $body = json_encode($request_body);
6596 +
6597 + $args = [
6598 + 'body' => $body,
6599 + 'headers' => [
6600 + 'Content-Type' => 'application/json',
6601 + 'Authorization' => 'Bearer ' . $api_key,
6602 + ],
6603 + 'timeout' => 60,
6604 + 'redirection' => 5,
6605 + 'blocking' => true,
6606 + 'httpversion' => '1.0',
6607 + 'sslverify' => true,
6608 + ];
6609 +
6610 + $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
6611 +
6612 + if (is_wp_error($response)) {
6613 + $error_message = $response->get_error_message();
6614 + return [
6615 + 'error' => esc_html__('Connection error when contacting OpenAI: ', 'mxchat') . esc_html($error_message),
6616 + 'error_code' => 'openai_connection_error',
6617 + 'provider' => 'openai'
6618 + ];
6619 + }
6620 +
6621 + $status_code = wp_remote_retrieve_response_code($response);
6622 + if ($status_code !== 200) {
6623 + $response_body = wp_remote_retrieve_body($response);
6624 + $decoded_response = json_decode($response_body, true);
6625 +
6626 + $error_message = isset($decoded_response['error']['message'])
6627 + ? $decoded_response['error']['message']
6628 + : 'HTTP Error ' . $status_code;
6629 +
6630 + $error_type = isset($decoded_response['error']['type'])
6631 + ? $decoded_response['error']['type']
6632 + : 'unknown';
6633 +
6634 + // Handle specific error types
6635 + switch ($error_type) {
6636 + case 'invalid_request_error':
6637 + if (strpos($error_message, 'API key') !== false) {
6638 + return [
6639 + 'error' => esc_html__('Invalid OpenAI API key. Please check your API key configuration.', 'mxchat'),
6640 + 'error_code' => 'openai_invalid_api_key',
6641 + 'provider' => 'openai'
6642 + ];
6643 + }
6644 + break;
6645 +
6646 + case 'authentication_error':
6647 + return [
6648 + 'error' => esc_html__('Authentication failed with OpenAI. Please check your API key.', 'mxchat'),
6649 + 'error_code' => 'openai_auth_error',
6650 + 'provider' => 'openai'
6651 + ];
6652 +
6653 + case 'rate_limit_exceeded':
6654 + return [
6655 + 'error' => esc_html__('OpenAI rate limit exceeded. Please try again later.', 'mxchat'),
6656 + 'error_code' => 'openai_rate_limit',
6657 + 'provider' => 'openai'
6658 + ];
6659 +
6660 + case 'quota_exceeded':
6661 + return [
6662 + 'error' => esc_html__('OpenAI API quota exceeded. Please check your billing details.', 'mxchat'),
6663 + 'error_code' => 'openai_quota_exceeded',
6664 + 'provider' => 'openai'
6665 + ];
6666 + }
6667 +
6668 + // Generic error fallback
6669 + return [
6670 + 'error' => esc_html__('OpenAI API error: ', 'mxchat') . esc_html($error_message),
6671 + 'error_code' => 'openai_api_error',
6672 + 'provider' => 'openai',
6673 + 'status_code' => $status_code
6674 + ];
6675 + }
6676 +
6677 + $response_body = wp_remote_retrieve_body($response);
6678 + $decoded_response = json_decode($response_body, true);
6679 +
6680 + if (isset($decoded_response['choices'][0]['message']['content'])) {
6681 + return trim($decoded_response['choices'][0]['message']['content']);
6682 + } else {
6683 + return [
6684 + 'error' => esc_html__('Unexpected response format from OpenAI.', 'mxchat'),
6685 + 'error_code' => 'openai_response_format_error',
6686 + 'provider' => 'openai'
6687 + ];
6688 + }
6689 + } catch (Exception $e) {
6690 + return [
6691 + 'error' => esc_html__('System error when processing OpenAI request: ', 'mxchat') . esc_html($e->getMessage()),
6692 + 'error_code' => 'openai_exception',
6693 + 'provider' => 'openai'
6694 + ];
6695 + }
6696 +}
6697 +
6698 +private function mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content) {
6699 + try {
6700 + // Get bot ID from session or request
6701 + $bot_id = $this->get_current_bot_id($session_id);
6702 +
6703 + // Get system prompt instructions using centralized function
6704 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6705 +
6706 + // Add system prompt to relevant content
6707 + $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
6708 +
6709 + // Prepend system instructions to the conversation history
6710 + array_unshift($conversation_history, [
6711 + 'role' => 'system',
6712 + 'content' => "Here are your instructions: " . $content_with_instructions
6713 + ]);
6714 +
6715 + // Ensure consistency: Replace 'bot' and 'agent' roles with supported values
6716 + foreach ($conversation_history as &$message) {
6717 + if ($message['role'] === 'bot') {
6718 + $message['role'] = 'assistant';
6719 + } elseif ($message['role'] === 'agent') {
6720 + // Tag the message as coming from a live agent
6721 + $message['role'] = 'assistant';
6722 + if (!isset($message['metadata'])) {
6723 + $message['metadata'] = ['source' => 'live_agent'];
6724 + }
6725 + }
6726 +
6727 + // Ensure all roles are valid
6728 + if (!in_array($message['role'], ['system', 'assistant', 'user', 'function', 'tool'])) {
6729 + $message['role'] = 'user'; // Default to 'user'
6730 + }
6731 + }
6732 +
6733 + // Build the request body
6734 + $body = json_encode([
6735 + 'model' => $selected_model,
6736 + 'messages' => $conversation_history,
6737 + 'temperature' => 0.8,
6738 + 'stream' => false
6739 + ]);
6740 +
6741 + // Set up the API request
6742 + $args = [
6743 + 'body' => $body,
6744 + 'headers' => [
6745 + 'Content-Type' => 'application/json',
6746 + 'Authorization' => 'Bearer ' . $xai_api_key,
6747 + ],
6748 + 'timeout' => 60,
6749 + 'redirection' => 5,
6750 + 'blocking' => true,
6751 + 'httpversion' => '1.0',
6752 + 'sslverify' => true,
6753 + ];
6754 +
6755 + // Make the API request
6756 + $response = wp_remote_post('https://api.x.ai/v1/chat/completions', $args);
6757 +
6758 + // Process the response
6759 + if (is_wp_error($response)) {
6760 + $error_message = $response->get_error_message();
6761 + //error_log('X.AI API Error: ' . $error_message);
6762 + return [
6763 + 'error' => esc_html__('Connection error when contacting X.AI: ', 'mxchat') . esc_html($error_message),
6764 + 'error_code' => 'xai_connection_error',
6765 + 'provider' => 'xai'
6766 + ];
6767 + }
6768 +
6769 + $status_code = wp_remote_retrieve_response_code($response);
6770 + if ($status_code !== 200) {
6771 + $response_body = wp_remote_retrieve_body($response);
6772 + $decoded_response = json_decode($response_body, true);
6773 +
6774 + // Log the full response for debugging
6775 + //error_log('X.AI Error Response: ' . print_r($decoded_response, true));
6776 +
6777 + // Extract error message from X.AI's specific format
6778 + $error_message = '';
6779 +
6780 + // Check for direct error string (as seen in your logs)
6781 + if (isset($decoded_response['error']) && is_string($decoded_response['error'])) {
6782 + $error_message = $decoded_response['error'];
6783 + }
6784 + // Check for nested error object (OpenAI style)
6785 + elseif (isset($decoded_response['error']['message'])) {
6786 + $error_message = $decoded_response['error']['message'];
6787 + }
6788 + // Check for top-level message
6789 + elseif (isset($decoded_response['message'])) {
6790 + $error_message = $decoded_response['message'];
6791 + }
6792 + // Fallback
6793 + else {
6794 + $error_message = 'HTTP Error ' . $status_code;
6795 + }
6796 +
6797 + //error_log('X.AI API HTTP Error: ' . $status_code . ' - ' . $error_message);
6798 +
6799 + // Check for API key errors using string matching
6800 + if (stripos($error_message, 'api key') !== false ||
6801 + stripos($error_message, 'incorrect api key') !== false ||
6802 + stripos($error_message, 'invalid api key') !== false) {
6803 + return [
6804 + 'error' => esc_html__('Invalid X.AI API key. Please check your API key configuration.', 'mxchat'),
6805 + 'error_code' => 'xai_invalid_api_key',
6806 + 'provider' => 'xai'
6807 + ];
6808 + }
6809 +
6810 + // Authentication errors
6811 + if ($status_code === 401 || $status_code === 403 ||
6812 + stripos($error_message, 'auth') !== false) {
6813 + return [
6814 + 'error' => esc_html__('Authentication failed with X.AI. Please check your API key.', 'mxchat'),
6815 + 'error_code' => 'xai_auth_error',
6816 + 'provider' => 'xai'
6817 + ];
6818 + }
6819 +
6820 + // Model errors
6821 + if (stripos($error_message, 'model') !== false) {
6822 + return [
6823 + 'error' => esc_html__('Invalid model specified for X.AI. Please check your model configuration.', 'mxchat'),
6824 + 'error_code' => 'xai_invalid_model',
6825 + 'provider' => 'xai'
6826 + ];
6827 + }
6828 +
6829 + // Rate limit errors
6830 + if ($status_code === 429 ||
6831 + stripos($error_message, 'rate') !== false ||
6832 + stripos($error_message, 'limit') !== false) {
6833 + return [
6834 + 'error' => esc_html__('X.AI rate limit exceeded. Please try again later.', 'mxchat'),
6835 + 'error_code' => 'xai_rate_limit',
6836 + 'provider' => 'xai'
6837 + ];
6838 + }
6839 +
6840 + // Quota errors
6841 + if (stripos($error_message, 'quota') !== false ||
6842 + stripos($error_message, 'billing') !== false) {
6843 + return [
6844 + 'error' => esc_html__('X.AI API quota exceeded. Please check your billing details.', 'mxchat'),
6845 + 'error_code' => 'xai_quota_exceeded',
6846 + 'provider' => 'xai'
6847 + ];
6848 + }
6849 +
6850 + // Server errors
6851 + if ($status_code >= 500) {
6852 + return [
6853 + 'error' => esc_html__('X.AI service is currently unavailable. Please try again later.', 'mxchat'),
6854 + 'error_code' => 'xai_service_unavailable',
6855 + 'provider' => 'xai'
6856 + ];
6857 + }
6858 +
6859 + // Generic error fallback with the actual error message
6860 + return [
6861 + 'error' => esc_html__('X.AI API error: ', 'mxchat') . esc_html($error_message),
6862 + 'error_code' => 'xai_api_error',
6863 + 'provider' => 'xai',
6864 + 'status_code' => $status_code
6865 + ];
6866 + }
6867 +
6868 + $response_body = wp_remote_retrieve_body($response);
6869 + $decoded_response = json_decode($response_body, true);
6870 +
6871 + if (isset($decoded_response['choices'][0]['message']['content'])) {
6872 + return trim($decoded_response['choices'][0]['message']['content']);
6873 + } else {
6874 + //error_log('X.AI API Response Format Error: ' . print_r($decoded_response, true));
6875 + return [
6876 + 'error' => esc_html__('Unexpected response format from X.AI.', 'mxchat'),
6877 + 'error_code' => 'xai_response_format_error',
6878 + 'provider' => 'xai'
6879 + ];
6880 + }
6881 +} catch (Exception $e) {
6882 + //error_log('X.AI Exception: ' . $e->getMessage());
6883 + return [
6884 + 'error' => esc_html__('System error when processing X.AI request: ', 'mxchat') . esc_html($e->getMessage()),
6885 + 'error_code' => 'xai_exception',
6886 + 'provider' => 'xai'
6887 + ];
6888 +}
6889 +
6890 +
6891 +}
6892 +private function mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content) {
6893 + try {
6894 + // Ensure conversation_history is an array
6895 + if (!is_array($conversation_history)) {
6896 + $conversation_history = array();
6897 + }
6898 +
6899 + // Get bot ID from session or request
6900 + $bot_id = $this->get_current_bot_id($session_id);
6901 +
6902 + // Get system prompt instructions using centralized function
6903 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
6904 +
6905 + // Create a new array for the formatted conversation
6906 + $formatted_conversation = array();
6907 +
6908 + // Add system message first
6909 + $formatted_conversation[] = array(
6910 + 'role' => 'system',
6911 + 'content' => $system_prompt_instructions . " " . $relevant_content
6912 + );
6913 +
6914 + // Add the rest of the conversation history
6915 + foreach ($conversation_history as $message) {
6916 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
6917 + $role = $message['role'];
6918 +
6919 + // Convert roles to supported format
6920 + if ($role === 'bot' || $role === 'agent') {
6921 + $role = 'assistant';
6922 + }
6923 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
6924 + $role = 'user';
6925 + }
6926 +
6927 + $formatted_conversation[] = array(
6928 + 'role' => $role,
6929 + 'content' => $message['content']
6930 + );
6931 + }
6932 + }
6933 +
6934 + $body = json_encode([
6935 + 'model' => $selected_model,
6936 + 'messages' => $formatted_conversation,
6937 + 'temperature' => 0.8,
6938 + 'stream' => false
6939 + ]);
6940 +
6941 + $args = [
6942 + 'body' => $body,
6943 + 'headers' => [
6944 + 'Content-Type' => 'application/json',
6945 + 'Authorization' => 'Bearer ' . $deepseek_api_key,
6946 + ],
6947 + 'timeout' => 60,
6948 + 'redirection' => 5,
6949 + 'blocking' => true,
6950 + 'httpversion' => '1.0',
6951 + 'sslverify' => true,
6952 + ];
6953 +
6954 + $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', $args);
6955 +
6956 + if (is_wp_error($response)) {
6957 + $error_message = $response->get_error_message();
6958 + //error_log('DeepSeek API Error: ' . $error_message);
6959 + return [
6960 + 'error' => esc_html__('Connection error when contacting DeepSeek: ', 'mxchat') . esc_html($error_message),
6961 + 'error_code' => 'deepseek_connection_error',
6962 + 'provider' => 'deepseek'
6963 + ];
6964 + }
6965 +
6966 + $status_code = wp_remote_retrieve_response_code($response);
6967 + if ($status_code !== 200) {
6968 + $response_body = wp_remote_retrieve_body($response);
6969 + $decoded_response = json_decode($response_body, true);
6970 +
6971 + $error_message = isset($decoded_response['error']['message'])
6972 + ? $decoded_response['error']['message']
6973 + : 'HTTP Error ' . $status_code;
6974 +
6975 + $error_type = isset($decoded_response['error']['type'])
6976 + ? $decoded_response['error']['type']
6977 + : 'unknown';
6978 +
6979 + //error_log('DeepSeek API HTTP Error: ' . $status_code . ' - ' . $error_message);
6980 +
6981 + // Handle specific error types
6982 + switch ($status_code) {
6983 + case 401:
6984 + return [
6985 + 'error' => esc_html__('Authentication failed with DeepSeek. Please check your API key.', 'mxchat'),
6986 + 'error_code' => 'deepseek_auth_error',
6987 + 'provider' => 'deepseek'
6988 + ];
6989 +
6990 + case 400:
6991 + if (strpos($error_message, 'API key') !== false) {
6992 + return [
6993 + 'error' => esc_html__('Invalid DeepSeek API key. Please check your API key configuration.', 'mxchat'),
6994 + 'error_code' => 'deepseek_invalid_api_key',
6995 + 'provider' => 'deepseek'
6996 + ];
6997 + }
6998 + break;
6999 +
7000 + case 429:
7001 + if (strpos($error_message, 'quota') !== false) {
7002 + return [
7003 + 'error' => esc_html__('DeepSeek API quota exceeded. Please check your billing details.', 'mxchat'),
7004 + 'error_code' => 'deepseek_quota_exceeded',
7005 + 'provider' => 'deepseek'
7006 + ];
7007 + } else {
7008 + return [
7009 + 'error' => esc_html__('DeepSeek rate limit exceeded. Please try again later.', 'mxchat'),
7010 + 'error_code' => 'deepseek_rate_limit',
7011 + 'provider' => 'deepseek'
7012 + ];
7013 + }
7014 +
7015 + case 500:
7016 + case 502:
7017 + case 503:
7018 + case 504:
7019 + return [
7020 + 'error' => esc_html__('DeepSeek service is currently unavailable. Please try again later.', 'mxchat'),
7021 + 'error_code' => 'deepseek_service_unavailable',
7022 + 'provider' => 'deepseek'
7023 + ];
7024 + }
7025 +
7026 + // Generic error fallback
7027 + return [
7028 + 'error' => esc_html__('DeepSeek API error: ', 'mxchat') . esc_html($error_message),
7029 + 'error_code' => 'deepseek_api_error',
7030 + 'provider' => 'deepseek',
7031 + 'status_code' => $status_code
7032 + ];
7033 + }
7034 +
7035 + $response_body = wp_remote_retrieve_body($response);
7036 + $decoded_response = json_decode($response_body, true);
7037 +
7038 + if (isset($decoded_response['choices'][0]['message']['content'])) {
7039 + return trim($decoded_response['choices'][0]['message']['content']);
7040 + } else {
7041 + //error_log('DeepSeek API Response Format Error: ' . print_r($decoded_response, true));
7042 + return [
7043 + 'error' => esc_html__('Unexpected response format from DeepSeek.', 'mxchat'),
7044 + 'error_code' => 'deepseek_response_format_error',
7045 + 'provider' => 'deepseek'
7046 + ];
7047 + }
7048 + } catch (Exception $e) {
7049 + //error_log('DeepSeek Exception: ' . $e->getMessage());
7050 + return [
7051 + 'error' => esc_html__('System error when processing DeepSeek request: ', 'mxchat') . esc_html($e->getMessage()),
7052 + 'error_code' => 'deepseek_exception',
7053 + 'provider' => 'deepseek'
7054 + ];
7055 + }
7056 +}
7057 +private function mxchat_generate_response_gemini($selected_model, $gemini_api_key, $conversation_history, $relevant_content) {
7058 + // Get bot ID from session or request
7059 + $bot_id = $this->get_current_bot_id($session_id);
7060 +
7061 + // Get system prompt instructions using centralized function
7062 + $system_prompt_instructions = $this->get_system_instructions($bot_id);
7063 +
7064 + // Add system prompt to relevant content
7065 + $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
7066 +
7067 + // Format messages for Gemini API
7068 + $formatted_messages = [];
7069 +
7070 + // Add system message as the first user message with role prefix
7071 + // Note: Gemini doesn't have a dedicated system role, so we use a prefixed user message
7072 + $formatted_messages[] = [
7073 + 'role' => 'user',
7074 + 'parts' => [
7075 + ['text' => "[System Instructions] " . $content_with_instructions]
7076 + ]
7077 + ];
7078 +
7079 + // Add model response to acknowledge system instructions
7080 + $formatted_messages[] = [
7081 + 'role' => 'model',
7082 + 'parts' => [
7083 + ['text' => "I understand and will follow these instructions."]
7084 + ]
7085 + ];
7086 +
7087 + // Process the rest of the conversation history
7088 + $current_role = null;
7089 + $current_parts = [];
7090 +
7091 + foreach ($conversation_history as $message) {
7092 + // Skip the first system message as we already handled it
7093 + if ($message['role'] === 'system') {
7094 + continue;
7095 + }
7096 +
7097 + // Map roles to Gemini format
7098 + $gemini_role = '';
7099 + if ($message['role'] === 'user') {
7100 + $gemini_role = 'user';
7101 + } else if (in_array($message['role'], ['assistant', 'bot', 'agent'])) {
7102 + $gemini_role = 'model';
7103 + } else {
7104 + // Skip unsupported roles
7105 + continue;
7106 + }
7107 +
7108 + // If we have a new role, add the previous message
7109 + if ($current_role !== null && $current_role !== $gemini_role && !empty($current_parts)) {
7110 + $formatted_messages[] = [
7111 + 'role' => $current_role,
7112 + 'parts' => $current_parts
7113 + ];
7114 + $current_parts = [];
7115 + }
7116 +
7117 + // Set current role and add text to parts
7118 + $current_role = $gemini_role;
7119 + $current_parts[] = ['text' => $message['content']];
7120 + }
7121 +
7122 + // Add the last message if there's content
7123 + if ($current_role !== null && !empty($current_parts)) {
7124 + $formatted_messages[] = [
7125 + 'role' => $current_role,
7126 + 'parts' => $current_parts
7127 + ];
7128 + }
7129 +
7130 + // Build the request body
7131 + $body = json_encode([
7132 + 'contents' => $formatted_messages,
7133 + 'generationConfig' => [
7134 + 'temperature' => 0.7,
7135 + 'topP' => 0.95,
7136 + 'topK' => 40,
7137 + 'maxOutputTokens' => 8192,
7138 + ],
7139 + 'safetySettings' => [
7140 + [
7141 + 'category' => 'HARM_CATEGORY_HARASSMENT',
7142 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
7143 + ],
7144 + [
7145 + 'category' => 'HARM_CATEGORY_HATE_SPEECH',
7146 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
7147 + ],
7148 + [
7149 + 'category' => 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
7150 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
7151 + ],
7152 + [
7153 + 'category' => 'HARM_CATEGORY_DANGEROUS_CONTENT',
7154 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
7155 + ]
7156 + ]
7157 + ]);
7158 +
7159 + // Prepare the API endpoint
7160 + $api_endpoint = 'https://generativelanguage.googleapis.com/v1/models/' . $selected_model . ':generateContent?key=' . $gemini_api_key;
7161 +
7162 + // Set up the API request
7163 + $args = [
7164 + 'body' => $body,
7165 + 'headers' => [
7166 + 'Content-Type' => 'application/json',
7167 + ],
7168 + 'timeout' => 60,
7169 + 'redirection' => 5,
7170 + 'blocking' => true,
7171 + 'httpversion' => '1.0',
7172 + 'sslverify' => true,
7173 + ];
7174 +
7175 + // Make the API request
7176 + $response = wp_remote_post($api_endpoint, $args);
7177 +
7178 + // Process the response
7179 + if (is_wp_error($response)) {
7180 + return "Sorry, there was an error processing your request: " . $response->get_error_message();
7181 + }
7182 +
7183 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
7184 +
7185 + // Handle potential errors in the response
7186 + if (isset($response_body['error'])) {
7187 + //error_log('Gemini API Error: ' . json_encode($response_body['error']));
7188 + return "Sorry, there was an error with the Gemini API: " .
7189 + (isset($response_body['error']['message']) ? $response_body['error']['message'] : 'Unknown error');
7190 + }
7191 +
7192 + // Extract the response text
7193 + if (isset($response_body['candidates'][0]['content']['parts'][0]['text'])) {
7194 + return trim($response_body['candidates'][0]['content']['parts'][0]['text']);
7195 + } else {
7196 + //error_log('Unexpected Gemini API response format: ' . json_encode($response_body));
7197 + return "Sorry, I couldn't process that request. The response format was unexpected.";
7198 + }
7199 +}
7200 +
7201 +
7202 +public function test_streaming_request() {
7203 + $options = get_option('mxchat_options', []);
7204 + $model = $options['model'] ?? 'gpt-4o';
7205 +
7206 + // Detect provider from model prefix
7207 + $provider = strtolower(explode('-', $model)[0]);
7208 +
7209 + $sample_prompt = 'Hello! Can you stream this response back to me?';
7210 + $messages = [['role' => 'user', 'content' => $sample_prompt]];
7211 + $headers = [];
7212 + $body = [];
7213 + $url = '';
7214 + $api_key = '';
7215 +
7216 + switch ($provider) {
7217 + case 'gpt':
7218 + case 'o1':
7219 + $api_key = $options['api_key'] ?? '';
7220 + if (empty($api_key)) return '❌ Missing API key for OpenAI';
7221 + $url = 'https://api.openai.com/v1/chat/completions';
7222 + $headers = [
7223 + 'Content-Type: application/json',
7224 + 'Authorization: Bearer ' . $api_key
7225 + ];
7226 + $body = [
7227 + 'model' => $model,
7228 + 'messages' => $messages,
7229 + 'stream' => true
7230 + ];
7231 + break;
7232 +
7233 + case 'claude':
7234 + $api_key = $options['claude_api_key'] ?? '';
7235 + if (empty($api_key)) return '❌ Missing API key for Claude';
7236 + $url = 'https://api.anthropic.com/v1/messages';
7237 + $headers = [
7238 + 'Content-Type: application/json',
7239 + 'x-api-key: ' . $api_key,
7240 + 'anthropic-version: 2023-06-01'
7241 + ];
7242 + $body = [
7243 + 'model' => $model,
7244 + 'messages' => $messages,
7245 + 'max_tokens' => 100,
7246 + 'stream' => true
7247 + ];
7248 + break;
7249 +
7250 + case 'grok':
7251 + $api_key = $options['xai_api_key'] ?? '';
7252 + if (empty($api_key)) return '❌ Missing API key for X.AI';
7253 + $url = 'https://api.x.ai/v1/chat/completions';
7254 + $headers = [
7255 + 'Content-Type: application/json',
7256 + 'Authorization: Bearer ' . $api_key
7257 + ];
7258 + $body = [
7259 + 'model' => $model,
7260 + 'messages' => $messages,
7261 + 'stream' => true
7262 + ];
7263 + break;
7264 +
7265 + case 'deepseek':
7266 + if (empty($deepseek_api_key)) {
7267 + $error_response = [
7268 + 'error' => esc_html__('DeepSeek API key is not configured', 'mxchat'),
7269 + 'error_code' => 'missing_deepseek_api_key'
7270 + ];
7271 + if ($testing_data !== null) {
7272 + $error_response['testing_data'] = $testing_data;
7273 + }
7274 + return $error_response;
7275 + }
7276 + if ($streaming) {
7277 + return $this->mxchat_generate_response_deepseek_stream(
7278 + $selected_model,
7279 + $deepseek_api_key,
7280 + $conversation_history,
7281 + $relevant_content,
7282 + $session_id,
7283 + $testing_data // Pass testing data
7284 + );
7285 + } else {
7286 + $response = $this->mxchat_generate_response_deepseek(
7287 + $selected_model,
7288 + $deepseek_api_key,
7289 + $conversation_history,
7290 + $relevant_content
7291 + );
7292 + }
7293 + break;
7294 +
7295 + case 'gemini':
7296 + $api_key = $options['gemini_api_key'] ?? '';
7297 + if (empty($api_key)) return '❌ Missing API key for Gemini';
7298 + $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':streamGenerateContent?key=' . $api_key;
7299 + $headers = ['Content-Type: application/json'];
7300 + $body = [
7301 + 'contents' => [['role' => 'user', 'parts' => [['text' => $sample_prompt]]]],
7302 + 'generationConfig' => ['temperature' => 0.7]
7303 + ];
7304 + break;
7305 +
7306 + default:
7307 + return '❌ Unsupported provider: ' . $provider;
7308 + }
7309 +
7310 + // Do the actual streaming test
7311 + $ch = curl_init($url);
7312 + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
7313 + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
7314 + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
7315 + curl_setopt($ch, CURLOPT_TIMEOUT, 15);
7316 + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
7317 +
7318 + $response = curl_exec($ch);
7319 + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
7320 + $error = curl_error($ch);
7321 + curl_close($ch);
7322 +
7323 + if ($error) return "❌ cURL error: $error";
7324 + if ($http_code !== 200) {
7325 + $error_message = json_decode($response, true)['error']['message'] ?? 'Unknown';
7326 + return "❌ HTTP $http_code: $error_message";
7327 + }
7328 +
7329 + return true;
7330 +}
7331 +
7332 +public function mxchat_dismiss_pre_chat_message() {
7333 + // Get and sanitize the user identifier
7334 + $user_id = $this->mxchat_get_user_identifier();
7335 + $user_id = sanitize_key($user_id);
7336 +
7337 + // Set a transient to track that the user has dismissed the pre-chat message
7338 + $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
7339 + set_transient($transient_key, true, DAY_IN_SECONDS);
7340 +
7341 + wp_send_json_success();
7342 +}
7343 +
7344 +public function mxchat_check_pre_chat_message_status() {
7345 + // Get and sanitize the user identifier
7346 + $user_id = $this->mxchat_get_user_identifier();
7347 + $user_id = sanitize_key($user_id);
7348 +
7349 + // Check if the transient exists (i.e., if the message was dismissed)
7350 + $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
7351 + $dismissed = get_transient($transient_key);
7352 +
7353 + // Log the result to see if it's being set correctly
7354 + //error_log("Check pre-chat message dismissed for $user_id: " . ($dismissed ? 'Yes' : 'No'));
7355 +
7356 + if ($dismissed) {
7357 + wp_send_json_success(['dismissed' => true]);
7358 + } else {
7359 + wp_send_json_success(['dismissed' => false]);
7360 + }
7361 +
7362 + wp_die();
7363 +}
7364 +
7365 +private function mxchat_calculate_cosine_similarity($vectorA, $vectorB) {
7366 + if (!is_array($vectorA) || !is_array($vectorB) || empty($vectorA) || empty($vectorB)) {
7367 + return 0;
7368 + }
7369 +
7370 + $dotProduct = array_sum(array_map(function ($a, $b) {
7371 + return $a * $b;
7372 + }, $vectorA, $vectorB));
7373 + $normA = sqrt(array_sum(array_map(function ($a) {
7374 + return $a * $a;
7375 + }, $vectorA)));
7376 + $normB = sqrt(array_sum(array_map(function ($b) {
7377 + return $b * $b;
7378 + }, $vectorB)));
7379 +
7380 + if ($normA == 0 || $normB == 0) {
7381 + return 0;
7382 + }
7383 +
7384 + return $dotProduct / ($normA * $normB);
7385 + }
7386 +
7387 +
7388 +public function mxchat_enqueue_scripts_styles() {
7389 + // Enqueue the script
7390 + wp_enqueue_script(
7391 + 'mxchat-chat-js',
7392 + plugin_dir_url(__FILE__) . '../js/chat-script.js',
7393 + array('jquery'),
7394 + MXCHAT_VERSION,
7395 + true
7396 + );
7397 + // Enqueue the CSS
7398 + wp_enqueue_style(
7399 + 'mxchat-chat-css',
7400 + plugin_dir_url(__FILE__) . '../css/chat-style.css',
7401 + array(),
7402 + MXCHAT_VERSION
7403 + );
7404 + // Fetch options from the database
7405 + $this->options = get_option('mxchat_options');
7406 + $prompts_options = get_option('mxchat_prompts_options', array());
7407 +
7408 + // Prepare settings for JavaScript
7409 + $style_settings = array(
7410 + 'ajax_url' => admin_url('admin-ajax.php'),
7411 + 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
7412 + 'model' => isset($this->options['model']) ? $this->options['model'] : 'gpt-4o',
7413 + 'enable_streaming_toggle' => isset($this->options['enable_streaming_toggle']) ? $this->options['enable_streaming_toggle'] : 'on',
7414 + 'contextual_awareness_toggle' => isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off',
7415 + 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
7416 + 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
7417 + 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
7418 + 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
7419 + 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
7420 + 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
7421 + 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
7422 + 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
7423 + 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
7424 + 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
7425 + 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
7426 + 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
7427 + 'icon_color' => $this->options['icon_color'] ?? '#fff',
7428 + 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
7429 + 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
7430 + 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off',
7431 + 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
7432 + 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
7433 + 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
7434 + 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
7435 + 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
7436 + 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
7437 + 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
7438 + 'email_collection_enabled' => $this->options['enable_email_block'] ?? 'off', // FIXED
7439 + 'initial_email_state' => null, // Also fixed this undefined variable
7440 + 'skip_email_check' => true,
7441 + 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1'
7442 + );
7443 + // Pass the settings to the script
7444 + wp_localize_script('mxchat-chat-js', 'mxchatChat', $style_settings);
7445 +}
7446 +
7447 +
7448 +/**
7449 + * Setup the cron jobs for rate limits with guard against multiple calls
7450 + */
7451 +public function setup_rate_limit_cron_jobs() {
7452 + // Add a guard to prevent multiple rapid calls
7453 + $last_setup = get_transient('mxchat_cron_setup_guard');
7454 + if ($last_setup && (time() - $last_setup) < 60) {
7455 + // Don't run again if we ran less than 60 seconds ago
7456 + return;
7457 + }
7458 +
7459 + // Set the guard
7460 + set_transient('mxchat_cron_setup_guard', time(), 300); // 5 minutes
7461 +
7462 + try {
7463 + // First, check if WordPress cron is disabled
7464 + if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
7465 + //error_log('MxChat: WordPress cron is disabled (DISABLE_WP_CRON = true), using fallback system');
7466 + $this->setup_fallback_rate_limit_system();
7467 + return;
7468 + }
7469 +
7470 + // Check if cron is already scheduled - if so, don't mess with it
7471 + if (wp_next_scheduled('mxchat_reset_rate_limits')) {
7472 + //error_log('MxChat: Rate limit cron already scheduled, skipping setup');
7473 + return;
7474 + }
7475 +
7476 + // Clear any orphaned hooks (but don't loop indefinitely)
7477 + $hooks_to_clear = [
7478 + 'mxchat_reset_rate_limits',
7479 + 'mxchat_reset_hourly_rate_limits',
7480 + 'mxchat_reset_daily_rate_limits',
7481 + 'mxchat_reset_weekly_rate_limits',
7482 + 'mxchat_reset_monthly_rate_limits'
7483 + ];
7484 +
7485 + foreach ($hooks_to_clear as $hook) {
7486 + // Only clear a maximum of 3 instances to prevent infinite loops
7487 + $cleared = 0;
7488 + while (wp_next_scheduled($hook) && $cleared < 3) {
7489 + wp_clear_scheduled_hook($hook);
7490 + $cleared++;
7491 + }
7492 + }
7493 +
7494 + // Small delay after clearing
7495 + usleep(100000); // 0.1 seconds
7496 +
7497 + // Try to schedule the event
7498 + $initial_time = time() + 300; // Start in 5 minutes
7499 + $result = wp_schedule_event($initial_time, 'hourly', 'mxchat_reset_rate_limits');
7500 +
7501 + if ($result === false) {
7502 + //error_log('MxChat: Failed to schedule cron, using fallback system');
7503 + $this->setup_fallback_rate_limit_system();
7504 + } else {
7505 + //error_log('MxChat: Successfully scheduled rate limit reset cron');
7506 + }
7507 +
7508 + } catch (Exception $e) {
7509 + //error_log('MxChat: Cron setup exception: ' . $e->getMessage());
7510 + $this->setup_fallback_rate_limit_system();
7511 + }
7512 +}
7513 +
7514 +/**
7515 + * Try alternative cron scheduling methods
7516 + */
7517 +private function try_alternative_cron_scheduling($initial_time) {
7518 + try {
7519 + // Method 1: Try with current time instead of future time
7520 + $result1 = wp_schedule_event(time(), 'hourly', 'mxchat_reset_rate_limits');
7521 + if ($result1 !== false) {
7522 + //error_log('MxChat: Alternative method 1 (current time) succeeded');
7523 + return true;
7524 + }
7525 +
7526 + // Method 2: Try with a different interval
7527 + $result2 = wp_schedule_event($initial_time, 'daily', 'mxchat_reset_rate_limits');
7528 + if ($result2 !== false) {
7529 + //error_log('MxChat: Alternative method 2 (daily interval) succeeded');
7530 + return true;
7531 + }
7532 +
7533 + // Method 3: Try wp_schedule_single_event first, then recurring
7534 + $result3 = wp_schedule_single_event($initial_time, 'mxchat_reset_rate_limits');
7535 + if ($result3 !== false) {
7536 + //error_log('MxChat: Alternative method 3 (single event) succeeded');
7537 + // Schedule the next one manually in the handler
7538 + return true;
7539 + }
7540 +
7541 + return false;
7542 +
7543 + } catch (Exception $e) {
7544 + //error_log('MxChat: Alternative cron scheduling exception: ' . $e->getMessage());
7545 + return false;
7546 + }
7547 +}
7548 +
7549 +/**
7550 + * Enhanced fallback rate limit system
7551 + */
7552 +private function setup_fallback_rate_limit_system() {
7553 + // Set a flag to use database-based rate limit cleanup
7554 + update_option('mxchat_use_fallback_rate_limits', true);
7555 +
7556 + // Schedule a one-time check to happen on the next plugin load
7557 + update_option('mxchat_next_rate_limit_check', time() + 3600);
7558 +
7559 + // Also set up a more frequent fallback check (every 4 hours)
7560 + update_option('mxchat_fallback_check_interval', 4 * 3600);
7561 +
7562 + //error_log('MxChat: Fallback rate limit system activated');
7563 +}
7564 +
7565 +/**
7566 + * Enhanced fallback check method
7567 + */
7568 +public function check_fallback_rate_limits() {
7569 + $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
7570 +
7571 + if (!$use_fallback) {
7572 + return; // Regular cron is working
7573 + }
7574 +
7575 + $next_check = get_option('mxchat_next_rate_limit_check', 0);
7576 + $check_interval = get_option('mxchat_fallback_check_interval', 3600);
7577 +
7578 + if (time() >= $next_check) {
7579 + //error_log('MxChat: Running fallback rate limit cleanup');
7580 + $this->mxchat_reset_rate_limits();
7581 +
7582 + // Schedule next check
7583 + update_option('mxchat_next_rate_limit_check', time() + $check_interval);
7584 + }
7585 +}
7586 +/**
7587 + * Enhanced rate limit check that includes fallback cleanup and bot-specific rate limits
7588 + */
7589 +public function check_rate_limit() {
7590 + // Check if we need to run fallback cleanup
7591 + $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
7592 + $next_check = get_option('mxchat_next_rate_limit_check', 0);
7593 +
7594 + if ($use_fallback && time() >= $next_check) {
7595 + $this->mxchat_reset_rate_limits();
7596 + update_option('mxchat_next_rate_limit_check', time() + 3600); // Next hour
7597 + }
7598 +
7599 + // Get bot ID from current request context
7600 + $bot_id = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
7601 +
7602 + // Get bot-specific options (includes rate limits if overridden)
7603 + $bot_options = $this->get_bot_options($bot_id);
7604 + $current_options = !empty($bot_options) ? $bot_options : $this->options;
7605 +
7606 + // Use bot-specific rate limits if available, otherwise fall back to default
7607 + $rate_limits_source = isset($current_options['rate_limits']) ? $current_options['rate_limits'] : get_option('mxchat_options', [])['rate_limits'] ?? [];
7608 +
7609 + // Determine user role or if logged out
7610 + if (is_user_logged_in()) {
7611 + $user = wp_get_current_user();
7612 + $user_id = $user->ID;
7613 +
7614 + // Get the user's primary role using reset() to safely get the first element
7615 + $user_roles = $user->roles;
7616 +
7617 + // Safely get the first role regardless of array key structure
7618 + if (!empty($user_roles) && is_array($user_roles)) {
7619 + $role = reset($user_roles); // This safely gets the first element regardless of key
7620 + } else {
7621 + $role = 'subscriber'; // Default to subscriber if no role found
7622 + }
7623 + } else {
7624 + $role = 'logged_out';
7625 + // Use IP address for non-logged-in users
7626 + $user_id = $this->get_client_ip();
7627 + }
7628 +
7629 + // Check if rate limits are configured for this role
7630 + if (!isset($rate_limits_source[$role])) {
7631 + return true; // No limit set for this role
7632 + }
7633 +
7634 + $limit = $rate_limits_source[$role]['limit'];
7635 +
7636 + // If unlimited, return true immediately
7637 + if ($limit === 'unlimited') {
7638 + return true;
7639 + }
7640 +
7641 + // Get the option name for this user/role with safer naming (include bot_id for bot-specific limits)
7642 + $safe_role = preg_replace('/[^a-zA-Z0-9_]/', '_', $role);
7643 + $safe_user_id = preg_replace('/[^a-zA-Z0-9_]/', '_', $user_id);
7644 + $safe_bot_id = preg_replace('/[^a-zA-Z0-9_]/', '_', $bot_id);
7645 +
7646 + // Include bot_id in option name so each bot has separate rate limits
7647 + $option_name = 'mxchat_chat_limit_' . $safe_bot_id . '_' . $safe_role . '_' . $safe_user_id;
7648 +
7649 + // Get the counter data
7650 + $limit_data = get_option($option_name, ['count' => 0, 'timestamp' => time()]);
7651 +
7652 + // If first request or counter reset needed, set the initial timestamp
7653 + if ($limit_data['count'] === 0) {
7654 + $limit_data['timestamp'] = time();
7655 + update_option($option_name, $limit_data);
7656 + }
7657 +
7658 + // Get the timeframe
7659 + $timeframe = isset($rate_limits_source[$role]['timeframe']) ?
7660 + $rate_limits_source[$role]['timeframe'] : 'daily';
7661 +
7662 + // Check if the counter needs to be reset based on timeframe
7663 + $current_time = time();
7664 + $timestamp = $limit_data['timestamp'];
7665 + $should_reset = false;
7666 +
7667 + switch ($timeframe) {
7668 + case 'hourly':
7669 + $should_reset = ($current_time - $timestamp) >= 3600; // 1 hour
7670 + break;
7671 + case 'daily':
7672 + $should_reset = ($current_time - $timestamp) >= 86400; // 24 hours
7673 + break;
7674 + case 'weekly':
7675 + $should_reset = ($current_time - $timestamp) >= 604800; // 7 days
7676 + break;
7677 + case 'monthly':
7678 + $should_reset = ($current_time - $timestamp) >= 2592000; // 30 days
7679 + break;
7680 + }
7681 +
7682 + // Reset the counter if the timeframe has passed
7683 + if ($should_reset) {
7684 + $limit_data = ['count' => 0, 'timestamp' => $current_time];
7685 + update_option($option_name, $limit_data);
7686 + }
7687 +
7688 + // Check if user has exceeded their limit
7689 + if ($limit_data['count'] >= intval($limit)) {
7690 + // Get the custom message for this role
7691 + $message = !empty($rate_limits_source[$role]['message'])
7692 + ? $rate_limits_source[$role]['message']
7693 + : __('Rate limit exceeded. Please try again later.', 'mxchat');
7694 +
7695 + // Add timeframe information to the message if placeholders exist
7696 + $timeframe_label = '';
7697 + switch ($timeframe) {
7698 + case 'hourly':
7699 + $timeframe_label = __('hour', 'mxchat');
7700 + break;
7701 + case 'daily':
7702 + $timeframe_label = __('day', 'mxchat');
7703 + break;
7704 + case 'weekly':
7705 + $timeframe_label = __('week', 'mxchat');
7706 + break;
7707 + case 'monthly':
7708 + $timeframe_label = __('month', 'mxchat');
7709 + break;
7710 + }
7711 +
7712 + // Replace placeholders in the message
7713 + $message = str_replace(
7714 + ['{limit}', '{count}', '{remaining}', '{timeframe}'],
7715 + [intval($limit), $limit_data['count'], max(0, intval($limit) - $limit_data['count']), $timeframe_label],
7716 + $message
7717 + );
7718 +
7719 + // Process HTML links in the message
7720 + $message = $this->process_rate_limit_message_html($message);
7721 +
7722 + // Return error with the processed message
7723 + return [
7724 + 'error' => true,
7725 + 'message' => $message
7726 + ];
7727 + }
7728 +
7729 + // Increment the counter
7730 + $limit_data['count']++;
7731 + update_option($option_name, $limit_data);
7732 +
7733 + return true;
7734 +}
7735 +
7736 +/**
7737 + * Enhanced rate limit reset with better error handling
7738 + */
7739 +public function mxchat_reset_rate_limits() {
7740 + try {
7741 + global $wpdb;
7742 + $all_options = get_option('mxchat_options', []);
7743 + $current_time = time();
7744 +
7745 + // Get rate limit options with a safer query and limit
7746 + $option_names = $wpdb->get_col(
7747 + $wpdb->prepare(
7748 + "SELECT option_name FROM {$wpdb->options}
7749 + WHERE option_name LIKE %s
7750 + LIMIT 1000",
7751 + 'mxchat_chat_limit_%'
7752 + )
7753 + );
7754 +
7755 + if (empty($option_names)) {
7756 + return;
7757 + }
7758 +
7759 + $processed_count = 0;
7760 + $max_processing_time = 30; // Maximum 30 seconds
7761 + $start_time = time();
7762 +
7763 + foreach ($option_names as $option_name) {
7764 + // Check processing time limit
7765 + if ((time() - $start_time) > $max_processing_time) {
7766 + //error_log('MxChat: Rate limit reset timeout after processing ' . $processed_count . ' entries');
7767 + break;
7768 + }
7769 +
7770 + // Parse the option name more safely
7771 + if (!preg_match('/^mxchat_chat_limit_(.+)_(.+)$/', $option_name, $matches)) {
7772 + continue;
7773 + }
7774 +
7775 + $role_and_user = $matches[1] . '_' . $matches[2];
7776 + $parts = explode('_', $role_and_user);
7777 +
7778 + if (count($parts) < 2) {
7779 + continue;
7780 + }
7781 +
7782 + // Extract role (everything except the last part which is user ID)
7783 + $user_id_part = array_pop($parts);
7784 + $role = implode('_', $parts);
7785 +
7786 + // Skip if role doesn't exist in our settings
7787 + if (!isset($all_options['rate_limits'][$role])) {
7788 + // Clean up orphaned entries
7789 + delete_option($option_name);
7790 + continue;
7791 + }
7792 +
7793 + $timeframe = $all_options['rate_limits'][$role]['timeframe'] ?? 'daily';
7794 + $limit_data = get_option($option_name);
7795 +
7796 + if (!$limit_data || !is_array($limit_data) || !isset($limit_data['timestamp'])) {
7797 + // Clean up invalid entries
7798 + delete_option($option_name);
7799 + continue;
7800 + }
7801 +
7802 + $timestamp = $limit_data['timestamp'];
7803 + $should_reset = false;
7804 +
7805 + // Determine if we should reset based on the timeframe
7806 + switch ($timeframe) {
7807 + case 'hourly':
7808 + $should_reset = ($current_time - $timestamp) >= 3600;
7809 + break;
7810 + case 'daily':
7811 + $should_reset = ($current_time - $timestamp) >= 86400;
7812 + break;
7813 + case 'weekly':
7814 + $should_reset = ($current_time - $timestamp) >= 604800;
7815 + break;
7816 + case 'monthly':
7817 + $should_reset = ($current_time - $timestamp) >= 2592000;
7818 + break;
7819 + }
7820 +
7821 + // Reset the counter if the timeframe has passed
7822 + if ($should_reset) {
7823 + delete_option($option_name);
7824 + wp_cache_delete($option_name, 'options');
7825 + $processed_count++;
7826 + }
7827 + }
7828 +
7829 + // Clean up any orphaned cache entries
7830 + wp_cache_delete('mxchat_all_chat_limits', 'options');
7831 +
7832 + //error_log("MxChat: Rate limit reset completed. Processed {$processed_count} entries.");
7833 +
7834 + } catch (Exception $e) {
7835 + //error_log('MxChat: Rate limit reset error: ' . $e->getMessage());
7836 + }
7837 +}
7838 +
7839 +
7840 +/**
7841 + * Process HTML links in rate limit messages
7842 + *
7843 + * @param string $message The rate limit message
7844 + * @return string The processed message with safe HTML links
7845 + */
7846 +private function process_rate_limit_message_html($message) {
7847 + // Return original message if empty
7848 + if (empty($message)) {
7849 + return $message;
7850 + }
7851 +
7852 + // First, convert markdown links to HTML
7853 + $message = $this->convert_markdown_links($message);
7854 +
7855 + // Then, auto-convert any remaining plain URLs to links
7856 + $message = $this->auto_link_urls($message);
7857 +
7858 + // Allow basic HTML tags for links and formatting
7859 + $allowed_tags = [
7860 + 'a' => [
7861 + 'href' => true,
7862 + 'target' => true,
7863 + 'rel' => true,
7864 + 'title' => true,
7865 + 'class' => true
7866 + ],
7867 + 'strong' => [],
7868 + 'em' => [],
7869 + 'br' => [],
7870 + 'b' => [],
7871 + 'i' => [],
7872 + 'span' => ['class' => true]
7873 + ];
7874 +
7875 + // Sanitize but allow the specified HTML tags
7876 + $processed_message = wp_kses($message, $allowed_tags);
7877 +
7878 + // If wp_kses stripped everything, return the original message as plain text
7879 + if (empty($processed_message) && !empty($message)) {
7880 + // Strip all HTML and return plain text as fallback
7881 + return wp_strip_all_tags($message);
7882 + }
7883 +
7884 + return $processed_message;
7885 +}
7886 +
7887 +/**
7888 + * Convert markdown links to HTML
7889 + *
7890 + * @param string $text The text to process
7891 + * @return string The text with markdown links converted to HTML
7892 + */
7893 +private function convert_markdown_links($text) {
7894 + // Return original text if empty
7895 + if (empty($text)) {
7896 + return $text;
7897 + }
7898 +
7899 + // Pattern to match markdown links: [text](url)
7900 + $pattern = '/\[([^\]]+)\]\(([^)]+)\)/';
7901 +
7902 + $processed_text = preg_replace_callback($pattern, function($matches) {
7903 + $link_text = $matches[1];
7904 + $url = $matches[2];
7905 +
7906 + // Clean up any trailing punctuation from the URL
7907 + $url = rtrim($url, '.,;:!?');
7908 +
7909 + // Sanitize the link text and URL
7910 + $safe_text = esc_html($link_text);
7911 + $safe_url = esc_url($url);
7912 +
7913 + // Create the HTML link
7914 + return '<a href="' . $safe_url . '" target="_blank" rel="noopener noreferrer">' . $safe_text . '</a>';
7915 + }, $text);
7916 +
7917 + // If preg_replace_callback failed, return original text
7918 + if ($processed_text === null) {
7919 + return $text;
7920 + }
7921 +
7922 + return $processed_text;
7923 +}
7924 +
7925 +/**
7926 + * Auto-convert plain URLs to clickable links
7927 + *
7928 + * @param string $text The text to process
7929 + * @return string The text with URLs converted to links
7930 + */
7931 +private function auto_link_urls($text) {
7932 + // Return original text if empty
7933 + if (empty($text)) {
7934 + return $text;
7935 + }
7936 +
7937 + // Simple pattern that avoids complex lookbehinds
7938 + // This will match URLs that are not already inside href attributes or markdown links
7939 + $pattern = '/(?<!href=["\'])(?<!\]\()https?:\/\/[^\s<>"\')\]]+/i';
7940 +
7941 + $processed_text = preg_replace_callback($pattern, function($matches) {
7942 + $url = $matches[0];
7943 + // Clean up any trailing punctuation that might have been captured
7944 + $url = rtrim($url, '.,;:!?');
7945 +
7946 + // Add target="_blank" and rel="noopener noreferrer" for security
7947 + return '<a href="' . esc_url($url) . '" target="_blank" rel="noopener noreferrer">' . esc_html($url) . '</a>';
7948 + }, $text);
7949 +
7950 + // If preg_replace_callback failed, return original text
7951 + if ($processed_text === null) {
7952 + return $text;
7953 + }
7954 +
7955 + return $processed_text;
7956 +}
7957 +
7958 +
7959 +// Helper function to get client IP address
7960 +private function get_client_ip() {
7961 + // Check for shared internet/ISP IP
7962 + if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
7963 + return sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
7964 + }
7965 +
7966 + // Check for IPs passing through proxies
7967 + if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
7968 + // Use the first value in the comma-separated list
7969 + $forwarded_for = explode(',', sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']));
7970 + return trim($forwarded_for[0]);
7971 + }
7972 +
7973 + if (!empty($_SERVER['REMOTE_ADDR'])) {
7974 + return sanitize_text_field($_SERVER['REMOTE_ADDR']);
7975 + }
7976 +
7977 + // Fallback
7978 + return 'unknown';
7979 +}
7980 +
7981 +/**
7982 + * AJAX handler to get system information for testing panel
7983 + */
7984 +/**
7985 + * AJAX handler to get system information for testing panel
7986 + */
7987 +public function mxchat_get_system_info() {
7988 + // Verify nonce for security
7989 + if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
7990 + wp_send_json_error(['message' => 'Invalid nonce']);
7991 + return;
7992 + }
7993 +
7994 + // Only allow admin users
7995 + if (!current_user_can('administrator')) {
7996 + wp_send_json_error(['message' => 'Unauthorized']);
7997 + return;
7998 + }
7999 +
8000 + // Get system prompt from options
8001 + $system_prompt = isset($this->options['system_prompt_instructions'])
8002 + ? $this->options['system_prompt_instructions']
8003 + : 'No system prompt configured';
8004 +
8005 + // Get selected model
8006 + $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-4o';
8007 +
8008 + // Check if OpenRouter is being used
8009 + $is_openrouter = ($selected_model === 'openrouter');
8010 + $openrouter_model = '';
8011 +
8012 + if ($is_openrouter) {
8013 + // Get the actual OpenRouter model that's selected
8014 + $openrouter_model = isset($this->options['openrouter_selected_model'])
8015 + ? $this->options['openrouter_selected_model']
8016 + : 'No OpenRouter model selected';
8017 +
8018 + // Update selected_model display to show both
8019 + $selected_model = 'OpenRouter: ' . $openrouter_model;
8020 + }
8021 +
8022 + // Get API key status (just check if they exist, don't expose the keys)
8023 + $api_status = [];
8024 + $api_status['openai'] = !empty($this->options['api_key']);
8025 + $api_status['claude'] = !empty($this->options['claude_api_key']);
8026 + $api_status['gemini'] = !empty($this->options['gemini_api_key']);
8027 + $api_status['xai'] = !empty($this->options['xai_api_key']);
8028 + $api_status['deepseek'] = !empty($this->options['deepseek_api_key']);
8029 + $api_status['openrouter'] = !empty($this->options['openrouter_api_key']);
8030 +
8031 + wp_send_json_success([
8032 + 'system_prompt' => $system_prompt,
8033 + 'selected_model' => $selected_model,
8034 + 'is_openrouter' => $is_openrouter,
8035 + 'openrouter_model' => $openrouter_model,
8036 + 'api_status' => $api_status
8037 + ]);
8038 +}
8039 +
8040 +/**
8041 + * AJAX handler to get similarity threshold
8042 + */
8043 +public function mxchat_get_similarity_threshold() {
8044 + // Verify nonce for security
8045 + if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
8046 + wp_send_json_error(['message' => 'Invalid nonce']);
8047 + return;
8048 + }
8049 +
8050 + // Only allow admin users
8051 + if (!current_user_can('administrator')) {
8052 + wp_send_json_error(['message' => 'Unauthorized']);
8053 + return;
8054 + }
8055 +
8056 + // Get similarity threshold from main options (default 35%)
8057 + $similarity_threshold = isset($this->options['similarity_threshold'])
8058 + ? ((int) $this->options['similarity_threshold']) / 100
8059 + : 0.35;
8060 +
8061 + wp_send_json_success([
8062 + 'threshold' => $similarity_threshold,
8063 + 'threshold_percentage' => ($similarity_threshold * 100) . '%'
8064 + ]);
8065 +}
8066 +
8067 +/**
8068 + * AJAX handler to get knowledge base status
8069 + */
8070 +public function mxchat_get_kb_status() {
8071 + // Verify nonce for security
8072 + if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
8073 + wp_send_json_error(['message' => 'Invalid nonce']);
8074 + return;
8075 + }
8076 +
8077 + // Only allow admin users
8078 + if (!current_user_can('administrator')) {
8079 + wp_send_json_error(['message' => 'Unauthorized']);
8080 + return;
8081 + }
8082 +
8083 + // Check Pinecone vs WordPress
8084 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
8085 + $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1');
8086 +
8087 + $kb_info = [
8088 + 'type' => $use_pinecone ? 'Pinecone' : 'WordPress Database',
8089 + 'status' => 'Active'
8090 + ];
8091 +
8092 + // Get document count
8093 + if ($use_pinecone) {
8094 + $kb_info['documents'] = 'Connected to Pinecone';
8095 + $kb_info['api_configured'] = !empty($addon_options['mxchat_pinecone_api_key']);
8096 + } else {
8097 + // Count documents in WordPress database
8098 + global $wpdb;
8099 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
8100 + $count = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
8101 + $kb_info['documents'] = $count ? $count . ' documents' : 'No documents';
8102 + }
8103 +
8104 + wp_send_json_success($kb_info);
8105 +}
8106 +
8107 +/**
8108 + * AJAX handler to start a completely fresh session (NEW - replaces old clear session)
8109 + */
8110 +public function mxchat_start_fresh_session() {
8111 + // Verify nonce for security
8112 + if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
8113 + wp_send_json_error(['message' => 'Invalid nonce']);
8114 + return;
8115 + }
8116 +
8117 + // Only allow admin users
8118 + if (!current_user_can('administrator')) {
8119 + wp_send_json_error(['message' => 'Unauthorized']);
8120 + return;
8121 + }
8122 +
8123 + $old_session_id = isset($_POST['old_session_id']) ? sanitize_text_field($_POST['old_session_id']) : '';
8124 + $new_session_id = isset($_POST['new_session_id']) ? sanitize_text_field($_POST['new_session_id']) : '';
8125 +
8126 + if (empty($old_session_id)) {
8127 + wp_send_json_error(['message' => 'Old session ID required']);
8128 + return;
8129 + }
8130 +
8131 + // If no new session ID provided, generate one
8132 + if (empty($new_session_id)) {
8133 + $new_session_id = 'mxchat_chat_' . substr(md5(uniqid()), 0, 9);
8134 + }
8135 +
8136 + // Clear ALL data associated with the old session
8137 + $this->clear_complete_session_data($old_session_id);
8138 +
8139 + // Initialize the new session
8140 + $this->initialize_fresh_session($new_session_id);
8141 +
8142 + wp_send_json_success([
8143 + 'message' => 'Fresh session started successfully',
8144 + 'new_session_id' => $new_session_id,
8145 + 'old_session_id' => $old_session_id
8146 + ]);
8147 +}
8148 +
8149 +/**
8150 + * Clear ALL data associated with a session (ENHANCED)
8151 + */
8152 +private function clear_complete_session_data($session_id) {
8153 + // Clear chat history
8154 + delete_option("mxchat_history_{$session_id}");
8155 +
8156 + // Clear chat mode
8157 + delete_option("mxchat_mode_{$session_id}");
8158 +
8159 + // Clear any PDF/Word transients
8160 + $this->clear_pdf_transients($session_id);
8161 + if (method_exists($this, 'clear_word_transients')) {
8162 + $this->clear_word_transients($session_id);
8163 + }
8164 +
8165 + // Clear agent-related data
8166 + delete_option("mxchat_channel_{$session_id}");
8167 + delete_option("mxchat_agent_name_{$session_id}");
8168 + delete_option("mxchat_email_{$session_id}");
8169 +
8170 + // Clear any recommendation flow state
8171 + delete_option("mxchat_sr_flow_state_{$session_id}");
8172 +
8173 + // Clear any cached embeddings or context
8174 + delete_transient("mxchat_context_{$session_id}");
8175 + delete_transient("mxchat_last_query_{$session_id}");
8176 +
8177 + // Clear any testing data
8178 + delete_transient("mxchat_testing_data_{$session_id}");
8179 +
8180 + // Clear any rate limiting data for this session
8181 + delete_transient("mxchat_rate_limit_{$session_id}");
8182 +
8183 + // Clear any other session-specific transients
8184 + delete_transient("mxchat_waiting_for_pdf_url_{$session_id}");
8185 + delete_transient("mxchat_include_pdf_in_context_{$session_id}");
8186 + delete_transient("mxchat_include_word_in_context_{$session_id}");
8187 +
8188 + //error_log("MxChat: Cleared all data for session: {$session_id}");
8189 +}
8190 +
8191 +/**
8192 + * Initialize a fresh session with default data
8193 + */
8194 +private function initialize_fresh_session($session_id) {
8195 + // Set default chat mode
8196 + update_option("mxchat_mode_{$session_id}", 'ai');
8197 +
8198 + //error_log("MxChat: Initialized fresh session: {$session_id}");
8199 +}
8200 +
8201 +/**
8202 + * Helper method to clear Word document transients (if you have Word support)
8203 + */
8204 +private function clear_word_transients($session_id) {
8205 + delete_transient('mxchat_word_url_' . $session_id);
8206 + delete_transient('mxchat_word_filename_' . $session_id);
8207 + delete_transient('mxchat_word_embeddings_' . $session_id);
8208 + delete_transient('mxchat_include_word_in_context_' . $session_id);
8209 +}
8210 +
8211 +/**
8212 + * Simplified testing data capture method (CLEANED UP)
8213 + */
8214 +private function capture_testing_data($user_embedding, $message, $session_id) {
8215 + // Only capture for admin users
8216 + if (!current_user_can('administrator')) {
8217 + return null;
8218 + }
8219 +
8220 + $testing_data = [
8221 + 'query' => $message,
8222 + 'timestamp' => time(),
8223 + 'top_matches' => [],
8224 + 'action_matches' => [] // Add action matches
8225 + ];
8226 +
8227 + // Get similarity threshold
8228 + $similarity_threshold = isset($this->options['similarity_threshold'])
8229 + ? ((int) $this->options['similarity_threshold']) / 100
8230 + : 0.35;
8231 +
8232 + $testing_data['similarity_threshold'] = $similarity_threshold;
8233 +
8234 + // Use the real similarity analysis if available
8235 + if ($this->last_similarity_analysis !== null) {
8236 + $testing_data['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'];
8237 + $testing_data['top_matches'] = $this->last_similarity_analysis['top_matches'];
8238 + $testing_data['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
8239 + } else {
8240 + // Fallback: determine knowledge base type
8241 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
8242 + $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1');
8243 +
8244 + $testing_data['knowledge_base_type'] = $use_pinecone ? 'Pinecone' : 'WordPress Database';
8245 + }
8246 +
8247 + // Include action analysis if available
8248 + if (isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
8249 + $testing_data['action_matches'] = $this->last_action_analysis;
8250 +
8251 + // Clear it after capturing to avoid stale data
8252 + $this->last_action_analysis = null;
8253 + }
8254 +
8255 + return $testing_data;
8256 +}
8257 +
8258 +
8259 +/**
8260 + * Track URL clicks from chatbot responses
8261 + */
8262 +public function mxchat_track_url_click() {
8263 + // Verify nonce for security
8264 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
8265 + wp_send_json_error(['message' => 'Invalid nonce']);
8266 + wp_die();
8267 + }
8268 +
8269 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
8270 + $clicked_url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
8271 + $message_context = isset($_POST['message_context']) ? sanitize_textarea_field($_POST['message_context']) : '';
8272 +
8273 + if (empty($session_id) || empty($clicked_url)) {
8274 + wp_send_json_error(['message' => 'Missing required data']);
8275 + wp_die();
8276 + }
8277 +
8278 + global $wpdb;
8279 + $table_name = $wpdb->prefix . 'mxchat_url_clicks';
8280 +
8281 + // Insert click tracking record
8282 + $wpdb->insert(
8283 + $table_name,
8284 + [
8285 + 'session_id' => $session_id,
8286 + 'clicked_url' => $clicked_url,
8287 + 'message_context' => $message_context,
8288 + 'click_timestamp' => current_time('mysql', 1),
8289 + 'user_ip' => $_SERVER['REMOTE_ADDR'],
8290 + 'user_agent' => $_SERVER['HTTP_USER_AGENT']
8291 + ]
8292 + );
8293 +
8294 + wp_send_json_success(['message' => 'Click tracked']);
8295 + wp_die();
8296 +}
8297 +
8298 +/**
8299 + * Get URL click analytics for a session
8300 + */
8301 +public function mxchat_get_url_clicks($session_id) {
8302 + global $wpdb;
8303 + $table_name = $wpdb->prefix . 'mxchat_url_clicks';
8304 +
8305 + $clicks = $wpdb->get_results($wpdb->prepare(
8306 + "SELECT * FROM $table_name WHERE session_id = %s ORDER BY click_timestamp ASC",
8307 + $session_id
8308 + ));
8309 +
8310 + return $clicks;
8311 +}
8312 +/**
8313 + * Track the originating page where chat was started
8314 + */
8315 +public function mxchat_track_originating_page() {
8316 + // Verify nonce
8317 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
8318 + wp_send_json_error(['message' => 'Invalid nonce']);
8319 + wp_die();
8320 + }
8321 +
8322 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
8323 + $page_url = isset($_POST['page_url']) ? esc_url_raw($_POST['page_url']) : '';
8324 + $page_title = isset($_POST['page_title']) ? sanitize_text_field($_POST['page_title']) : '';
8325 +
8326 + if (empty($session_id)) {
8327 + wp_send_json_error(['message' => 'Missing session ID']);
8328 + wp_die();
8329 + }
8330 +
8331 + global $wpdb;
8332 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
8333 +
8334 + // Check if we've already tracked for this session
8335 + $existing = $wpdb->get_var($wpdb->prepare(
8336 + "SELECT COUNT(*) FROM $table_name
8337 + WHERE session_id = %s
8338 + AND originating_page_url IS NOT NULL",
8339 + $session_id
8340 + ));
8341 +
8342 + if ($existing > 0) {
8343 + wp_send_json_success(['message' => 'Already tracked']);
8344 + wp_die();
8345 + }
8346 +
8347 + // Update the first message in this session with originating page info
8348 + $wpdb->query($wpdb->prepare(
8349 + "UPDATE $table_name
8350 + SET originating_page_url = %s,
8351 + originating_page_title = %s
8352 + WHERE session_id = %s
8353 + ORDER BY timestamp ASC
8354 + LIMIT 1",
8355 + $page_url,
8356 + $page_title,
8357 + $session_id
8358 + ));
8359 +
8360 + wp_send_json_success(['message' => 'Originating page tracked']);
8361 + wp_die();
8362 +}
8363 +
8364 +/**
8365 + * Validate and clean URLs from AI response
8366 + * Removes any URLs that aren't in the knowledge base
8367 + *
8368 + * @param string $response_text The AI-generated response
8369 + * @param array $valid_urls Array of URLs from the knowledge base
8370 + * @return string Cleaned response with invalid URLs removed/flagged
8371 + */
8372 +private function validate_and_clean_urls($response_text, $valid_urls) {
8373 + // DEBUG: Log what we're working with
8374 + error_log("=== MxChat URL Validation Debug ===");
8375 + error_log("Valid URLs count: " . count($valid_urls));
8376 + error_log("Valid URLs: " . print_r($valid_urls, true));
8377 + error_log("Response text length: " . strlen($response_text));
8378 + error_log("Response text preview: " . substr($response_text, 0, 500));
8379 +
8380 + // If no valid URLs provided or empty response, return as-is
8381 + if (empty($valid_urls) || empty($response_text)) {
8382 + error_log("Validation skipped - empty valid_urls or response");
8383 + return $response_text;
8384 + }
8385 +
8386 + // Extract all URLs from the AI response
8387 + // This regex matches http:// and https:// URLs
8388 + preg_match_all(
8389 + '#\bhttps?://[^\s<>"\')\]]+#i',
8390 + $response_text,
8391 + $matches
8392 + );
8393 +
8394 + // If no URLs found in response, return as-is
8395 + if (empty($matches[0])) {
8396 + error_log("No URLs found in response");
8397 + return $response_text;
8398 + }
8399 +
8400 + $found_urls = $matches[0];
8401 + $cleaned_response = $response_text;
8402 + $removed_count = 0;
8403 +
8404 + // Normalize valid URLs for comparison (remove trailing slashes, fragments, etc.)
8405 + $normalized_valid_urls = array_map(function($url) {
8406 + // Remove trailing slash
8407 + $url = rtrim($url, '/');
8408 + // Remove URL fragments (#section)
8409 + $url = preg_replace('/#.*$/', '', $url);
8410 + // Remove trailing punctuation that might have been captured
8411 + $url = rtrim($url, '.,;:!?');
8412 + return $url;
8413 + }, $valid_urls);
8414 +
8415 + error_log("Normalized valid URLs: " . print_r($normalized_valid_urls, true));
8416 +
8417 + foreach ($found_urls as $found_url) {
8418 + // Clean up the found URL (remove trailing punctuation that might have been captured)
8419 + $clean_found_url = rtrim($found_url, '.,;:!?)');
8420 +
8421 + // DEBUG: Log each URL being checked
8422 + error_log("Checking found URL: " . $found_url);
8423 +
8424 + // Normalize for comparison
8425 + $normalized_found = rtrim($clean_found_url, '/');
8426 + $normalized_found = preg_replace('/#.*$/', '', $normalized_found);
8427 +
8428 + error_log("Normalized found URL: " . $normalized_found);
8429 +
8430 + // Check if this URL exists in our valid URLs list
8431 + $is_valid = false;
8432 +
8433 + error_log("Starting validation checks for: " . $normalized_found);
8434 +
8435 + // First, try exact match
8436 + if (in_array($normalized_found, $normalized_valid_urls)) {
8437 + $is_valid = true;
8438 + error_log("EXACT MATCH FOUND");
8439 + } else {
8440 + error_log("No exact match, checking variations...");
8441 + // If no exact match, check if it's a variation (with query params, etc.)
8442 + foreach ($normalized_valid_urls as $valid_url) {
8443 + error_log(" Comparing against valid URL: " . $valid_url);
8444 +
8445 + // Check if the found URL starts with a valid URL (handles query params)
8446 + if (strpos($normalized_found, $valid_url) === 0) {
8447 + // Check what comes after the valid URL
8448 + $remainder = substr($normalized_found, strlen($valid_url));
8449 +
8450 + // Only valid if:
8451 + // 1. Exact match (remainder is empty)
8452 + // 2. Query params (starts with ?)
8453 + // 3. Fragment (starts with #)
8454 + if (empty($remainder) || $remainder[0] === '?' || $remainder[0] === '#') {
8455 + $is_valid = true;
8456 + error_log(" MATCH: Found URL is valid variation of base URL");
8457 + break;
8458 + } else {
8459 + error_log(" NOT A MATCH: Found URL extends path beyond valid URL (remainder: " . $remainder . ")");
8460 + }
8461 + }
8462 + // Also check the reverse (in case valid URL has query params)
8463 + if (strpos($valid_url, $normalized_found) === 0) {
8464 + $is_valid = true;
8465 + error_log(" MATCH: Valid URL starts with found URL");
8466 + break;
8467 + }
8468 + }
8469 +
8470 + if (!$is_valid) {
8471 + error_log("NO MATCH FOUND - URL should be removed");
8472 + }
8473 + }
8474 +
8475 + // If URL is not valid, remove it from the response
8476 + if (!$is_valid) {
8477 + // Log the removal for debugging
8478 + error_log("MxChat: Removed hallucinated URL: " . $found_url);
8479 + error_log("MxChat: Valid URLs were: " . implode(', ', array_slice($normalized_valid_urls, 0, 5)));
8480 +
8481 + $removed_count++;
8482 +
8483 + // Check if URL is part of a markdown link: [text](url)
8484 + $markdown_pattern = '/\[([^\]]+)\]\(' . preg_quote($found_url, '/') . '\)/';
8485 + if (preg_match($markdown_pattern, $cleaned_response)) {
8486 + error_log("Found markdown link, removing but keeping text");
8487 + // Remove the markdown link but keep the text
8488 + $cleaned_response = preg_replace($markdown_pattern, '$1', $cleaned_response);
8489 + }
8490 + // Check if URL is part of an HTML link: <a href="url">text</a>
8491 + else if (preg_match('/<a[^>]*href=["\']' . preg_quote($found_url, '/') . '["\'][^>]*>(.*?)<\/a>/i', $cleaned_response, $link_match)) {
8492 + error_log("Found HTML link, removing but keeping text");
8493 + // Remove the HTML link but keep the text
8494 + $link_text = $link_match[1];
8495 + $cleaned_response = preg_replace(
8496 + '/<a[^>]*href=["\']' . preg_quote($found_url, '/') . '["\'][^>]*>.*?<\/a>/i',
8497 + $link_text,
8498 + $cleaned_response
8499 + );
8500 + }
8501 + // Otherwise just remove the bare URL
8502 + else {
8503 + error_log("Removing bare URL");
8504 + $cleaned_response = str_replace($found_url, '', $cleaned_response);
8505 + }
8506 + }
8507 + }
8508 +
8509 + // Log summary if any URLs were removed
8510 + if ($removed_count > 0) {
8511 + error_log("MxChat: URL Validation Summary - Removed {$removed_count} hallucinated URL(s)");
8512 + } else {
8513 + error_log("MxChat: URL Validation Summary - No URLs removed, all were valid");
8514 + }
8515 +
8516 + // Clean up any double spaces or awkward punctuation left behind
8517 + $cleaned_response = preg_replace('/\s+/', ' ', $cleaned_response);
8518 + $cleaned_response = preg_replace('/\s+([.,;:!?])/', '$1', $cleaned_response);
8519 +
8520 + error_log("Final cleaned response: " . $cleaned_response);
8521 +
8522 + return trim($cleaned_response);
8523 +}
8524 +
8525 +/**
8526 + * AJAX handler to get current chat mode for a session
8527 + */
8528 +public function mxchat_get_current_chat_mode() {
8529 + // Verify nonce for security
8530 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
8531 + wp_send_json_error(['message' => 'Invalid nonce']);
8532 + wp_die();
8533 + }
8534 +
8535 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
8536 +
8537 + if (empty($session_id)) {
8538 + wp_send_json_error(['message' => 'Session ID missing']);
8539 + wp_die();
8540 + }
8541 +
8542 + // Get the current chat mode for this session
8543 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
8544 +
8545 + wp_send_json_success([
8546 + 'chat_mode' => $chat_mode
8547 + ]);
8548 + wp_die();
8549 +}
8550 +
8551 +
8552 +
8553 +}
8554 +?>