PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 1.2
MxChat – AI Chatbot & Content Generation for WordPress v1.2
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 2.0.6 All 152 releases
← All changes | includes/class-mxchat-integrator.php +839 -12893 3.2.141.2 View file →
@@ -1,12893 +1,839 @@
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 - // plan-mxchat-20260717-03ba33 — consent-safe YouTube embed queued during RAG
13 - // retrieval when a video-backed KB entry is used as context. Emitted on the
14 - // response 'html' channel alongside productCardHtml (non-streaming path,
15 - // same constraint as product cards).
16 - private $videoEmbedHtml = '';
17 - // plan-mxchat-20260617-48a57a — function-calling UI payload capture. When a
18 - // model-invoked tool yields a UI element (generated image, woo product card,
19 - // image-search gallery), the FC loop stashes its html here so the FC outcome
20 - // handler can SURFACE it to the frontend the same way the intent path does,
21 - // instead of stripping it to text for the model (the bug: UI-bearing actions
22 - // rendered nothing under function calling).
23 - private $fc_ui_html = '';
24 - private $fc_ui_images = array();
25 - private $fc_ui_captured = false;
26 - private $word_handler;
27 - private $last_similarity_analysis = null;
28 - private $current_valid_urls = [];
29 - private $last_vectorstore_error = null;
30 - private $is_streaming = false; // ADDED: Track if current request is streaming
31 - private $streaming_headers_sent = false; // Track if streaming headers have been sent
32 - private $pending_originating_page = null; // Originating page captured at session start, consumed on row insert
33 - private $current_action_instruction = null; // Success-message instruction injected into the next system context
34 - private $last_action_analysis = null; // Last action-match analysis for testing_data payloads
35 -
36 -/**
37 - * Setup streaming headers - call this right before actually streaming
38 - * This delays header setup to allow actions/forms to return JSON responses
39 - */
40 -/**
41 - * Auto-retry wrapper around wp_remote_post for chat-send provider calls.
42 - *
43 - * Retries up to twice (750ms then 2000ms backoff) when the upstream provider
44 - * returns a TRANSIENT error: WP timeout, 429, 502, 503, 504, or a provider-
45 - * specific "overloaded" / "rate limit" body string. Returns immediately on
46 - * permanent errors (401/403/404/422) so misconfiguration surfaces fast.
47 - *
48 - * Drop-in replacement for wp_remote_post — returns the same shape
49 - * (WP_Error or response array) so the caller's existing error-handling
50 - * code path is unchanged.
51 - *
52 - * STREAMING PATH NOTE: this helper is ONLY for non-streaming chat-send
53 - * paths (the *_response_openai / *_response_claude / etc functions).
54 - * For the *_stream variants, the cURL initial-connect happens inside a
55 - * read-chunks loop — retrying there safely (without re-emitting partial
56 - * stream chunks to the client) is a separate problem. Streaming paths
57 - * are NOT wrapped in this build; tracked as a follow-on.
58 - *
59 - * Honors the `mxchat_options['auto_retry_on_transient_error']` toggle
60 - * (default true). When false, behavior is identical to plain wp_remote_post.
61 - */
62 -private function mxchat_provider_call_with_retry($url, $args, $provider_hint = '') {
63 - $opts = is_array($this->options ?? null) ? $this->options : array();
64 - $enabled = !isset($opts['auto_retry_on_transient_error']) ||
65 - (string) $opts['auto_retry_on_transient_error'] !== '0';
66 -
67 - if (!$enabled) {
68 - return wp_remote_post($url, $args);
69 - }
70 -
71 - $backoffs = array(0, 750, 2000); // ms — first attempt 0, then retry waits
72 - $last_response = null;
73 -
74 - foreach ($backoffs as $i => $delay_ms) {
75 - if ($delay_ms > 0) {
76 - usleep($delay_ms * 1000);
77 - }
78 - $response = wp_remote_post($url, $args);
79 - $last_response = $response;
80 -
81 - if (!$this->mxchat_is_transient_provider_error($response, $provider_hint)) {
82 - return $response;
83 - }
84 -
85 - if (defined('WP_DEBUG') && WP_DEBUG) {
86 - $code_for_log = is_wp_error($response) ? 'wp_error:' . $response->get_error_code()
87 - : (int) wp_remote_retrieve_response_code($response);
88 - error_log(sprintf(
89 - '[MxChat] Transient provider error (provider=%s, attempt=%d/3, status=%s). %s',
90 - $provider_hint ?: 'unknown',
91 - $i + 1,
92 - $code_for_log,
93 - ($i + 1) < count($backoffs) ? 'Retrying.' : 'Giving up.'
94 - ));
95 - }
96 - }
97 -
98 - return $last_response;
99 -}
100 -
101 -/**
102 - * Returns true if a wp_remote_post response represents a TRANSIENT
103 - * provider error worth retrying. Conservative — only retries on signals
104 - * that are very likely to clear within a few seconds.
105 - *
106 - * Transient signals:
107 - * - WP_Error with timeout / connection / dns / ssl
108 - * - HTTP 429, 502, 503, 504
109 - * - Provider-specific overload bodies (gemini "overloaded", openai
110 - * "server_error", anthropic "overloaded_error", xai/grok "Rate limit")
111 - *
112 - * NOT transient (return false — fail-fast):
113 - * - 200/2xx (success)
114 - * - 401, 403, 404, 422 (auth / config errors — retrying wastes the
115 - * budget; the user needs to fix something)
116 - * - Any other 4xx (assume permanent unless explicitly listed above)
117 - * - 5xx other than the four listed above (e.g. 500 generic server error
118 - * is often a malformed request on our side, not a transient outage)
119 - */
120 -private function mxchat_is_transient_provider_error($response, $provider_hint = '') {
121 - if (is_wp_error($response)) {
122 - $code = $response->get_error_code();
123 - return in_array($code, array('http_request_failed', 'connection_failed', 'connection_timeout'), true)
124 - || stripos((string) $response->get_error_message(), 'timed out') !== false
125 - || stripos((string) $response->get_error_message(), 'timeout') !== false;
126 - }
127 -
128 - $status = (int) wp_remote_retrieve_response_code($response);
129 - if (in_array($status, array(429, 502, 503, 504), true)) {
130 - return true;
131 - }
132 - if ($status >= 200 && $status < 300) {
133 - return false;
134 - }
135 - // Permanent 4xx that should fail fast — even with no body.
136 - if (in_array($status, array(401, 403, 404, 405, 422), true)) {
137 - return false;
138 - }
139 -
140 - // Provider-specific body inspection for the cases where the upstream
141 - // returns 200 with an error envelope (gemini does this for overload).
142 - $body = (string) wp_remote_retrieve_body($response);
143 - if ($body === '') {
144 - return false;
145 - }
146 - $lower = strtolower($body);
147 - $hint = strtolower((string) $provider_hint);
148 -
149 - if ($hint === 'gemini' && (strpos($lower, 'overloaded') !== false
150 - || strpos($lower, 'high demand') !== false
151 - || strpos($lower, 'model is overloaded') !== false)) {
152 - return true;
153 - }
154 - if ($hint === 'openai' && (strpos($lower, 'rate limit reached') !== false
155 - || strpos($lower, '"type":"server_error"') !== false
156 - || strpos($lower, '"code":"server_error"') !== false)) {
157 - return true;
158 - }
159 - if ($hint === 'anthropic' && (strpos($lower, '"type":"overloaded_error"') !== false
160 - || strpos($lower, 'overloaded_error') !== false)) {
161 - return true;
162 - }
163 - if (($hint === 'xai' || $hint === 'grok') && strpos($lower, 'rate limit') !== false) {
164 - return true;
165 - }
166 -
167 - return false;
168 -}
169 -
170 -/**
171 - * Streaming-path classifier: same rules as mxchat_is_transient_provider_error
172 - * but takes a raw (http_code, body, provider_hint, curl_errno) tuple as
173 - * captured during a cURL streaming exec. cURL's WRITEFUNCTION/HEADERFUNCTION
174 - * collect status separately from a plain wp_remote_post array shape, so the
175 - * non-streaming helper above can't be called directly. This delegate keeps
176 - * the classification rules identical across both paths.
177 - */
178 -private function mxchat_is_transient_provider_error_raw($http_code, $body, $provider_hint = '', $curl_errno = 0) {
179 - if ($curl_errno) {
180 - // cURL transport-level error (timeout, connection failure, DNS, etc.)
181 - // Match the same WP_Error timeout/connection signals the array variant treats as transient.
182 - return in_array($curl_errno, array(
183 - CURLE_OPERATION_TIMEDOUT,
184 - CURLE_COULDNT_CONNECT,
185 - CURLE_COULDNT_RESOLVE_HOST,
186 - CURLE_SSL_CONNECT_ERROR,
187 - CURLE_GOT_NOTHING,
188 - CURLE_SEND_ERROR,
189 - CURLE_RECV_ERROR,
190 - ), true);
191 - }
192 -
193 - $status = (int) $http_code;
194 - if (in_array($status, array(429, 502, 503, 504), true)) {
195 - return true;
196 - }
197 - if ($status >= 200 && $status < 300) {
198 - return false;
199 - }
200 - if (in_array($status, array(401, 403, 404, 405, 422), true)) {
201 - return false;
202 - }
203 -
204 - $body = (string) $body;
205 - if ($body === '') {
206 - return false;
207 - }
208 - $lower = strtolower($body);
209 - $hint = strtolower((string) $provider_hint);
210 -
211 - if ($hint === 'gemini' && (strpos($lower, 'overloaded') !== false
212 - || strpos($lower, 'high demand') !== false
213 - || strpos($lower, 'model is overloaded') !== false)) {
214 - return true;
215 - }
216 - if ($hint === 'openai' && (strpos($lower, 'rate limit reached') !== false
217 - || strpos($lower, '"type":"server_error"') !== false
218 - || strpos($lower, '"code":"server_error"') !== false)) {
219 - return true;
220 - }
221 - if ($hint === 'anthropic' && (strpos($lower, '"type":"overloaded_error"') !== false
222 - || strpos($lower, 'overloaded_error') !== false)) {
223 - return true;
224 - }
225 - if (($hint === 'xai' || $hint === 'grok') && strpos($lower, 'rate limit') !== false) {
226 - return true;
227 - }
228 -
229 - return false;
230 -}
231 -
232 -/**
233 - * Whether transient-error auto-retry is enabled in admin settings.
234 - * Default true unless explicitly set to '0'. Used by both wp_remote_post
235 - * (mxchat_provider_call_with_retry) and cURL streaming paths.
236 - */
237 -private function mxchat_retry_enabled() {
238 - $opts = is_array($this->options ?? null) ? $this->options : array();
239 - return !isset($opts['auto_retry_on_transient_error']) ||
240 - (string) $opts['auto_retry_on_transient_error'] !== '0';
241 -}
242 -
243 -private function setup_streaming_headers() {
244 - if ($this->streaming_headers_sent || headers_sent()) {
245 - return false;
246 - }
247 -
248 - // Disable output buffering
249 - while (ob_get_level()) {
250 - ob_end_flush();
251 - }
252 -
253 - // Set headers for SSE
254 - header('Content-Type: text/event-stream');
255 - header('Cache-Control: no-cache');
256 - header('Connection: keep-alive');
257 - header('X-Accel-Buffering: no');
258 -
259 - ob_implicit_flush(true);
260 - flush();
261 -
262 - $this->streaming_headers_sent = true;
263 - return true;
264 -}
265 -
266 -/**
267 - * Class constructor
268 - */
269 -public function __construct() {
270 - $this->options = get_option('mxchat_options');
271 - $this->prompts_options = get_option('mxchat_prompts_options', array());
272 - $this->chat_count = get_option('mxchat_chat_count', 0);
273 - $this->word_handler = new MXChat_Word_Handler($this->options);
274 -
275 - // Add all action hooks
276 - add_action('wp_enqueue_scripts', array($this, 'mxchat_enqueue_scripts_styles'));
277 - add_action('wp_ajax_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
278 - add_action('wp_ajax_nopriv_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
279 - add_action('wp_ajax_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
280 - add_action('wp_ajax_nopriv_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
281 -
282 - // Add the AJAX actions for checking if the pre-chat message was dismissed
283 - add_action('wp_ajax_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
284 - add_action('wp_ajax_nopriv_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
285 - add_action('wp_ajax_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
286 - add_action('wp_ajax_nopriv_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
287 - add_action('wp_ajax_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
288 - add_action('wp_ajax_nopriv_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
289 -
290 - // Add REST API routes registration
291 - add_action('rest_api_init', array($this, 'register_routes'));
292 - add_action('wp_ajax_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
293 - add_action('wp_ajax_nopriv_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
294 -
295 - // Rate limit action - notice we removed the old schedule setup
296 - add_action('mxchat_reset_rate_limits', array($this, 'mxchat_reset_rate_limits'));
297 -
298 - // File upload and handling actions
299 - add_action('wp_ajax_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
300 - add_action('wp_ajax_nopriv_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
301 - add_action('wp_ajax_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
302 - add_action('wp_ajax_nopriv_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
303 -
304 - // Word document handling actions
305 - add_action('wp_ajax_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
306 - add_action('wp_ajax_nopriv_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
307 - add_action('wp_ajax_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
308 - add_action('wp_ajax_nopriv_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
309 - add_action('wp_ajax_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
310 - add_action('wp_ajax_nopriv_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
311 -
312 - // Email handling actions
313 - add_action('wp_ajax_nopriv_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
314 - add_action('wp_ajax_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
315 - add_action('wp_ajax_nopriv_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
316 - add_action('wp_ajax_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
317 -
318 - add_action('wp_ajax_mxchat_stream_chat', array($this, 'mxchat_handle_chat_request'));
319 - add_action('wp_ajax_nopriv_mxchat_stream_chat', array($this, 'mxchat_handle_chat_request'));
320 -
321 - // Testing panel AJAX actions
322 - add_action('wp_ajax_mxchat_get_system_info', array($this, 'mxchat_get_system_info'));
323 - add_action('wp_ajax_mxchat_get_similarity_threshold', array($this, 'mxchat_get_similarity_threshold'));
324 - add_action('wp_ajax_mxchat_get_kb_status', array($this, 'mxchat_get_kb_status'));
325 - add_action('wp_ajax_mxchat_start_fresh_session', array($this, 'mxchat_start_fresh_session'));
326 - // Add to your existing constructor, in the section with other AJAX actions:
327 - add_action('wp_ajax_mxchat_track_url_click', array($this, 'mxchat_track_url_click'));
328 - add_action('wp_ajax_nopriv_mxchat_track_url_click', array($this, 'mxchat_track_url_click'));
329 - add_action('wp_ajax_mxchat_track_originating_page', array($this, 'mxchat_track_originating_page'));
330 - add_action('wp_ajax_nopriv_mxchat_track_originating_page', array($this, 'mxchat_track_originating_page'));
331 - // Add chat mode checking actions
332 - add_action('wp_ajax_mxchat_get_current_chat_mode', array($this, 'mxchat_get_current_chat_mode'));
333 - add_action('wp_ajax_nopriv_mxchat_get_current_chat_mode', array($this, 'mxchat_get_current_chat_mode'));
334 -
335 - // Nonce refresh for page-cache compatibility (WP Rocket, LiteSpeed, etc.)
336 - add_action('wp_ajax_mxchat_refresh_nonce', array($this, 'mxchat_refresh_nonce'));
337 - add_action('wp_ajax_nopriv_mxchat_refresh_nonce', array($this, 'mxchat_refresh_nonce'));
338 -
339 - // Auto-email transcript action
340 - add_action('mxchat_send_delayed_transcript', array($this, 'mxchat_send_delayed_transcript'), 10, 1);
341 -
342 - add_filter('mxchat_check_actions_only', array($this, 'check_actions_for_addons'), 10, 4);
343 -
344 -
345 -}
346 -
347 -/**
348 - * Return a fresh nonce so cached pages can replace the stale one.
349 - * With `with_settings`, also returns the current behavior-gate settings so
350 - * the widget can correct stale inline-localized values (plan-32db95).
351 - */
352 -public function mxchat_refresh_nonce() {
353 - nocache_headers();
354 - $payload = array('nonce' => wp_create_nonce('mxchat_chat_nonce'));
355 - if (!empty($_REQUEST['with_settings'])) {
356 - $payload['settings'] = $this->get_dynamic_widget_settings(true);
357 - }
358 - wp_send_json_success($payload);
359 -}
360 -
361 -/**
362 - * Behavior-gate settings the widget may re-fetch at runtime (plan-32db95).
363 - *
364 - * Every widget setting ships inline in page HTML via wp_localize_script, so
365 - * full-page caches (host caches, WP Rocket, LiteSpeed, W3TC, FlyingPress,
366 - * WP Super Cache, Cloudflare APO, the browser itself) keep serving a stale
367 - * snapshot after an admin changes a setting. MxChat_Cache_Purge clears the
368 - * caches PHP can reach; this payload covers the rest — the widget requests
369 - * it on first open (via the nonce-refresh endpoints) and merges it over
370 - * `mxchatChat`, the same distrust-cached-HTML pattern the 3.2.7 per-request
371 - * nonce uses.
372 - *
373 - * Behavior gates + labels ONLY — colors stay inline because they're also
374 - * server-inline-styled, and a runtime swap would visibly flash.
375 - *
376 - * Both wp_localize_script blocks merge this exact array, so the inline and
377 - * refreshed payloads cannot drift.
378 - *
379 - * @param bool $fresh Re-read mxchat_options from the DB (endpoint paths)
380 - * instead of trusting the instance copy.
381 - * @return array
382 - */
383 -public function get_dynamic_widget_settings($fresh = false) {
384 - $options = $fresh ? get_option('mxchat_options', array()) : $this->options;
385 - if (!is_array($options)) {
386 - $options = array();
387 - }
388 - return array(
389 - 'model' => isset($options['model']) ? $options['model'] : 'gpt-5.1-chat-latest',
390 - 'enable_streaming_toggle' => isset($options['enable_streaming_toggle']) ? $options['enable_streaming_toggle'] : 'on',
391 - 'rate_limit_message' => $options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
392 - 'chat_toolbar_toggle' => $options['chat_toolbar_toggle'] ?? 'off',
393 - 'print_button_enabled' => $options['print_button_enabled'] ?? 'on',
394 - 'print_button_label' => esc_html__('Download Transcript', 'mxchat'),
395 - // "Start new chat" header-menu item (plan ac2e81). Default OFF.
396 - 'reset_chat_enabled' => $options['reset_chat_enabled'] ?? 'off',
397 - 'reset_chat_label' => !empty($options['reset_chat_label']) ? esc_html($options['reset_chat_label']) : esc_html__('Start new chat', 'mxchat'),
398 - 'reset_chat_confirm' => esc_html__('Start a new chat? This clears the current conversation.', 'mxchat'),
399 - 'stop_button_label' => esc_html__('Stop response', 'mxchat'),
400 - 'print_header_title' => esc_html(get_bloginfo('name')) . ' — ' . esc_html__('Chat transcript', 'mxchat'),
401 - // Emit 'on'/'off' STRINGS, never booleans: wp_localize_script casts
402 - // scalars to string, and (string) false === '' — which the widget's
403 - // old gate read as enabled (plan-4bba64). The filter keeps its
404 - // boolean contract; only the emitted value is stringified.
405 - 'satisfaction_rating_enabled' => apply_filters(
406 - 'mxchat_satisfaction_rating_enabled',
407 - ($options['satisfaction_rating_enabled'] ?? 'off') === 'on'
408 - ) ? 'on' : 'off',
409 - 'satisfaction_rating_idle_seconds' => max(5, min(600, intval($options['satisfaction_rating_idle_seconds'] ?? 60))),
410 - 'satisfaction_rating_copy' => array(
411 - 'question' => !empty($options['satisfaction_rating_question']) ? esc_html($options['satisfaction_rating_question']) : esc_html__('Was this helpful?', 'mxchat'),
412 - 'helpful' => esc_html__('Helpful', 'mxchat'),
413 - 'not_helpful' => esc_html__('Not helpful', 'mxchat'),
414 - 'dismiss' => esc_html__('Dismiss', 'mxchat'),
415 - 'thanks' => !empty($options['satisfaction_rating_thanks']) ? esc_html($options['satisfaction_rating_thanks']) : esc_html__('Thanks! Anything we should improve? (optional)', 'mxchat'),
416 - 'placeholder' => !empty($options['satisfaction_rating_placeholder']) ? esc_html($options['satisfaction_rating_placeholder']) : esc_html__('Tell us what could be better…', 'mxchat'),
417 - 'send' => esc_html__('Send', 'mxchat'),
418 - 'skip' => esc_html__('Skip', 'mxchat'),
419 - 'saved' => !empty($options['satisfaction_rating_saved']) ? esc_html($options['satisfaction_rating_saved']) : esc_html__('Thanks for the feedback.', 'mxchat'),
420 - ),
421 - );
422 -}
423 -
424 -// In your core plugin's check_actions_for_addons method:
425 -public function check_actions_for_addons($default, $message, $user_id, $session_id) {
426 - //error_log('MxChat Core: check_actions_for_addons called with message: ' . $message);
427 -
428 - $result = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
429 -
430 - //error_log('MxChat Core: Intent check result = ' . ($result === false ? 'false' : 'true'));
431 -
432 - return $result;
433 -}
434 -
435 - private function mxchat_increment_chat_count() {
436 - $chat_count = get_option('mxchat_chat_count', 0);
437 - $chat_count++;
438 - update_option('mxchat_chat_count', $chat_count);
439 - }
440 -
441 -function mxchat_fetch_conversation_history() {
442 - if (empty($_POST['session_id'])) {
443 - wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
444 - wp_die();
445 - }
446 -
447 - $session_id = sanitize_text_field($_POST['session_id']);
448 -
449 - // SECURITY FIX: Verify session ownership before retrieving data
450 - // If IP/user changed, signal frontend to reset session instead of blocking
451 - $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
452 -
453 - // Check if this session has an owner recorded
454 - $session_owner = get_option("mxchat_session_owner_{$session_id}");
455 -
456 - // Update session owner if it changed (e.g. IP changed due to network switch)
457 - // The session ID itself is the authentication — if the client has it, they own it
458 - if (!$session_owner || $session_owner !== $current_user_identifier) {
459 - update_option("mxchat_session_owner_{$session_id}", $current_user_identifier, 'no');
460 - }
461 -
462 - $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history
463 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai'); // Get current chat mode
464 -
465 - if (empty($history)) {
466 - // Even if history is empty, return the chat mode
467 - wp_send_json_success([
468 - 'conversation' => [],
469 - 'chat_mode' => $chat_mode
470 - ]);
471 - wp_die();
472 - }
473 -
474 - wp_send_json_success([
475 - 'conversation' => $history,
476 - 'chat_mode' => $chat_mode
477 - ]);
478 - wp_die();
479 -}
480 -private function mxchat_fetch_conversation_history_for_ai($session_id, $session_start_timestamp = 0) {
481 - $history = get_option("mxchat_history_{$session_id}", []);
482 -
483 - // Check persistence setting - when OFF, only include messages from current page load
484 - $options = get_option('mxchat_options', []);
485 - $persistence_enabled = isset($options['chat_persistence_toggle']) && $options['chat_persistence_toggle'] === 'on';
486 -
487 - // Filter history when persistence is OFF to match what the user sees
488 - if (!$persistence_enabled && $session_start_timestamp > 0) {
489 - $history = array_filter($history, function($entry) use ($session_start_timestamp) {
490 - // Include messages from this page load onwards
491 - return isset($entry['timestamp']) && $entry['timestamp'] >= $session_start_timestamp;
492 - });
493 - // Re-index array after filtering
494 - $history = array_values($history);
495 - }
496 -
497 - $formatted_history = [];
498 -
499 - // Adjusted for code-heavy conversations
500 - $max_tokens = 120000; // Context window size
501 - $reserved_tokens = 5000; // Space for system prompts + current query
502 - $current_token_count = 0;
503 -
504 - // Allowed HTML tags for content sanitization
505 - $allowed_tags = [
506 - 'pre' => ['class' => true],
507 - 'code' => ['class' => true],
508 - 'span' => ['class' => true],
509 - 'div' => ['class' => true],
510 - 'strong' => [],
511 - 'em' => []
512 - ];
513 -
514 - foreach (array_reverse($history) as $entry) {
515 - // Preserve code blocks while sanitizing other HTML
516 - $clean_content = wp_kses($entry['content'], $allowed_tags);
517 -
518 - // Detect code blocks in content
519 - $has_code = false;
520 -// Replace the HTML check with:
521 -// Allow messages that contain code blocks or are plain text
522 -if (strpos($clean_content, '<pre') === false &&
523 - strpos($clean_content, '<code') === false &&
524 - $clean_content !== strip_tags($entry['content'])) {
525 - continue;
526 -}
527 -
528 - // Skip entries that lost significant content during sanitization
529 - if (!$has_code && $clean_content !== strip_tags($entry['content'])) {
530 - continue;
531 - }
532 -
533 - // More accurate token estimation (1 token ≈ 4 characters)
534 - $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
535 -
536 - // Check token budget with the new estimate
537 - if (($current_token_count + $token_estimate + $reserved_tokens) > $max_tokens) {
538 - // Try to fit partial content if it's the first entry
539 - if (empty($formatted_history)) {
540 - $clean_content = mb_substr($clean_content, 0, ($max_tokens - $reserved_tokens) * 4);
541 - $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
542 - } else {
543 - break;
544 - }
545 - }
546 -
547 - // Add to formatted history
548 - $formatted_history[] = [
549 - 'role' => $entry['role'],
550 - 'content' => $clean_content
551 - ];
552 -
553 - $current_token_count += $token_estimate;
554 - }
555 -
556 - // Reverse back to maintain chronological order
557 - $formatted_history = array_reverse($formatted_history);
558 -
559 - // Add system message about code context
560 - array_unshift($formatted_history, [
561 - 'role' => 'system',
562 - 'content' => 'Preserved code blocks are marked with [CODE BLOCK PRESERVED]. '
563 - . 'Maintain formatting and syntax highlighting when referencing code.'
564 - ]);
565 -
566 - return $formatted_history;
567 -}
568 -
569 -public function register_routes() {
570 - //error_log(esc_html__('Registering MxChat REST routes', 'mxchat'));
571 -
572 - // Per-request chat-send nonce endpoint — issues a fresh nonce on demand
573 - // so the chat widget never depends on a stale nonce embedded in cached HTML.
574 - // Public (no auth), rate-limited (1 call / IP / second via a transient).
575 - register_rest_route('mxchat/v1', '/nonce', [
576 - 'methods' => 'GET',
577 - 'callback' => [$this, 'mxchat_issue_chat_send_nonce'],
578 - 'permission_callback' => '__return_true',
579 - ]);
580 -
581 - register_rest_route('mxchat/v1', '/stream', [
582 - 'methods' => 'GET',
583 - 'callback' => [$this, 'mxchat_stream_events'],
584 - 'permission_callback' => [$this, 'verify_chat_session'],
585 - ]);
586 -
587 - register_rest_route('mxchat/v1', '/agent-response', [
588 - 'methods' => 'POST',
589 - 'callback' => [$this, 'mxchat_handle_agent_response'],
590 - 'permission_callback' => [$this, 'verify_slack_request'],
591 - ]);
592 -
593 - register_rest_route('mxchat/v1', '/slack-interaction', [
594 - 'methods' => 'POST',
595 - 'callback' => [$this, 'handle_slack_interaction'],
596 - 'permission_callback' => [$this, 'verify_slack_request'],
597 - ]);
598 -
599 - register_rest_route('mxchat/v1', '/slack-messages', [
600 - 'methods' => 'POST',
601 - 'callback' => [$this, 'handle_slack_messages'],
602 - 'permission_callback' => [$this, 'verify_slack_request'],
603 - ]);
604 -
605 - // Telegram webhook endpoint
606 - register_rest_route('mxchat/v1', '/telegram-webhook', [
607 - 'methods' => 'POST',
608 - 'callback' => [$this, 'handle_telegram_webhook'],
609 - 'permission_callback' => [$this, 'verify_telegram_request'],
610 - ]);
611 -
612 - //error_log(esc_html__('MxChat REST routes registered', 'mxchat'));
613 -}
614 -
615 -/**
616 - * Issue a fresh per-request nonce for chat-send. Returned to the widget which
617 - * caches it for the session and includes it on every chat-send / stream-send /
618 - * upload call. By moving the nonce out of inline `window.mxchatChat = {...}` HTML
619 - * we eliminate the entire class of "first-message Access denied" failures that
620 - * plague WP installs behind a full-page cache (WP Rocket, LiteSpeed, FlyingPress,
621 - * W3 Total Cache, Cloudflare APO) — the nonce is never cached because it never
622 - * lives in the HTML body.
623 - *
624 - * Public endpoint. Rate-limited to 1 call / IP / 1s via a transient so a single
625 - * client browser can't be used to flood the nonce-issuance path.
626 - *
627 - * Nonce action: `mxchat_chat_send` (new). The chat-send AJAX handlers accept
628 - * BOTH this action AND the legacy `mxchat_chat_nonce` action for a 30-day
629 - * backwards-compat window so cached pages still in users' browsers don't break
630 - * mid-session.
631 - *
632 - * @since 3.2.7
633 - */
634 -public function mxchat_issue_chat_send_nonce(WP_REST_Request $request) {
635 - $ip = '';
636 - if (!empty($_SERVER['REMOTE_ADDR'])) {
637 - $ip = preg_replace('#[^0-9a-fA-F:\.]#', '', wp_unslash((string) $_SERVER['REMOTE_ADDR']));
638 - }
639 - if ($ip !== '') {
640 - // Best-effort rate limit. WP transients with sub-second TTL are racy
641 - // (parallel bursts can squeak through before set_transient completes);
642 - // we use 2s to make the gate slightly more reliable. Real production
643 - // rate-limiting at sub-second granularity needs Redis or DB row locks
644 - // — out of scope for this endpoint, which is already cheap.
645 - $key = 'mxchat_nonce_rl_' . md5($ip);
646 - if (get_transient($key)) {
647 - return new WP_REST_Response(array(
648 - 'error' => 'rate_limited',
649 - 'message' => __('Too many nonce requests. Try again shortly.', 'mxchat'),
650 - ), 429);
651 - }
652 - set_transient($key, 1, 2);
653 - }
654 -
655 - // The widget calls this endpoint without an X-WP-Nonce header, so WordPress does not
656 - // honor the auth cookie and the request runs as uid=0 even for logged-in users. That
657 - // makes wp_create_nonce() bind the nonce to uid=0, which then fails wp_verify_nonce()
658 - // at admin-ajax (which runs as the real uid) -> logged-in users get a 403 on upload.
659 - // Resolve the real user from the logged_in cookie so the nonce binds to the correct uid.
660 - if ( ! is_user_logged_in() ) {
661 - $maybe_uid = wp_validate_auth_cookie( '', 'logged_in' );
662 - if ( $maybe_uid ) {
663 - wp_set_current_user( $maybe_uid );
664 - }
665 - }
666 -
667 - $payload = array(
668 - 'nonce' => wp_create_nonce('mxchat_chat_send'),
669 - 'expires_in' => 86400, // WP nonces live 24h; widget caches for 12h conservatively.
670 - );
671 -
672 - // plan-32db95: the widget's first-open refresh asks for current behavior
673 - // settings in the same round-trip, so stale inline-localized values on
674 - // cached pages get corrected without a second request. All values in
675 - // this payload already ship in public page HTML — nothing sensitive.
676 - if ($request->get_param('with_settings')) {
677 - $payload['settings'] = $this->get_dynamic_widget_settings(true);
678 - }
679 -
680 - return new WP_REST_Response($payload, 200);
681 -}
682 -
683 -/**
684 - * Verify a chat-send nonce. Accepts BOTH the new `mxchat_chat_send` action
685 - * (issued by /wp-json/mxchat/v1/nonce) AND the legacy `mxchat_chat_nonce`
686 - * action (inline-localized in older cached HTML). The legacy acceptance is
687 - * a 30-day backwards-compat window — to be removed in a follow-up release
688 - * after 2026-06-27.
689 - *
690 - * @param string $posted_nonce
691 - * @return bool
692 - */
693 -public static function mxchat_verify_chat_send_nonce($posted_nonce) {
694 - if (!is_string($posted_nonce) || $posted_nonce === '') {
695 - return false;
696 - }
697 - return (bool) wp_verify_nonce($posted_nonce, 'mxchat_chat_send')
698 - || (bool) wp_verify_nonce($posted_nonce, 'mxchat_chat_nonce');
699 -}
700 -
701 -/**
702 - * Verify valid chat session
703 - */
704 -public function verify_chat_session($request) {
705 - $session_id = $request->get_param('session_id');
706 - if (empty($session_id)) {
707 - //error_log(esc_html__('Empty session ID in chat request', 'mxchat'));
708 - return false;
709 - }
710 -
711 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
712 - return $chat_mode === 'agent';
713 -}
714 -
715 -/**
716 - * Verify request is coming from Slack.
717 - *
718 - * @param WP_REST_Request $request
719 - * @return bool True if valid, false otherwise.
720 - */
721 -public function verify_slack_request($request) {
722 - // Get the Slack signing secret from your plugin options
723 - $valid_key = $this->options['live_agent_secret_key'] ?? '';
724 -
725 - if (empty($valid_key)) {
726 - //error_log(esc_html__('Slack signing secret not configured', 'mxchat'));
727 - return false;
728 - }
729 -
730 - $timestamp = $request->get_header('X-Slack-Request-Timestamp');
731 - $slack_signature = $request->get_header('X-Slack-Signature');
732 -
733 - // Verify timestamp to prevent replay attacks
734 - if (abs(time() - intval($timestamp)) > 300) {
735 - //error_log(esc_html__('Slack request timestamp too old', 'mxchat'));
736 - return false;
737 - }
738 -
739 - // Get raw request body from the WP_REST_Request object
740 - // (php://input may already be consumed by WordPress at this point)
741 - $request_body = $request->get_body();
742 -
743 - // Create the signature base string
744 - $sig_basestring = "v0:{$timestamp}:{$request_body}";
745 -
746 - // Calculate expected signature
747 - $my_signature = 'v0=' . hash_hmac('sha256', $sig_basestring, $valid_key);
748 -
749 - // Compare signatures
750 - return hash_equals($my_signature, $slack_signature);
751 -}
752 -
753 -/**
754 - * Verify request is coming from Telegram.
755 - *
756 - * @param WP_REST_Request $request
757 - * @return bool True if valid, false otherwise.
758 - */
759 -public function verify_telegram_request($request) {
760 - $secret_token = $this->options['telegram_webhook_secret'] ?? '';
761 -
762 - //error_log('[MxChat Telegram DEBUG] verify_telegram_request called');
763 - //error_log('[MxChat Telegram DEBUG] Stored secret: ' . (empty($secret_token) ? 'EMPTY' : substr($secret_token, 0, 10) . '...'));
764 -
765 - if (empty($secret_token)) {
766 - // No secret configured (legacy setup). Do NOT fail open to the whole
767 - // internet — that lets an unauthenticated caller write agent-branded
768 - // messages. Fall back to verifying the request originates from
769 - // Telegram's published webhook IP ranges so existing no-secret installs
770 - // keep working while an arbitrary-internet caller is blocked. Setting a
771 - // real secret (see the admin notice) is the recommended path.
772 - // (plan-0c17b5)
773 - $peer = isset($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : '';
774 - if ($this->mxchat_ip_in_telegram_ranges($peer)) {
775 - return true;
776 - }
777 - error_log('MxChat: Telegram webhook has no secret configured and the request '
778 - . 'is not from a Telegram IP range; rejected. Set a webhook secret to secure it.');
779 - return false;
780 - }
781 -
782 - // Telegram sends the secret token in the X-Telegram-Bot-Api-Secret-Token header
783 - $request_token = $request->get_header('X-Telegram-Bot-Api-Secret-Token');
784 -
785 - //error_log('[MxChat Telegram DEBUG] Request token: ' . (empty($request_token) ? 'EMPTY' : substr($request_token, 0, 10) . '...'));
786 -
787 - if (empty($request_token)) {
788 - //error_log('[MxChat Telegram DEBUG] Request rejected: No token in header');
789 - return false;
790 - }
791 -
792 - // Timing-safe comparison
793 - $result = hash_equals($secret_token, $request_token);
794 - //error_log('[MxChat Telegram DEBUG] Token comparison result: ' . ($result ? 'MATCH' : 'MISMATCH'));
795 - return $result;
796 -}
797 -
798 -/**
799 - * Whether $ip falls within Telegram's published webhook IPv4 ranges
800 - * (149.154.160.0/20 and 91.108.4.0/22). Used as an authenticity fallback for
801 - * the Telegram webhook when no secret token is configured, so a legacy
802 - * no-secret install keeps working without failing open to the entire internet.
803 - *
804 - * Uses the real TCP peer (REMOTE_ADDR); a spoofable X-Forwarded-For is NOT
805 - * consulted. Behind a reverse proxy / CDN that rewrites REMOTE_ADDR this may
806 - * not match — which is exactly why configuring a real webhook secret is the
807 - * recommended path. (plan-0c17b5)
808 - *
809 - * @param string $ip Candidate IPv4 address.
810 - * @return bool
811 - */
812 -private function mxchat_ip_in_telegram_ranges($ip) {
813 - if (!is_string($ip) || $ip === '' || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
814 - return false;
815 - }
816 - $ip_long = ip2long($ip);
817 - if ($ip_long === false) {
818 - return false;
819 - }
820 - $ranges = array(
821 - array('149.154.160.0', 20),
822 - array('91.108.4.0', 22),
823 - );
824 - foreach ($ranges as $range) {
825 - $subnet_long = ip2long($range[0]);
826 - if ($subnet_long === false) {
827 - continue;
828 - }
829 - $mask = (0xFFFFFFFF << (32 - $range[1])) & 0xFFFFFFFF;
830 - if (($ip_long & $mask) === ($subnet_long & $mask)) {
831 - return true;
832 - }
833 - }
834 - return false;
835 -}
836 -
837 -public function mxchat_stream_events(WP_REST_Request $request) {
838 - header('Content-Type: text/event-stream');
839 - header('Cache-Control: no-cache');
840 - header('Connection: keep-alive');
841 -
842 - $session_id = sanitize_text_field($request->get_param('session_id'));
843 - $last_seen_id = sanitize_text_field($request->get_param('last_seen_id')) ?: '';
844 -
845 - if (empty($session_id)) {
846 - echo esc_html__("event: error\ndata: ", 'mxchat') . esc_html__('Missing session_id', 'mxchat') . "\n\n";
847 - flush();
848 - exit;
849 - }
850 -
851 - $history = get_option("mxchat_history_{$session_id}", []);
852 -
853 - // Filter only new messages
854 - $new_messages = array_filter($history, function ($message) use ($last_seen_id) {
855 - return !empty($message['id']) && $message['id'] > $last_seen_id;
856 - });
857 -
858 - // Send new messages if available
859 - if (!empty($new_messages)) {
860 - echo esc_html__("event: newMessages\ndata: ", 'mxchat') . json_encode(array_values($new_messages)) . "\n\n";
861 - } else {
862 - // Keep the connection alive
863 - echo esc_html__("event: keepAlive\ndata: ", 'mxchat') . "{}\n\n";
864 - }
865 - flush();
866 - exit;
867 -}
868 -
869 -
870 -
871 -
872 -private function mxchat_save_chat_message($session_id, $role, $message, $originating_page = null, $rag_context = null) {
873 - global $wpdb;
874 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
875 - //error_log("[DEBUG] mxchat_save_chat_message -> START for session_id: {$session_id}, role: {$role}");
876 -
877 - // Check if this is the first message in a new session (before any other database operations)
878 - $is_new_session = false;
879 - if ($role === 'user') { // Only check for user messages, not bot responses
880 - $existing_messages = $wpdb->get_var($wpdb->prepare(
881 - "SELECT COUNT(*) FROM $table_name WHERE session_id = %s",
882 - $session_id
883 - ));
884 - $is_new_session = ($existing_messages == 0);
885 -
886 - // Log for debugging
887 - if ($is_new_session) {
888 - //error_log("[DEBUG] This is a NEW session - first message");
889 - }
890 - }
891 -
892 - // SECURITY FIX: Set session ownership for new sessions
893 - if ($is_new_session && $role === 'user') {
894 - $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
895 - $session_owner_key = "mxchat_session_owner_{$session_id}";
896 -
897 - // Only set ownership if not already set
898 - if (!get_option($session_owner_key)) {
899 - update_option($session_owner_key, $current_user_identifier, 'no');
900 - //error_log("[DEBUG] Set session ownership for {$session_id} to {$current_user_identifier}");
901 - }
902 - }
903 -
904 - // 1) Extract agent name if present
905 - $agent_name = '';
906 - if (preg_match('/^Agent: (.*?) - /', $message, $matches)) {
907 - $agent_name = $matches[1];
908 - $message = str_replace("Agent: $agent_name - ", '', $message);
909 - $session_meta_key = "mxchat_agent_name_{$session_id}";
910 - if (empty(get_option($session_meta_key))) {
911 - update_option($session_meta_key, $agent_name);
912 - //error_log("[DEBUG] mxchat_save_chat_message -> Stored agent_name in option: {$session_meta_key} => {$agent_name}");
913 - }
914 - }
915 -
916 - // 2) Generate unique message_id
917 - $message_id = uniqid();
918 - //error_log("[DEBUG] mxchat_save_chat_message -> Generated message_id: {$message_id}");
919 -
920 - // 3) Determine user_id
921 - $user_id = is_user_logged_in() ? get_current_user_id() : 0;
922 -
923 - // 4) Determine user_identifier
924 - $user_identifier = $agent_name
925 - ? $agent_name
926 - : MxChat_User::mxchat_get_user_identifier();
927 -
928 - // 5) Determine displayed_name
929 - $user_email = MxChat_User::mxchat_get_user_email();
930 - $displayed_name = $agent_name ? $agent_name : ($user_email ?: $user_identifier);
931 -
932 - // 6) Check for a saved email in wp_options
933 - $email_option_key = "mxchat_email_{$session_id}";
934 - $saved_email = get_option($email_option_key);
935 - //error_log("[DEBUG] mxchat_save_chat_message -> Checking wp_options for email_option_key: {$email_option_key}, found: {$saved_email}");
936 -
937 - // Check for a saved name in wp_options
938 - $name_option_key = "mxchat_name_{$session_id}";
939 - $saved_name = get_option($name_option_key);
940 - //error_log("[DEBUG] mxchat_save_chat_message -> Checking wp_options for name_option_key: {$name_option_key}, found: {$saved_name}");
941 -
942 - // If found, update DB user_email and user_name
943 - if ($saved_email || $saved_name) {
944 - $update_data = [];
945 - if ($saved_email) {
946 - $update_data['user_email'] = $saved_email;
947 - }
948 - if ($saved_name) {
949 - $update_data['user_name'] = $saved_name;
950 - }
951 -
952 - if (!empty($update_data)) {
953 - $update_res = $wpdb->update(
954 - $table_name,
955 - $update_data,
956 - ['session_id' => $session_id],
957 - array_fill(0, count($update_data), '%s'),
958 - ['%s']
959 - );
960 - //error_log("[DEBUG] mxchat_save_chat_message -> Attempted DB user_email/user_name update for session_id {$session_id}. update_res: {$update_res}");
961 - }
962 - }
963 -
964 - // 7) Save to session history in wp_options
965 - $history_key = "mxchat_history_{$session_id}";
966 - $history = get_option($history_key, []);
967 - $history[] = [
968 - 'id' => $message_id,
969 - 'role' => $role,
970 - 'content' => $message,
971 - 'timestamp' => round(microtime(true) * 1000),
972 - 'agent_name' => $displayed_name,
973 - ];
974 - update_option($history_key, $history, 'no');
975 - //error_log("[DEBUG] mxchat_save_chat_message -> Updated session history in option: {$history_key}");
976 -
977 - // 8) Save the message to DB (INSERT)
978 - $insert_data = [
979 - 'user_id' => $user_id,
980 - 'user_identifier'=> $user_identifier,
981 - 'user_email' => $saved_email ?: $user_email,
982 - 'user_name' => $saved_name ?: '', // Add name to insert data
983 - 'session_id' => $session_id,
984 - 'role' => $role,
985 - 'message' => $message,
986 - 'timestamp' => current_time('mysql', 1),
987 - ];
988 -
989 - // IMPROVED: Handle originating page data
990 - $columns_exist = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'");
991 -
992 - if ($columns_exist) {
993 - if ($is_new_session && $role === 'user') {
994 - // For the first user message, set originating page data
995 -
996 - // First check if we have it from the parameter
997 - if ($originating_page && !empty($originating_page['url'])) {
998 - $insert_data['originating_page_url'] = $originating_page['url'];
999 - $insert_data['originating_page_title'] = $originating_page['title'] ?? '';
1000 -
1001 - //error_log("[DEBUG] Setting originating page from parameter: " . $originating_page['url']);
1002 - }
1003 - // Otherwise check if it's stored in the instance property
1004 - else if (isset($this->pending_originating_page) && !empty($this->pending_originating_page['url'])) {
1005 - $insert_data['originating_page_url'] = $this->pending_originating_page['url'];
1006 - $insert_data['originating_page_title'] = $this->pending_originating_page['title'] ?? '';
1007 -
1008 - //error_log("[DEBUG] Setting originating page from pending_originating_page: " . $this->pending_originating_page['url']);
1009 -
1010 - // Clear after using (= null, not unset(): unset() undeclares the property
1011 - // and the next assignment recreates it dynamic, re-triggering the PHP 8.2 deprecation)
1012 - $this->pending_originating_page = null;
1013 - }
1014 - // Fallback to HTTP_REFERER if nothing else is available
1015 - else if (isset($_SERVER['HTTP_REFERER'])) {
1016 - $referer_url = esc_url_raw($_SERVER['HTTP_REFERER']);
1017 - $insert_data['originating_page_url'] = $referer_url;
1018 -
1019 - // Generate title from URL
1020 - $parsed_url = parse_url($referer_url);
1021 - $path = isset($parsed_url['path']) ? trim($parsed_url['path'], '/') : '';
1022 -
1023 - if (empty($path) || $path === 'index.php' || $path === 'index.html') {
1024 - $insert_data['originating_page_title'] = 'Homepage';
1025 - } else {
1026 - $title = str_replace(['-', '_', '/', '.php', '.html'], ' ', $path);
1027 - $insert_data['originating_page_title'] = ucwords(trim($title));
1028 - }
1029 -
1030 - //error_log("[DEBUG] Setting originating page from HTTP_REFERER: " . $referer_url);
1031 - }
1032 -
1033 - // Store for this session so all messages have the same originating page
1034 - if (!empty($insert_data['originating_page_url'])) {
1035 - update_option("mxchat_originating_page_{$session_id}", [
1036 - 'url' => $insert_data['originating_page_url'],
1037 - 'title' => $insert_data['originating_page_title']
1038 - ], 'no');
1039 - }
1040 - } else {
1041 - // For subsequent messages in the session, use the stored originating page
1042 - $stored_originating = get_option("mxchat_originating_page_{$session_id}");
1043 - if ($stored_originating && !empty($stored_originating['url'])) {
1044 - $insert_data['originating_page_url'] = $stored_originating['url'];
1045 - $insert_data['originating_page_title'] = $stored_originating['title'] ?? '';
1046 - }
1047 - }
1048 - }
1049 -
1050 - // Add RAG context if provided (for bot messages)
1051 - if ($rag_context !== null && $role === 'bot') {
1052 - $rag_context_column_exists = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'rag_context'");
1053 - if ($rag_context_column_exists) {
1054 - $insert_data['rag_context'] = is_array($rag_context) ? wp_json_encode($rag_context) : $rag_context;
1055 - }
1056 - }
1057 -
1058 - $wpdb->insert($table_name, $insert_data);
1059 - //error_log("[DEBUG] mxchat_save_chat_message -> Inserted message into DB. row_id: {$wpdb->insert_id}, data: " . print_r($insert_data, true));
1060 -
1061 - // 9) Send notification email if this is the first user message in a new session
1062 - if ($wpdb->insert_id && $is_new_session && $role === 'user') {
1063 - $this->send_new_chat_notification($session_id, array(
1064 - 'identifier' => $user_identifier,
1065 - 'email' => $saved_email ?: $user_email,
1066 - 'ip' => $_SERVER['REMOTE_ADDR']
1067 - ));
1068 - }
1069 -
1070 - // 10) Schedule delayed transcript email if enabled and message is from user
1071 - if ($wpdb->insert_id && $role === 'user') {
1072 - $this->schedule_delayed_transcript_email($session_id);
1073 - }
1074 -
1075 - //error_log("[DEBUG] mxchat_save_chat_message -> END for session_id: {$session_id}");
1076 - return $message_id;
1077 -}
1078 -
1079 -private function send_new_chat_notification($session_id, $user_info = array()) {
1080 - $options = get_option('mxchat_transcripts_options');
1081 -
1082 - // Check if notifications are enabled
1083 - if (empty($options['mxchat_enable_notifications'])) {
1084 - return false;
1085 - }
1086 -
1087 - // Get notification email
1088 - $to = !empty($options['mxchat_notification_email']) ?
1089 - $options['mxchat_notification_email'] :
1090 - get_option('admin_email');
1091 -
1092 - if (!is_email($to)) {
1093 - return false;
1094 - }
1095 -
1096 - // Prepare email content
1097 - $subject = sprintf('[%s] New Chat Session Started', get_bloginfo('name'));
1098 -
1099 - $user_identifier = isset($user_info['identifier']) ? $user_info['identifier'] : 'Guest';
1100 - $user_email = isset($user_info['email']) ? $user_info['email'] : 'Not provided';
1101 - $user_ip = isset($user_info['ip']) ? $user_info['ip'] : $_SERVER['REMOTE_ADDR'];
1102 -
1103 - $message = sprintf(
1104 - "A new chat session has started on your website.\n\n" .
1105 - "Session ID: %s\n" .
1106 - "User: %s\n" .
1107 - "Email: %s\n" .
1108 - "IP Address: %s\n" .
1109 - "Time: %s\n\n" .
1110 - "View transcripts: %s",
1111 - $session_id,
1112 - $user_identifier,
1113 - $user_email,
1114 - $user_ip,
1115 - current_time('mysql'),
1116 - admin_url('admin.php?page=mxchat-transcripts')
1117 - );
1118 -
1119 - // Send email
1120 - return wp_mail($to, $subject, $message);
1121 -}
1122 -
1123 -/**
1124 - * Schedule delayed transcript email for a session
1125 - * Reschedules if a new user message is received
1126 - */
1127 -private function schedule_delayed_transcript_email($session_id) {
1128 - $options = get_option('mxchat_transcripts_options');
1129 -
1130 - // Check if auto-email is enabled
1131 - if (empty($options['mxchat_auto_email_transcript_enabled'])) {
1132 - return;
1133 - }
1134 -
1135 - // Get notification email
1136 - $email = !empty($options['mxchat_notification_email']) ?
1137 - $options['mxchat_notification_email'] :
1138 - get_option('admin_email');
1139 -
1140 - if (!is_email($email)) {
1141 - return;
1142 - }
1143 -
1144 - // Get delay in minutes (default 30)
1145 - $delay_minutes = isset($options['mxchat_auto_email_transcript_delay']) ?
1146 - intval($options['mxchat_auto_email_transcript_delay']) : 30;
1147 -
1148 - // Clear any existing scheduled event for this session
1149 - $hook = 'mxchat_send_delayed_transcript';
1150 - $args = array($session_id);
1151 - $timestamp = wp_next_scheduled($hook, $args);
1152 -
1153 - if ($timestamp) {
1154 - wp_unschedule_event($timestamp, $hook, $args);
1155 - }
1156 -
1157 - // Schedule new event
1158 - $schedule_time = time() + ($delay_minutes * 60);
1159 - wp_schedule_single_event($schedule_time, $hook, $args);
1160 -}
1161 -
1162 -/**
1163 - * Check if chat messages contain contact information (email or phone number)
1164 - *
1165 - * @param array $messages Array of message objects with 'message' property
1166 - * @param object|null $session_data Session data object with user_email property
1167 - * @return bool True if contact info found, false otherwise
1168 - */
1169 -private function chat_contains_contact_info($messages, $session_data = null) {
1170 - // Check if session already has a stored email
1171 - if ($session_data && !empty($session_data->user_email)) {
1172 - return true;
1173 - }
1174 -
1175 - // Email regex pattern
1176 - $email_pattern = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/';
1177 -
1178 - // Phone number patterns (covers various formats including international, WhatsApp style)
1179 - // Matches: +1234567890, (123) 456-7890, 123-456-7890, 123.456.7890, 1234567890, +1 234 567 8900, etc.
1180 - $phone_pattern = '/(?:\+?\d{1,3}[-.\s]?)?\(?\d{2,4}\)?[-.\s]?\d{2,4}[-.\s]?\d{2,4}(?:[-.\s]?\d{1,4})?/';
1181 -
1182 - // Only check user messages (not assistant responses)
1183 - foreach ($messages as $msg) {
1184 - if ($msg->role !== 'user') {
1185 - continue;
1186 - }
1187 -
1188 - $message_text = $msg->message;
1189 -
1190 - // Check for email
1191 - if (preg_match($email_pattern, $message_text)) {
1192 - return true;
1193 - }
1194 -
1195 - // Check for phone number (must be at least 7 digits total to avoid false positives)
1196 - if (preg_match($phone_pattern, $message_text, $matches)) {
1197 - // Count actual digits to avoid matching short numbers
1198 - $digits_only = preg_replace('/\D/', '', $matches[0]);
1199 - if (strlen($digits_only) >= 7) {
1200 - return true;
1201 - }
1202 - }
1203 - }
1204 -
1205 - return false;
1206 -}
1207 -
1208 -/**
1209 - * Send the delayed transcript email with .txt attachment
1210 - */
1211 -public function mxchat_send_delayed_transcript($session_id) {
1212 - global $wpdb;
1213 -
1214 - $options = get_option('mxchat_transcripts_options');
1215 -
1216 - // Get notification email
1217 - $to = !empty($options['mxchat_notification_email']) ?
1218 - $options['mxchat_notification_email'] :
1219 - get_option('admin_email');
1220 -
1221 - if (!is_email($to)) {
1222 - return false;
1223 - }
1224 -
1225 - // Get all messages for this session
1226 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1227 - $messages = $wpdb->get_results($wpdb->prepare(
1228 - "SELECT role, message, timestamp FROM {$table_name}
1229 - WHERE session_id = %s
1230 - ORDER BY timestamp ASC",
1231 - $session_id
1232 - ));
1233 -
1234 - if (empty($messages)) {
1235 - return false;
1236 - }
1237 -
1238 - // Get session metadata
1239 - $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1240 - $session_data = $wpdb->get_row($wpdb->prepare(
1241 - "SELECT * FROM {$sessions_table} WHERE session_id = %s",
1242 - $session_id
1243 - ));
1244 -
1245 - // Check if contact info is required and if it's present
1246 - $require_contact = !empty($options['mxchat_auto_email_transcript_require_contact']);
1247 - if ($require_contact && !$this->chat_contains_contact_info($messages, $session_data)) {
1248 - // Contact info required but not found - skip sending
1249 - return false;
1250 - }
1251 -
1252 - // Build transcript content
1253 - $transcript_content = "Chat Transcript\n";
1254 - $transcript_content .= "================\n\n";
1255 - $transcript_content .= "Session ID: " . $session_id . "\n";
1256 -
1257 - if ($session_data) {
1258 - $transcript_content .= "User: " . ($session_data->user_identifier ?: 'Guest') . "\n";
1259 - $transcript_content .= "Email: " . ($session_data->user_email ?: 'Not provided') . "\n";
1260 - $transcript_content .= "Started: " . $session_data->created_at . "\n";
1261 - }
1262 -
1263 - $transcript_content .= "\n" . str_repeat("=", 50) . "\n\n";
1264 -
1265 - // Add messages
1266 - foreach ($messages as $msg) {
1267 - $role_label = ($msg->role === 'user') ? 'User' : 'Assistant';
1268 - $transcript_content .= "[{$msg->timestamp}] {$role_label}:\n";
1269 - $transcript_content .= $msg->message . "\n\n";
1270 - }
1271 -
1272 - // Create temporary file for attachment using WP_Filesystem
1273 - $upload_dir = wp_upload_dir();
1274 - $temp_file = $upload_dir['basedir'] . '/mxchat-transcript-' . $session_id . '.txt';
1275 - global $wp_filesystem;
1276 - if (empty($wp_filesystem)) {
1277 - require_once ABSPATH . 'wp-admin/includes/file.php';
1278 - WP_Filesystem();
1279 - }
1280 - $wp_filesystem->put_contents($temp_file, $transcript_content, FS_CHMOD_FILE);
1281 -
1282 - // Prepare email
1283 - $subject = sprintf('[%s] Chat Transcript - Session %s', get_bloginfo('name'), substr($session_id, 0, 8));
1284 -
1285 - $message = "Please find attached the full chat transcript.\n\n";
1286 - $message .= "Session ID: {$session_id}\n";
1287 -
1288 - if ($session_data) {
1289 - $message .= "User: " . ($session_data->user_identifier ?: 'Guest') . "\n";
1290 - $message .= "Email: " . ($session_data->user_email ?: 'Not provided') . "\n";
1291 - }
1292 -
1293 - $message .= "\nView online: " . admin_url('admin.php?page=mxchat-transcripts');
1294 -
1295 - // Send email with attachment
1296 - $attachments = array($temp_file);
1297 - $result = wp_mail($to, $subject, $message, '', $attachments);
1298 -
1299 - // Clean up temporary file
1300 - if (file_exists($temp_file)) {
1301 - unlink($temp_file);
1302 - }
1303 -
1304 - return $result;
1305 -}
1306 -
1307 -
1308 -
1309 -public function mxchat_handle_save_email_and_response() {
1310 - //error_log('[DEBUG] ---------- mxchat_handle_save_email_and_response START ----------');
1311 - //error_log('DEBUG: POST data: ' . print_r($_POST, true));
1312 -
1313 - nocache_headers();
1314 -
1315 - // Validate nonce
1316 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce($_POST['nonce'])) {
1317 - //error_log(esc_html__('[ERROR] Invalid nonce in mxchat_handle_save_email_and_response', 'mxchat'));
1318 - wp_send_json_error(['message' => esc_html__('Invalid nonce.', 'mxchat')]);
1319 - wp_die();
1320 - }
1321 -
1322 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
1323 - $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
1324 - $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
1325 -
1326 - //error_log("[DEBUG] handle_save_email_and_response -> session_id: {$session_id}, email: {$email}, name: {$name}");
1327 -
1328 - if (empty($session_id) || $session_id === 'null' || empty($email)) {
1329 - //error_log("[ERROR] Missing session_id or email: session_id={$session_id}, email={$email}");
1330 - wp_send_json_error(['message' => esc_html__('Session ID or email is missing.', 'mxchat')]);
1331 - wp_die();
1332 - }
1333 -
1334 - // Validate name if provided (check if name field is enabled and name is required)
1335 - $options = get_option('mxchat_options', []);
1336 - $name_field_enabled = isset($options['enable_name_field']) &&
1337 - ($options['enable_name_field'] === '1' || $options['enable_name_field'] === 'on');
1338 -
1339 - if ($name_field_enabled && (empty($name) || strlen(trim($name)) < 2 || strlen(trim($name)) > 100)) {
1340 - //error_log("[ERROR] Invalid name: {$name} (enabled: {$name_field_enabled})");
1341 - wp_send_json_error(['message' => esc_html__('Name must be between 2 and 100 characters.', 'mxchat')]);
1342 - wp_die();
1343 - }
1344 -
1345 - // 1) Always store email in wp_options
1346 - $email_option_key = "mxchat_email_{$session_id}";
1347 - update_option($email_option_key, $email, 'no');
1348 - //error_log("[DEBUG] handle_save_email_and_response -> updated option: {$email_option_key} => {$email}");
1349 -
1350 - // Store name in wp_options if provided
1351 - if (!empty($name)) {
1352 - $name_option_key = "mxchat_name_{$session_id}";
1353 - update_option($name_option_key, $name, 'no');
1354 - //error_log("[DEBUG] handle_save_email_and_response -> updated option: {$name_option_key} => {$name}");
1355 - }
1356 -
1357 - // 2) (Optional) Also store in DB if a row already exists
1358 - global $wpdb;
1359 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1360 -
1361 - // Make sure we have a valid placeholder in prepare
1362 - $sql = $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", $session_id);
1363 - $session_count = $wpdb->get_var($sql);
1364 -
1365 - //error_log("[DEBUG] handle_save_email_and_response -> session_count for {$session_id}: {$session_count} (SQL: {$sql})");
1366 -
1367 - if ($session_count) {
1368 - // Update both user_email and user_name if row(s) exist
1369 - if (!empty($name)) {
1370 - $update_sql = $wpdb->prepare(
1371 - "UPDATE {$table_name} SET user_email = %s, user_name = %s WHERE session_id = %s",
1372 - $email,
1373 - $name,
1374 - $session_id
1375 - );
1376 - } else {
1377 - $update_sql = $wpdb->prepare(
1378 - "UPDATE {$table_name} SET user_email = %s WHERE session_id = %s",
1379 - $email,
1380 - $session_id
1381 - );
1382 - }
1383 - $wpdb->query($update_sql);
1384 - //error_log("[DEBUG] handle_save_email_and_response -> DB updated: {$update_sql}");
1385 - } else {
1386 - //error_log("[INFO] handle_save_email_and_response -> No DB entry for {$session_id}, so email/name is only in wp_options.");
1387 - }
1388 -
1389 - // Provide success response (same as original)
1390 - $bot_message = __('Thanks for providing your email! You can continue chatting now.', 'mxchat');
1391 - //error_log("[DEBUG] handle_save_email_and_response -> success, returning bot_message: {$bot_message}");
1392 - wp_send_json_success(['message' => $bot_message]);
1393 - wp_die();
1394 -}
1395 -
1396 -public function mxchat_check_email_provided() {
1397 - //error_log('[DEBUG] ---------- mxchat_check_email_provided START ----------');
1398 -
1399 - nocache_headers();
1400 -
1401 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce($_POST['nonce'])) {
1402 - //error_log('[ERROR] Invalid nonce in mxchat_check_email_provided');
1403 - wp_send_json_error(['message' => esc_html__('Invalid nonce', 'mxchat')]);
1404 - }
1405 -
1406 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
1407 - if (empty($session_id) || $session_id === 'null') {
1408 - //error_log('[ERROR] No session ID provided in mxchat_check_email_provided');
1409 - wp_send_json_error(['message' => esc_html__('No session ID provided', 'mxchat')]);
1410 - }
1411 -
1412 - // Check if the user is logged in
1413 - if (is_user_logged_in()) {
1414 - $current_user = wp_get_current_user();
1415 - //error_log("[DEBUG] User is logged in as {$current_user->user_email}");
1416 -
1417 - // Get user's display name for logged in users
1418 - $user_name = !empty($current_user->display_name) ? $current_user->display_name :
1419 - (!empty($current_user->first_name) ? $current_user->first_name : '');
1420 -
1421 - $response_data = ['logged_in' => true, 'email' => $current_user->user_email];
1422 - if (!empty($user_name)) {
1423 - $response_data['name'] = $user_name;
1424 - }
1425 -
1426 - wp_send_json_success($response_data);
1427 - }
1428 -
1429 - // Check if name field is required
1430 - $options = get_option('mxchat_options', []);
1431 - $name_field_enabled = isset($options['enable_name_field']) &&
1432 - ($options['enable_name_field'] === '1' || $options['enable_name_field'] === 'on');
1433 -
1434 - $email_option_key = "mxchat_email_{$session_id}";
1435 - $stored_email = get_option($email_option_key, '');
1436 -
1437 - // Check for stored name
1438 - $name_option_key = "mxchat_name_{$session_id}";
1439 - $stored_name = get_option($name_option_key, '');
1440 -
1441 - //error_log("[DEBUG] mxchat_check_email_provided -> Checking email option: {$email_option_key}, found: {$stored_email}");
1442 - //error_log("[DEBUG] mxchat_check_email_provided -> Checking name option: {$name_option_key}, found: {$stored_name}, required: " . ($name_field_enabled ? 'yes' : 'no'));
1443 -
1444 - // Check if we have email and name (if name is required)
1445 - $has_required_info = !empty($stored_email);
1446 -
1447 - if ($name_field_enabled) {
1448 - $has_required_info = $has_required_info && !empty($stored_name);
1449 - }
1450 -
1451 - if ($has_required_info) {
1452 - //error_log("[DEBUG] mxchat_check_email_provided -> Required info found, returning success");
1453 -
1454 - $response_data = ['email' => $stored_email];
1455 - if (!empty($stored_name)) {
1456 - $response_data['name'] = $stored_name;
1457 - }
1458 -
1459 - wp_send_json_success($response_data);
1460 - } else {
1461 - //error_log("[DEBUG] mxchat_check_email_provided -> Required info missing, returning error");
1462 - wp_send_json_error(['message' => esc_html__('No email found', 'mxchat')]);
1463 - }
1464 -}
1465 -
1466 -/**
1467 - * Send error response in appropriate format based on streaming mode
1468 - * ADDED: Helper method to consistently handle errors in both streaming and non-streaming modes
1469 - *
1470 - * @param string $error_message The error message to display
1471 - * @param string $error_code Optional error code for debugging
1472 - */
1473 -private function send_error_response($error_message, $error_code = 'api_error') {
1474 - if ($this->is_streaming) {
1475 - echo "data: " . json_encode([
1476 - 'error' => true,
1477 - 'error_message' => $error_message,
1478 - 'error_code' => $error_code,
1479 - 'text' => $error_message,
1480 - 'message' => $error_message
1481 - ]) . "\n\n";
1482 - echo "data: [DONE]\n\n";
1483 - flush();
1484 - } else {
1485 - wp_send_json_error([
1486 - 'error_message' => $error_message,
1487 - 'error_code' => $error_code
1488 - ]);
1489 - }
1490 - wp_die();
1491 -}
1492 -
1493 -public function mxchat_handle_chat_request() {
1494 - global $wpdb;
1495 -
1496 - // Debug: Log incoming bot_id
1497 - $bot_id = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
1498 - //error_log("=== MXCHAT DEBUG: Starting chat request ===");
1499 - //error_log("MXCHAT DEBUG: Bot ID received: " . $bot_id);
1500 -
1501 - // Get bot-specific options
1502 - $bot_options = $this->get_bot_options($bot_id);
1503 - $current_options = !empty($bot_options) ? $bot_options : $this->options;
1504 -
1505 - // Check if this is a streaming request
1506 - // Allow force_streaming_test parameter to bypass the setting check (for admin compatibility testing)
1507 - $force_streaming_test = isset($_POST['force_streaming_test']) && $_POST['force_streaming_test'] === '1' && current_user_can('administrator');
1508 - $is_streaming = isset($_POST['action']) && $_POST['action'] === 'mxchat_stream_chat' &&
1509 - ($force_streaming_test || (isset($current_options['enable_streaming_toggle']) && $current_options['enable_streaming_toggle'] === 'on'));
1510 -
1511 - // ADDED: Store streaming state in class property for use in private methods
1512 - $this->is_streaming = $is_streaming;
1513 -
1514 - // NOTE: Streaming headers are now set later via setup_streaming_headers()
1515 - // This allows actions/forms to return JSON responses without header conflicts
1516 -
1517 - // Check if MX Chat Moderation is active
1518 - if (class_exists('MX_Chat_Moderation')) {
1519 - // Get user email and IP
1520 - $user_email = '';
1521 - $user_ip = $_SERVER['REMOTE_ADDR'];
1522 -
1523 - // If user is logged in, get their email
1524 - if (is_user_logged_in()) {
1525 - $current_user = wp_get_current_user();
1526 - $user_email = $current_user->user_email;
1527 - }
1528 -
1529 - // Create ban handler instance
1530 - $ban_handler = new MX_Chat_Ban_Handler();
1531 -
1532 - // Check if user is banned by IP
1533 - if ($ban_handler->check_ban($user_ip, 'ip')) {
1534 - wp_send_json([
1535 - 'success' => false,
1536 - 'message' => esc_html__('Access denied. Your IP address has been banned.', 'mxchat'),
1537 - 'status' => 'banned'
1538 - ]);
1539 - wp_die();
1540 - }
1541 -
1542 - // If user is logged in, also check email
1543 - if (!empty($user_email) && $ban_handler->check_ban($user_email, 'email')) {
1544 - wp_send_json([
1545 - 'success' => false,
1546 - 'message' => esc_html__('Access denied. Your email address has been banned.', 'mxchat'),
1547 - 'status' => 'banned'
1548 - ]);
1549 - wp_die();
1550 - }
1551 - }
1552 -
1553 - $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
1554 - $this->productCardHtml = '';
1555 - $this->videoEmbedHtml = '';
1556 - // Reset the per-turn function-calling UI capture (plan 48a57a).
1557 - $this->fc_ui_html = '';
1558 - $this->fc_ui_images = array();
1559 - $this->fc_ui_captured = false;
1560 -
1561 - // Get the actual WordPress user ID if logged in
1562 - $is_logged_in = is_user_logged_in();
1563 - if ($is_logged_in) {
1564 - $user_id = get_current_user_id(); // This will get the actual WordPress user ID
1565 - } else {
1566 - // For logged-out users, use your existing identifier method
1567 - $user_id = $this->mxchat_get_user_identifier();
1568 - }
1569 -
1570 - // Get and sanitize the user identifier
1571 - $user_id = sanitize_key($user_id);
1572 -
1573 - // Check rate limit using new settings structure
1574 - $rate_limit_result = $this->check_rate_limit();
1575 -
1576 - if ($rate_limit_result !== true) {
1577 - wp_send_json([
1578 - 'success' => false,
1579 - 'message' => $rate_limit_result['message'],
1580 - 'status' => 'rate_limit_exceeded'
1581 - ]);
1582 - wp_die();
1583 - }
1584 -
1585 - // Rest of your existing code...
1586 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
1587 -
1588 - // Treat the literal strings 'null' / 'undefined' as missing too. Browser edge cases
1589 - // (Safari ITP, private mode, cross-origin iframes with partitioned storage) can cause
1590 - // the frontend FormData.append() to stringify a null session_id into the literal
1591 - // "null", which would otherwise pass empty() and pollute the transcripts table with
1592 - // ghost sessions that group every visitor's first message under one row.
1593 - if ($session_id === 'null' || $session_id === 'undefined') {
1594 - $session_id = '';
1595 - }
1596 -
1597 - if (empty($session_id)) {
1598 - wp_send_json_error(esc_html__('Session ID is missing.', 'mxchat'));
1599 - wp_die();
1600 - }
1601 -
1602 - // Update session owner if it changed (e.g. IP changed due to network switch)
1603 - // The session ID itself is the authentication — if the client has it, they own it
1604 - $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
1605 - $session_owner = get_option("mxchat_session_owner_{$session_id}");
1606 -
1607 - if (!$session_owner || $session_owner !== $current_user_identifier) {
1608 - update_option("mxchat_session_owner_{$session_id}", $current_user_identifier, 'no');
1609 - }
1610 -
1611 - // Validate and sanitize the incoming message
1612 - if (empty($_POST['message'])) {
1613 - wp_send_json_error(esc_html__('No message received.', 'mxchat'));
1614 - wp_die();
1615 - }
1616 -
1617 - // Enforce the configurable max input length (plan a3fae2 part C). 0 = unlimited.
1618 - // Server-side guard backing the textarea's client-side maxlength (which is bypassable).
1619 - // Reads the global core setting and measures characters (mb_strlen on the unslashed
1620 - // raw POST), matching the maxlength semantics.
1621 - $mxchat_max_input_length = isset($this->options['max_input_length']) ? intval($this->options['max_input_length']) : 0;
1622 - if ($mxchat_max_input_length > 0) {
1623 - $mxchat_incoming_raw = is_string($_POST['message']) ? wp_unslash($_POST['message']) : '';
1624 - if (mb_strlen($mxchat_incoming_raw) > $mxchat_max_input_length) {
1625 - wp_send_json([
1626 - 'success' => false,
1627 - /* translators: %d: maximum allowed characters */
1628 - 'message' => sprintf(esc_html__('Your message is too long. Please keep it under %d characters.', 'mxchat'), $mxchat_max_input_length),
1629 - 'status' => 'message_too_long'
1630 - ]);
1631 - wp_die();
1632 - }
1633 - }
1634 -
1635 -
1636 - // Track originating page for first message in session
1637 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1638 -
1639 - // Check if originating page columns exist
1640 - $columns_exist = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'");
1641 -
1642 - if ($columns_exist) {
1643 - // Check if this session already has messages
1644 - $message_count = $wpdb->get_var($wpdb->prepare(
1645 - "SELECT COUNT(*) FROM $table_name WHERE session_id = %s",
1646 - $session_id
1647 - ));
1648 -
1649 - // If this is the first message in the session
1650 - if ($message_count == 0) {
1651 - // Get originating page from JavaScript (preferred) or HTTP_REFERER (fallback)
1652 - $originating_url = '';
1653 - $originating_title = '';
1654 -
1655 - // Try to get from POST data first (sent by JavaScript)
1656 - if (isset($_POST['current_page_url'])) {
1657 - $originating_url = esc_url_raw($_POST['current_page_url']);
1658 - $originating_title = isset($_POST['current_page_title'])
1659 - ? sanitize_text_field($_POST['current_page_title'])
1660 - : '';
1661 - }
1662 - // Fallback to HTTP_REFERER if not provided by JavaScript
1663 - else if (isset($_SERVER['HTTP_REFERER'])) {
1664 - $originating_url = esc_url_raw($_SERVER['HTTP_REFERER']);
1665 - }
1666 -
1667 - // Generate title if we have URL but no title
1668 - if ($originating_url && empty($originating_title)) {
1669 - $parsed_url = parse_url($originating_url);
1670 - $path = isset($parsed_url['path']) ? trim($parsed_url['path'], '/') : '';
1671 -
1672 - if (empty($path) || $path === 'index.php' || $path === 'index.html') {
1673 - $originating_title = 'Homepage';
1674 - } else {
1675 - // Clean up the path to make a readable title
1676 - $originating_title = str_replace(['-', '_', '/', '.php', '.html'], ' ', $path);
1677 - $originating_title = ucwords(trim($originating_title));
1678 - }
1679 - }
1680 -
1681 - // Store for later use when saving the message
1682 - $this->pending_originating_page = [
1683 - 'url' => $originating_url,
1684 - 'title' => $originating_title
1685 - ];
1686 - }
1687 - }
1688 -
1689 -
1690 -
1691 - // Get page context if provided
1692 - $page_context = null;
1693 - if (isset($_POST['page_context']) && !empty($_POST['page_context'])) {
1694 - $page_context_raw = stripslashes($_POST['page_context']);
1695 - $page_context = json_decode($page_context_raw, true);
1696 -
1697 - // Validate page context structure
1698 - if (is_array($page_context) &&
1699 - isset($page_context['url']) &&
1700 - isset($page_context['title']) &&
1701 - isset($page_context['content'])) {
1702 -
1703 - // Sanitize page context
1704 - $page_context['url'] = esc_url_raw($page_context['url']);
1705 - $page_context['title'] = sanitize_text_field($page_context['title']);
1706 - $page_context['content'] = wp_kses_post($page_context['content']);
1707 - } else {
1708 - $page_context = null;
1709 - }
1710 - }
1711 -
1712 - // Modify the message sanitization to preserve PHP tags in code blocks
1713 - $allowed_tags = [
1714 - 'pre' => [],
1715 - 'code' => ['class' => true],
1716 - 'span' => ['class' => true],
1717 - 'div' => ['class' => true],
1718 - ];
1719 -
1720 - // First preserve code blocks
1721 - $message = preg_replace_callback('/<pre><code.*?>.*?<\/code><\/pre>/s', function($matches) {
1722 - return htmlspecialchars_decode($matches[0]);
1723 - }, $_POST['message']);
1724 -
1725 - // Then apply sanitization
1726 - $message = wp_kses($message, $allowed_tags);
1727 -
1728 - // Preserve code blocks from markdown conversion
1729 - $message = preg_replace('/```(\w+)?\s*([\s\S]+?)```/s', '<pre><code class="$1">$2</code></pre>', $message);
1730 - $message = apply_filters('mxchat_filter_message', $message, 'prompt', $session_id);
1731 -
1732 - // ===== SIMPLIFIED TESTING PANEL INITIALIZATION =====
1733 - // Always initialize testing data for admins (no toggle needed)
1734 - $testing_data = null;
1735 - if (current_user_can('administrator')) {
1736 - // For vision messages, use the original user message for the query display
1737 - $query_for_testing = $message;
1738 - if (isset($_POST['vision_processed']) && $_POST['vision_processed'] && isset($_POST['original_user_message'])) {
1739 - $query_for_testing = sanitize_textarea_field($_POST['original_user_message']);
1740 - }
1741 -
1742 - $testing_data = [
1743 - 'query' => $query_for_testing,
1744 - 'timestamp' => time(),
1745 - 'top_matches' => [],
1746 - 'action_matches' => [], // Initialize action matches array
1747 - 'page_context' => $page_context, // Include page context in testing data
1748 - 'is_vision' => isset($_POST['vision_processed']) && $_POST['vision_processed'],
1749 - 'bot_id' => $bot_id // Include bot ID in testing data
1750 - ];
1751 -
1752 - // Get similarity threshold from bot options or default options
1753 - $similarity_threshold = isset($current_options['similarity_threshold'])
1754 - ? ((int) $current_options['similarity_threshold']) / 100
1755 - : 0.35;
1756 -
1757 - $testing_data['similarity_threshold'] = $similarity_threshold;
1758 -
1759 - // Determine knowledge base type using bot-specific config
1760 - $bot_pinecone_config = $this->get_bot_pinecone_config($bot_id);
1761 - $use_pinecone = isset($bot_pinecone_config['use_pinecone']) ? $bot_pinecone_config['use_pinecone'] : false;
1762 - $testing_data['knowledge_base_type'] = $use_pinecone ? 'Pinecone' : 'WordPress Database';
1763 - }
1764 - // ===== END SIMPLIFIED TESTING INITIALIZATION =====
1765 -
1766 - // Add debug before and after:
1767 - //error_log('MxChat Core: About to call mxchat_pre_process_message filter with message: ' . $message);
1768 - $pre_processed_result = apply_filters('mxchat_pre_process_message', $message, $user_id, $session_id);
1769 - //error_log('MxChat Core: Filter returned: ' . (is_array($pre_processed_result) ? 'array' : $pre_processed_result));
1770 -
1771 -
1772 - // If the pre-processing returned a result (not the original message), use it directly
1773 - if (is_array($pre_processed_result) && isset($pre_processed_result['text'])) {
1774 - // Save the AI response
1775 - $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['text']);
1776 -
1777 - // Save HTML content if provided
1778 - if (!empty($pre_processed_result['html'])) {
1779 - $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['html']);
1780 - }
1781 -
1782 - // Add testing data if admin
1783 - $response_data = [
1784 - 'text' => $pre_processed_result['text'],
1785 - 'html' => $pre_processed_result['html'] ?? '',
1786 - 'session_id' => $session_id
1787 - ];
1788 -
1789 - if ($testing_data !== null) {
1790 - $response_data['testing_data'] = $testing_data;
1791 - }
1792 -
1793 - wp_send_json($response_data);
1794 - wp_die();
1795 - }
1796 -
1797 - // Save the user's message - handle vision processed messages differently
1798 - if (isset($_POST['vision_processed']) && $_POST['vision_processed'] && isset($_POST['original_user_message'])) {
1799 - // For vision messages, save the original user message with image indicator
1800 - $original_message = sanitize_textarea_field($_POST['original_user_message']);
1801 - if (isset($_POST['vision_images_count']) && $_POST['vision_images_count'] > 0) {
1802 - $image_count = intval($_POST['vision_images_count']);
1803 - $original_message .= " [{$image_count} image(s)]";
1804 - }
1805 - $this->mxchat_save_chat_message($session_id, 'user', $original_message);
1806 - } else {
1807 - // Regular message - save as normal
1808 - $this->mxchat_save_chat_message($session_id, 'user', $message);
1809 - }
1810 -
1811 -
1812 - if (is_email($message)) {
1813 - // Add the email to Loops
1814 - $this->add_email_to_loops($message);
1815 -
1816 - // Get the user's success message instruction using current_options
1817 - $user_success_message = $current_options['email_capture_response'] ?? __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
1818 -
1819 - // Set instruction for AI using the user's success message
1820 - $this->current_action_instruction = $user_success_message;
1821 -
1822 - // Clear the email capture transient since we got the email
1823 - delete_transient('mxchat_email_capture_' . $user_id);
1824 - }
1825 -
1826 - // Check if we're in an email capture flow but user hasn't provided email yet
1827 - elseif (get_transient('mxchat_email_capture_' . $user_id)) {
1828 - // Check if the message contains an email (not the whole message being an email)
1829 - if (preg_match('/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/', $message, $matches)) {
1830 - $extracted_email = $matches[0];
1831 -
1832 - // Add the extracted email to Loops
1833 - $this->add_email_to_loops($extracted_email);
1834 -
1835 - // Get the user's success message instruction using current_options
1836 - $user_success_message = $current_options['email_capture_response'] ?? __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
1837 -
1838 - // Set instruction for AI using the user's success message
1839 - $this->current_action_instruction = $user_success_message;
1840 -
1841 - // Clear the email capture transient since we got the email
1842 - delete_transient('mxchat_email_capture_' . $user_id);
1843 - }
1844 - // If no email found but we're in capture mode, remind them
1845 - else {
1846 - // Get the original instruction to remind them using current_options
1847 - $original_instruction = $current_options['triggered_phrase_response'] ?? __("Please provide your email address.", 'mxchat');
1848 - $this->current_action_instruction = $original_instruction;
1849 - }
1850 - }
1851 -
1852 - $intent_info = '';
1853 -
1854 - // Check chat mode
1855 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
1856 -
1857 - // Handle agent mode
1858 - // Handle agent mode
1859 - if ($chat_mode === 'agent') {
1860 - // First, check for switch intent before doing anything else
1861 - $intent_matched = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
1862 -
1863 - // Capture action analysis for testing panel after intent check
1864 - if ($testing_data !== null && isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
1865 - $testing_data['action_matches'] = $this->last_action_analysis;
1866 - }
1867 -
1868 - // Around line 506, in the agent mode handling section:
1869 - if ($intent_matched && !empty($this->fallbackResponse['text'])) {
1870 - // Update chat mode first
1871 - update_option("mxchat_mode_{$session_id}", 'ai');
1872 -
1873 - // Clear any existing PDF context to start fresh
1874 - $this->clear_pdf_transients($session_id);
1875 -
1876 - // Prepare clean switch response with explicit chat_mode
1877 - $response_data = [
1878 - 'text' => $this->fallbackResponse['text'],
1879 - 'html' => $this->fallbackResponse['html'] ?? '',
1880 - 'session_id' => $session_id,
1881 - 'chat_mode' => 'ai' // EXPLICITLY SET THIS
1882 - ];
1883 -
1884 - if ($testing_data !== null) {
1885 - $response_data['testing_data'] = $testing_data;
1886 - }
1887 -
1888 - // Save the mode switch message
1889 - $this->mxchat_save_chat_message($session_id, 'system', esc_html__('Switched to AI chat mode', 'mxchat'));
1890 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
1891 -
1892 - // Send response and exit
1893 - wp_send_json($response_data);
1894 - wp_die();
1895 - } elseif (!$intent_matched) {
1896 - // No intent matched, handle live agent message
1897 - try {
1898 - $this->mxchat_send_user_message_to_agent($message, $user_id, $session_id);
1899 -
1900 - $agent_response = [
1901 - 'status' => 'waiting_for_agent',
1902 - 'message' => esc_html__('Message sent to live agent.', 'mxchat')
1903 - ];
1904 -
1905 - if ($testing_data !== null) {
1906 - $agent_response['testing_data'] = $testing_data;
1907 - }
1908 -
1909 - wp_send_json_success($agent_response);
1910 - } catch (\Exception $e) {
1911 - wp_send_json_error(esc_html__('Failed to send message to agent', 'mxchat'));
1912 - }
1913 - wp_die();
1914 - }
1915 - }
1916 -
1917 - // Step 1: Check for new PDF URL in the message
1918 - if (!isset($_POST['vision_processed']) && preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
1919 - $new_pdf_url = $matches[0];
1920 -
1921 - // Check if this is likely a PDF-related request
1922 - $pdf_keywords = ['pdf', 'document', 'read', 'analyze'];
1923 - $is_pdf_request = false;
1924 -
1925 - foreach ($pdf_keywords as $keyword) {
1926 - if (stripos($message, $keyword) !== false) {
1927 - $is_pdf_request = true;
1928 - break;
1929 - }
1930 - }
1931 -
1932 - // If it looks like a PDF request or we're waiting for a PDF URL
1933 - if ($is_pdf_request || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
1934 - // Validate HTTPS
1935 - if (wp_http_validate_url($new_pdf_url) && parse_url($new_pdf_url, PHP_URL_SCHEME) === 'https') {
1936 - // Extract filename from URL
1937 - $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
1938 -
1939 - // Clear previous PDF transients
1940 - $this->clear_pdf_transients($session_id);
1941 -
1942 - // Process new PDF using current_options
1943 - $max_pages = $current_options['pdf_max_pages'] ?? 69;
1944 - $embeddings = $this->fetch_and_split_pdf_pages($new_pdf_url, $max_pages);
1945 -
1946 - if ($embeddings === 'too_many_pages') {
1947 - $error_text = sprintf(
1948 - $current_options['pdf_intent_error_text'] ??
1949 - esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
1950 - $max_pages
1951 - );
1952 - $this->fallbackResponse['text'] = $error_text;
1953 - } elseif ($embeddings) {
1954 - // Store new PDF information
1955 - $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
1956 -
1957 - // If the filename is generic, create a more descriptive one
1958 - if (in_array($pdf_filename, ['results_download.php', 'download.php', 'view.php', 'pdf.php']) ||
1959 - strpos($pdf_filename, '.php') !== false) {
1960 - $pdf_filename = 'Document_' . date('Y-m-d_H-i') . '.pdf';
1961 - }
1962 -
1963 - set_transient('mxchat_pdf_url_' . $session_id, $new_pdf_url, HOUR_IN_SECONDS);
1964 - set_transient('mxchat_pdf_filename_' . $session_id, $pdf_filename, HOUR_IN_SECONDS);
1965 - set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
1966 - set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
1967 -
1968 - $success_text = $current_options['pdf_intent_success_text'] ??
1969 - esc_html__("I've processed the new PDF '{$pdf_filename}'. What questions do you have about it?", 'mxchat');
1970 -
1971 - $pdf_response = [
1972 - 'success' => true,
1973 - 'message' => $success_text,
1974 - 'data' => [
1975 - 'filename' => $pdf_filename
1976 - ]
1977 - ];
1978 -
1979 - if ($testing_data !== null) {
1980 - $pdf_response['testing_data'] = $testing_data;
1981 - }
1982 -
1983 - wp_send_json($pdf_response);
1984 - wp_die();
1985 - } else {
1986 - $error_text = $current_options['pdf_intent_error_text'] ??
1987 - esc_html__("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
1988 - $this->fallbackResponse['text'] = $error_text;
1989 - }
1990 -
1991 - $pdf_error_response = [
1992 - 'success' => false,
1993 - 'message' => $this->fallbackResponse['text']
1994 - ];
1995 -
1996 - if ($testing_data !== null) {
1997 - $pdf_error_response['testing_data'] = $testing_data;
1998 - }
1999 -
2000 - wp_send_json($pdf_error_response);
2001 - wp_die();
2002 - }
2003 - }
2004 - }
2005 -
2006 -
2007 - // Step 2: Detect intent and handle intent-based responses
2008 - $intent_result = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
2009 -
2010 - // Capture action analysis for testing panel after intent check
2011 - if ($testing_data !== null && isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
2012 - $testing_data['action_matches'] = $this->last_action_analysis;
2013 - }
2014 -
2015 - // Step 3: Handle the intent result appropriately
2016 - if ($intent_result !== false) {
2017 - // Intent was matched - ALWAYS send as JSON response, never streaming
2018 -
2019 - if (is_array($intent_result) && (isset($intent_result['text']) || isset($intent_result['html']))) {
2020 - // Intent returned a direct response array
2021 - $response_data = [
2022 - 'text' => $intent_result['text'] ?? '',
2023 - 'html' => $intent_result['html'] ?? '',
2024 - 'session_id' => $session_id
2025 - ];
2026 -
2027 - // IMPORTANT: Include chat_mode if present (for WhatsApp, Slack, etc.)
2028 - if (isset($intent_result['chat_mode'])) {
2029 - $response_data['chat_mode'] = $intent_result['chat_mode'];
2030 - }
2031 -
2032 - if ($testing_data !== null) {
2033 - $response_data['testing_data'] = $testing_data;
2034 - }
2035 -
2036 - wp_send_json($response_data);
2037 - wp_die();
2038 - } else if ($intent_result === true && (!empty($this->fallbackResponse['text']) || !empty($this->fallbackResponse['html']))) {
2039 - // Intent returned true and set fallbackResponse
2040 -
2041 - // SAVE TO TRANSCRIPT
2042 - if (!empty($this->fallbackResponse['text'])) {
2043 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
2044 - }
2045 - // Save action HTML (product cards, featured products, etc.) so it renders in transcripts
2046 - if (!empty($this->fallbackResponse['html'])) {
2047 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
2048 - }
2049 -
2050 - $response_data = [
2051 - 'text' => $this->fallbackResponse['text'] ?? '',
2052 - 'html' => $this->fallbackResponse['html'] ?? '',
2053 - 'session_id' => $session_id
2054 - ];
2055 -
2056 - if (isset($this->fallbackResponse['chat_mode'])) {
2057 - $response_data['chat_mode'] = $this->fallbackResponse['chat_mode'];
2058 - }
2059 -
2060 - if ($testing_data !== null) {
2061 - $response_data['testing_data'] = $testing_data;
2062 - }
2063 -
2064 - wp_send_json($response_data);
2065 - wp_die();
2066 - }
2067 - }
2068 -
2069 - // If we get here, no intent matched OR the intent didn't provide a usable response
2070 -
2071 - // Step 4: Generate AI response
2072 - // Get session start timestamp - when persistence is OFF, only include messages from this page load
2073 - $session_start_timestamp = isset($_POST['session_start_timestamp']) ? intval($_POST['session_start_timestamp']) : 0;
2074 - $conversation_history = $this->mxchat_fetch_conversation_history_for_ai($session_id, $session_start_timestamp);
2075 - $this->mxchat_increment_chat_count();
2076 -
2077 - // Generate embedding for the user's query - USE BOT-SPECIFIC API KEY
2078 - $api_key = $current_options['api_key'] ?? $this->options['api_key'];
2079 - $user_message_embedding = $this->mxchat_generate_embedding($message, $api_key);
2080 -
2081 - // Check if the embedding generation returned an error
2082 - if (is_array($user_message_embedding) && isset($user_message_embedding['error'])) {
2083 - $error_message = $user_message_embedding['error'];
2084 - $error_code = $user_message_embedding['error_code'] ?? 'embedding_error';
2085 -
2086 - // FIXED: Send error in appropriate format based on streaming mode
2087 - if ($is_streaming) {
2088 - echo "data: " . json_encode([
2089 - 'error' => true,
2090 - 'error_message' => $error_message,
2091 - 'error_code' => $error_code,
2092 - 'text' => $error_message,
2093 - 'message' => $error_message
2094 - ]) . "\n\n";
2095 - echo "data: [DONE]\n\n";
2096 - flush();
2097 - } else {
2098 - wp_send_json_error([
2099 - 'error_message' => $error_message,
2100 - 'error_code' => $error_code
2101 - ]);
2102 - }
2103 - wp_die();
2104 - }
2105 -
2106 - // Check if the embedding is valid
2107 - if (!is_array($user_message_embedding) || empty($user_message_embedding)) {
2108 - $error_message = esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat');
2109 -
2110 - // FIXED: Send error in appropriate format based on streaming mode
2111 - if ($is_streaming) {
2112 - echo "data: " . json_encode([
2113 - 'error' => true,
2114 - 'error_message' => $error_message,
2115 - 'error_code' => 'invalid_embedding',
2116 - 'text' => $error_message,
2117 - 'message' => $error_message
2118 - ]) . "\n\n";
2119 - echo "data: [DONE]\n\n";
2120 - flush();
2121 - } else {
2122 - wp_send_json_error([
2123 - 'error_message' => $error_message,
2124 - 'error_code' => 'invalid_embedding'
2125 - ]);
2126 - }
2127 - wp_die();
2128 - }
2129 -
2130 - // Build context with both knowledge base and PDF content if available
2131 - $context_content = "User asked: '{$message}'\n\n";
2132 -
2133 - // Add action instruction if present (add this right after the above line)
2134 - if (!empty($this->current_action_instruction)) {
2135 - $context_content .= "===== SPECIAL INSTRUCTION =====\n";
2136 - $context_content .= "IMPORTANT: " . $this->current_action_instruction . "\n";
2137 - $context_content .= "Respond naturally and conversationally while following this instruction.\n";
2138 - $context_content .= "===== END SPECIAL INSTRUCTION =====\n\n";
2139 -
2140 - // Clear the instruction after using it
2141 - $this->current_action_instruction = null;
2142 - }
2143 -
2144 -
2145 - // Add page context if available and contextual awareness is enabled using current_options
2146 - if ($page_context && isset($current_options['contextual_awareness_toggle']) && $current_options['contextual_awareness_toggle'] === 'on') {
2147 - $context_content .= "===== CURRENT PAGE CONTEXT =====\n";
2148 - $context_content .= "Page URL: " . $page_context['url'] . "\n";
2149 - $context_content .= "Page Title: " . $page_context['title'] . "\n";
2150 - $context_content .= "Page Content: " . $page_context['content'] . "\n";
2151 - $context_content .= "===== END CURRENT PAGE CONTEXT =====\n\n";
2152 - }
2153 -
2154 - // Get relevant content from knowledge base - PASS BOT_ID and MESSAGE for Vector Store
2155 - $relevant_content = $this->mxchat_find_relevant_content($user_message_embedding, $bot_id, $message);
2156 -
2157 - // NEW: Also extract URLs from system instructions (only if citation links enabled)
2158 - // Use fresh options to ensure we get the latest setting value
2159 - $fresh_options = get_option('mxchat_options', []);
2160 - $citation_links_enabled = isset($fresh_options['citation_links_toggle']) ? ($fresh_options['citation_links_toggle'] === 'on') : true;
2161 -
2162 - $system_instructions = $this->get_system_instructions($bot_id, $session_id);
2163 - if ($citation_links_enabled && !empty($system_instructions)) {
2164 - preg_match_all(
2165 - '#\bhttps?://[^\s<>"\']+#i',
2166 - $system_instructions,
2167 - $system_instruction_urls
2168 - );
2169 -
2170 - if (!empty($system_instruction_urls[0])) {
2171 - // Merge with existing valid URLs
2172 - $this->current_valid_urls = array_merge(
2173 - $this->current_valid_urls,
2174 - $system_instruction_urls[0]
2175 - );
2176 - // Remove duplicates
2177 - $this->current_valid_urls = array_unique($this->current_valid_urls);
2178 -
2179 - //error_log("Added " . count($system_instruction_urls[0]) . " URLs from system instructions");
2180 - }
2181 - }
2182 -
2183 -// ===== CAPTURE REAL SIMILARITY DATA FOR ADMINS =====
2184 -if ($testing_data !== null && $this->last_similarity_analysis !== null) {
2185 - // Update testing data with the REAL similarity analysis
2186 - $testing_data['top_matches'] = $this->last_similarity_analysis['top_matches'];
2187 - $testing_data['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
2188 - $testing_data['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'];
2189 - $testing_data['sources_used'] = $this->last_similarity_analysis['sources_used'] ?? 0;
2190 - $testing_data['total_chunks_used'] = $this->last_similarity_analysis['total_chunks_used'] ?? 0;
2191 -}
2192 -// ===== END SIMILARITY DATA CAPTURE =====
2193 -
2194 -// NEW: Add valid URLs to testing data for admin panel display (AFTER similarity data)
2195 -if ($testing_data !== null && !empty($this->current_valid_urls)) {
2196 - $testing_data['approved_urls'] = array_values($this->current_valid_urls);
2197 - //error_log("Added " . count($this->current_valid_urls) . " approved URLs to testing data");
2198 -}
2199 -
2200 - if (!empty($relevant_content)) {
2201 - $context_content .= "===== OFFICIAL KNOWLEDGE DATABASE CONTENT =====\n" . $relevant_content . "\n===== END OF OFFICIAL KNOWLEDGE DATABASE CONTENT =====\n\n";
2202 - } else {
2203 - $context_content .= "===== NO RELEVANT CONTENT FOUND IN KNOWLEDGE DATABASE =====\n";
2204 - }
2205 -
2206 - // NEW: Add approved URLs list to context for AI (only if citation links enabled)
2207 - if ($citation_links_enabled && !empty($this->current_valid_urls)) {
2208 - $context_content .= "===== APPROVED URLS FOR CITATIONS =====\n";
2209 - $context_content .= "You may ONLY use these exact URLs in your response:\n";
2210 - foreach ($this->current_valid_urls as $url) {
2211 - $context_content .= "- " . $url . "\n";
2212 - }
2213 - $context_content .= "\nCRITICAL: Do NOT create, modify, extend, or invent any other URLs. ";
2214 - $context_content .= "===== END APPROVED URLS =====\n\n";
2215 - }
2216 -
2217 - // Check for and include PDF content
2218 - $pdf_url = get_transient('mxchat_pdf_url_' . $session_id);
2219 - $pdf_embeddings = get_transient('mxchat_pdf_embeddings_' . $session_id);
2220 - $pdf_filename = get_transient('mxchat_pdf_filename_' . $session_id);
2221 - if ($pdf_url && $pdf_embeddings && get_transient('mxchat_include_pdf_in_context_' . $session_id)) {
2222 - $relevant_pdf_pages = $this->find_relevant_pdf_pages($user_message_embedding, $pdf_embeddings);
2223 - if (!empty($relevant_pdf_pages)) {
2224 - $context_content .= "Relevant content from PDF document '{$pdf_filename}':\n";
2225 - foreach ($relevant_pdf_pages as $page_data) {
2226 - $context_content .= "Page {$page_data['page_number']} of '{$pdf_filename}': {$page_data['text']}\n";
2227 - }
2228 - $context_content .= "\n";
2229 - }
2230 - }
2231 -
2232 - // Check for and include Word content
2233 - $word_url = get_transient('mxchat_word_url_' . $session_id);
2234 - $word_embeddings = get_transient('mxchat_word_embeddings_' . $session_id);
2235 - $word_filename = get_transient('mxchat_word_filename_' . $session_id);
2236 - if ($word_url && $word_embeddings && get_transient('mxchat_include_word_in_context_' . $session_id)) {
2237 - $relevant_word_chunks = $this->word_handler->mxchat_find_relevant_word_chunks($user_message_embedding, $word_embeddings);
2238 - if (!empty($relevant_word_chunks)) {
2239 - $context_content .= "Relevant content from Word document '{$word_filename}':\n";
2240 - foreach ($relevant_word_chunks as $chunk_data) {
2241 - $context_content .= "Section {$chunk_data['chunk_number']} of '{$word_filename}': {$chunk_data['text']}\n";
2242 - }
2243 - $context_content .= "\n";
2244 - }
2245 - }
2246 -
2247 - $context_content = apply_filters('mxchat_prepare_context', $context_content, $session_id);
2248 -
2249 - // Extract model from current options for bot-specific model support
2250 - $selected_model = isset($current_options['model']) ? $current_options['model'] : 'gpt-5.1-chat-latest';
2251 -
2252 - // ===== Native function-calling fallback (plan-mxchat-20260617-a41dee) =====
2253 - // Intents already missed (we're past the intent router). If function
2254 - // calling is enabled and the active model is tool-capable, let the model
2255 - // SELECT and run registered callbacks as tools — independent of intents,
2256 - // works with zero Actions. The tool round is buffered; the final answer is
2257 - // emitted via the SAME envelopes the normal path uses. Default-off, so
2258 - // existing installs never enter this branch.
2259 - if ($this->mxchat_fc_should_run($selected_model)) {
2260 - $fc_outcome = $this->mxchat_fc_attempt(
2261 - $message,
2262 - $context_content,
2263 - $conversation_history,
2264 - $selected_model,
2265 - $current_options,
2266 - $session_id,
2267 - $user_id
2268 - );
2269 - if (is_array($fc_outcome) && !empty($fc_outcome['handled'])) {
2270 - $fc_text = isset($fc_outcome['text']) ? $fc_outcome['text'] : '';
2271 - if (!empty($this->current_valid_urls)) {
2272 - $fc_text = $this->validate_and_clean_urls($fc_text, $this->current_valid_urls, $session_id, $bot_id);
2273 - }
2274 - // plan-mxchat-20260617-48a57a — surface any UI element a tool
2275 - // produced (generated image / product card / image gallery) so the
2276 - // widget RENDERS it, instead of emitting only the model's text.
2277 - // The html was already saved to the transcript in
2278 - // mxchat_fc_execute_tool (or by the callback itself for self-saving
2279 - // core tools), so we persist ONLY the model's caption text here.
2280 - $fc_html = isset($this->fc_ui_html) ? $this->fc_ui_html : '';
2281 -
2282 - if ($fc_text !== '') {
2283 - $this->mxchat_save_chat_message($session_id, 'bot', $fc_text, null, null);
2284 - }
2285 -
2286 - // A video-backed KB source queued during retrieval (03ba33) must
2287 - // surface on the FC path too — the FC envelopes below are the ONLY
2288 - // exit for this turn, so append it to the html channel and persist
2289 - // it (tool html was already saved in mxchat_fc_execute_tool; the
2290 - // video embed has no other save point on this path).
2291 - if (!empty($this->videoEmbedHtml)) {
2292 - $fc_html .= $this->videoEmbedHtml;
2293 - $this->mxchat_save_chat_message($session_id, 'bot', $this->videoEmbedHtml);
2294 - }
2295 -
2296 - if ($is_streaming) {
2297 - // The frontend SSE reader routes any event carrying text/html
2298 - // to handleNonStreamResponse(), which renders text + html in a
2299 - // single bot message — so emit one complete event (mirrors the
2300 - // intent path's text/html envelope).
2301 - $sse = array('session_id' => $session_id);
2302 - if ($fc_text !== '') $sse['text'] = $fc_text;
2303 - if ($fc_html !== '') $sse['html'] = $fc_html;
2304 - if ($fc_text === '' && $fc_html === '') $sse['text'] = $this->mxchat_fc_giveup_text();
2305 - echo "data: " . wp_json_encode($sse) . "\n\n";
2306 - echo "data: [DONE]\n\n";
2307 - flush();
2308 - } else {
2309 - $fc_response_data = array('text' => $fc_text, 'html' => $fc_html, 'session_id' => $session_id);
2310 - if ($testing_data !== null) {
2311 - $fc_response_data['testing_data'] = $testing_data;
2312 - }
2313 - wp_send_json($fc_response_data);
2314 - }
2315 - wp_die();
2316 - }
2317 - }
2318 - // ===== end function-calling fallback =====
2319 -
2320 - // Streaming + a queued video embed (03ba33): the provider handlers own the
2321 - // token stream and the [DONE] terminator, so the embed rides a dedicated
2322 - // append_html SSE event emitted BEFORE the stream starts. The client
2323 - // stashes it and appends it as its own bot bubble after [DONE] — old
2324 - // cached widget JS simply ignores the unknown key (no content/text/html/
2325 - // error field, so no branch matches). Transcript save happens after the
2326 - // stream completes, so history order matches the live order (text, then
2327 - // embed).
2328 - if ($is_streaming && !empty($this->videoEmbedHtml)) {
2329 - echo "data: " . wp_json_encode(array(
2330 - 'append_html' => $this->videoEmbedHtml,
2331 - 'session_id' => $session_id,
2332 - )) . "\n\n";
2333 - flush();
2334 - }
2335 -
2336 - $response = $this->mxchat_generate_response(
2337 - $context_content,
2338 - $current_options['api_key'] ?? $this->options['api_key'],
2339 - $current_options['xai_api_key'] ?? $this->options['xai_api_key'],
2340 - $current_options['claude_api_key'] ?? $this->options['claude_api_key'],
2341 - $current_options['deepseek_api_key'] ?? $this->options['deepseek_api_key'],
2342 - $current_options['gemini_api_key'] ?? $this->options['gemini_api_key'],
2343 - $current_options['openrouter_api_key'] ?? $this->options['openrouter_api_key'],
2344 - $conversation_history,
2345 - $is_streaming,
2346 - $session_id,
2347 - $testing_data,
2348 - $selected_model
2349 - );
2350 -
2351 - // Handle streaming vs non-streaming responses
2352 - if ($is_streaming) {
2353 - // Check if streaming actually happened or if it fell back to regular response
2354 - if ($response === true) {
2355 - // Persist the video embed AFTER the provider saved the streamed
2356 - // text, so history replays in the same order the visitor saw
2357 - // (text bubble, then embed bubble). See 03ba33.
2358 - if (!empty($this->videoEmbedHtml)) {
2359 - $this->mxchat_save_chat_message($session_id, 'bot', $this->videoEmbedHtml);
2360 - }
2361 - wp_die();
2362 - }
2363 - // If we get here, streaming fell back to regular response, continue
2364 - // But if there's an error, we need to send it as SSE format since headers are already set
2365 - if (is_array($response) && isset($response['error'])) {
2366 - $error_message = $response['error'];
2367 - $error_code = $response['error_code'] ?? 'api_error';
2368 - // Send error in SSE format that the client JS can handle
2369 - echo "data: " . json_encode([
2370 - 'error' => true,
2371 - 'error_message' => $error_message,
2372 - 'error_code' => $error_code,
2373 - 'text' => $error_message, // Also include as text for fallback handling
2374 - 'message' => $error_message
2375 - ]) . "\n\n";
2376 - echo "data: [DONE]\n\n";
2377 - flush();
2378 - wp_die();
2379 - }
2380 - }
2381 -
2382 - // Check if the response is an error array (non-streaming mode)
2383 - if (is_array($response) && isset($response['error'])) {
2384 - wp_send_json_error([
2385 - 'error_message' => $response['error'],
2386 - 'error_code' => $response['error_code'] ?? 'api_error'
2387 - ]);
2388 - wp_die();
2389 - }
2390 -
2391 - // DEBUG: Check what we have
2392 - //error_log("=== BEFORE URL VALIDATION ===");
2393 - //error_log("current_valid_urls is empty? " . (empty($this->current_valid_urls) ? 'YES' : 'NO'));
2394 - //error_log("current_valid_urls count: " . count($this->current_valid_urls));
2395 - //error_log("current_valid_urls content: " . print_r($this->current_valid_urls, true));
2396 -
2397 - // If we get here, the response is valid text - now validate URLs
2398 - if (!empty($this->current_valid_urls)) {
2399 - //error_log("CALLING validate_and_clean_urls");
2400 - $response = $this->validate_and_clean_urls($response, $this->current_valid_urls, $session_id, $bot_id);
2401 - } else {
2402 - //error_log("SKIPPING validation - current_valid_urls is empty");
2403 - }
2404 - // ===== END URL VALIDATION =====
2405 -
2406 - // Prepare RAG context data for storage (only include documents used for context)
2407 - $rag_context_for_storage = null;
2408 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
2409 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
2410 -
2411 - if ($has_rag_data || $has_action_data) {
2412 - $rag_context_for_storage = [];
2413 -
2414 - // Add RAG/source data if available
2415 - if ($has_rag_data) {
2416 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
2417 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
2418 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
2419 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
2420 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
2421 - $rag_context_for_storage['sources_used'] = $this->last_similarity_analysis['sources_used'] ?? 0;
2422 - $rag_context_for_storage['total_chunks_used'] = $this->last_similarity_analysis['total_chunks_used'] ?? 0;
2423 - }
2424 -
2425 - // Add action analysis data if available
2426 - if ($has_action_data) {
2427 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
2428 - }
2429 - }
2430 -
2431 - // Save the cleaned response with RAG context
2432 - $this->mxchat_save_chat_message($session_id, 'bot', $response, null, $rag_context_for_storage);
2433 -
2434 - // Step 5: Save additional content if available
2435 - if (!empty($this->productCardHtml)) {
2436 - $this->mxchat_save_chat_message($session_id, 'bot', $this->productCardHtml);
2437 - }
2438 -
2439 - if (!empty($this->fallbackResponse['html'])) {
2440 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
2441 - }
2442 -
2443 - if (!empty($this->videoEmbedHtml)) {
2444 - $this->mxchat_save_chat_message($session_id, 'bot', $this->videoEmbedHtml);
2445 - }
2446 -
2447 - // Step 6: Return the response
2448 - // DEBUG: Check if newlines exist in the response
2449 - //error_log("=== MXCHAT NON-STREAMING RESPONSE DEBUG ===");
2450 - //error_log("Response has newlines: " . (strpos($response, "\n") !== false ? 'YES' : 'NO'));
2451 - //error_log("Response first 500 chars: " . substr($response, 0, 500));
2452 -
2453 - // Product cards and action html keep their existing either/or precedence;
2454 - // a queued video embed (03ba33) is APPENDED so it can coexist with both.
2455 - $additional_html = !empty($this->productCardHtml) ? $this->productCardHtml : ($this->fallbackResponse['html'] ?? '');
2456 - if (!empty($this->videoEmbedHtml)) {
2457 - $additional_html .= $this->videoEmbedHtml;
2458 - }
2459 -
2460 - $response_data = [
2461 - 'text' => $response,
2462 - 'html' => $additional_html,
2463 - 'session_id' => $session_id
2464 - ];
2465 -
2466 - // Include vectorstore error info for admin debugging (only visible to admins via testing_data)
2467 - if (!empty($this->last_vectorstore_error) && $testing_data !== null) {
2468 - $testing_data['vectorstore_error'] = $this->last_vectorstore_error;
2469 - }
2470 -
2471 - // Also pass it as a top-level field so JS can show a better error message to admins
2472 - if (!empty($this->last_vectorstore_error) && current_user_can('manage_options')) {
2473 - $response_data['vectorstore_error'] = $this->last_vectorstore_error;
2474 - }
2475 -
2476 - // Always add testing data for admins (no toggle needed)
2477 - if ($testing_data !== null) {
2478 - $response_data['testing_data'] = $testing_data;
2479 - }
2480 -
2481 - wp_send_json($response_data);
2482 - wp_die();
2483 -}
2484 -
2485 -/**
2486 - * Get bot-specific options for multi-bot functionality
2487 - * Falls back to default options if bot_id is 'default' or multi-bot add-on is not active
2488 - */
2489 -// Also debug the bot options retrieval
2490 -private function get_bot_options($bot_id = 'default') {
2491 - //error_log("MXCHAT DEBUG: get_bot_options called for bot: " . $bot_id);
2492 -
2493 - // The admin Testing tab renders the real widget as bot_id "testing", which
2494 - // is not a registered multi-bot. It must resolve the DEFAULT bot's config
2495 - // so the Testing chat behaves exactly like the front-end (same precedent
2496 - // as the Actions enabled_bots check).
2497 - if ($bot_id === 'testing') {
2498 - $bot_id = 'default';
2499 - }
2500 -
2501 - if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
2502 - //error_log("MXCHAT DEBUG: Using default options (no multi-bot or bot is 'default')");
2503 - return array();
2504 - }
2505 -
2506 - $bot_options = apply_filters('mxchat_get_bot_options', array(), $bot_id);
2507 -
2508 - if (!empty($bot_options)) {
2509 - //error_log("MXCHAT DEBUG: Got bot-specific options from filter");
2510 - if (isset($bot_options['similarity_threshold'])) {
2511 - //error_log(" - similarity_threshold: " . $bot_options['similarity_threshold']);
2512 - }
2513 - }
2514 -
2515 - return is_array($bot_options) ? $bot_options : array();
2516 -}
2517 -
2518 -/**
2519 - * Get bot-specific Pinecone configuration
2520 - * Used in the knowledge retrieval functions
2521 - */
2522 -// Also add debugging to your get_bot_pinecone_config function
2523 -private function get_bot_pinecone_config($bot_id = 'default') {
2524 - //error_log("MXCHAT DEBUG: get_bot_pinecone_config called for bot: " . $bot_id);
2525 -
2526 - // Admin Testing tab bot → resolve the DEFAULT bot's backend. Without this,
2527 - // on a multi-bot + Pinecone site the filter below gets an unknown bot id
2528 - // with an EMPTY default, returns array(), and the dispatcher silently
2529 - // searches the WordPress DB while the front-end searches Pinecone — the
2530 - // Testing panel then reports similarity results from a different KB.
2531 - if ($bot_id === 'testing') {
2532 - $bot_id = 'default';
2533 - }
2534 -
2535 - // If default bot or multi-bot add-on not active, use default Pinecone config
2536 - if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
2537 - //error_log("MXCHAT DEBUG: Using default Pinecone config (no multi-bot or bot is 'default')");
2538 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
2539 - $config = array(
2540 - 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
2541 - 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
2542 - 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
2543 - 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
2544 - );
2545 - //error_log("MXCHAT DEBUG: Default config - use_pinecone: " . ($config['use_pinecone'] ? 'true' : 'false'));
2546 - return $config;
2547 - }
2548 -
2549 - //error_log("MXCHAT DEBUG: Calling filter 'mxchat_get_bot_pinecone_config' for bot: " . $bot_id);
2550 -
2551 - // Hook for multi-bot add-on to provide bot-specific Pinecone config
2552 - $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
2553 -
2554 - if (!empty($bot_pinecone_config)) {
2555 - //error_log("MXCHAT DEBUG: Got bot-specific config from filter");
2556 - //error_log(" - use_pinecone: " . (isset($bot_pinecone_config['use_pinecone']) ? ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false') : 'not set'));
2557 - //error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'not set'));
2558 - //error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'not set'));
2559 - } else {
2560 - //error_log("MXCHAT DEBUG: Filter returned empty config!");
2561 - }
2562 -
2563 - return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
2564 -}
2565 -
2566 -
2567 -// Updated function to check intents and invoke the callback function
2568 -private function mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id) {
2569 - global $wpdb;
2570 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
2571 -
2572 - // Get the current bot_id
2573 - $current_bot_id = $this->get_current_bot_id($session_id);
2574 -
2575 - // Generate the user embedding
2576 - $user_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
2577 -
2578 - // Check if embedding generation returned an error
2579 - if (is_array($user_embedding) && isset($user_embedding['error'])) {
2580 - $error_message = $user_embedding['error'];
2581 - $error_code = $user_embedding['error_code'] ?? 'embedding_error';
2582 -
2583 - // FIXED: Send error in appropriate format based on streaming mode
2584 - if ($this->is_streaming) {
2585 - echo "data: " . json_encode([
2586 - 'error' => true,
2587 - 'error_message' => $error_message,
2588 - 'error_code' => $error_code,
2589 - 'text' => $error_message,
2590 - 'message' => $error_message
2591 - ]) . "\n\n";
2592 - echo "data: [DONE]\n\n";
2593 - flush();
2594 - } else {
2595 - wp_send_json_error([
2596 - 'error_message' => $error_message,
2597 - 'error_code' => $error_code
2598 - ]);
2599 - }
2600 - wp_die();
2601 - }
2602 -
2603 - // Check if embedding is valid
2604 - if (!is_array($user_embedding) || empty($user_embedding)) {
2605 - $error_message = esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat');
2606 -
2607 - // FIXED: Send error in appropriate format based on streaming mode
2608 - if ($this->is_streaming) {
2609 - echo "data: " . json_encode([
2610 - 'error' => true,
2611 - 'error_message' => $error_message,
2612 - 'error_code' => 'invalid_embedding',
2613 - 'text' => $error_message,
2614 - 'message' => $error_message
2615 - ]) . "\n\n";
2616 - echo "data: [DONE]\n\n";
2617 - flush();
2618 - } else {
2619 - wp_send_json_error([
2620 - 'error_message' => $error_message,
2621 - 'error_code' => 'invalid_embedding'
2622 - ]);
2623 - }
2624 - wp_die();
2625 - }
2626 -
2627 - // Fetch intents from the database
2628 - $table_name = $wpdb->prefix . 'mxchat_intents';
2629 - if ($chat_mode === 'agent') {
2630 - $query = $wpdb->prepare(
2631 - "SELECT * FROM $table_name WHERE callback_function = %s AND (enabled = 1 OR enabled IS NULL)",
2632 - 'mxchat_handle_switch_to_chatbot_intent'
2633 - );
2634 - $intents = $wpdb->get_results($query);
2635 - } else {
2636 - $intents = $wpdb->get_results("SELECT * FROM $table_name WHERE enabled = 1 OR enabled IS NULL");
2637 - }
2638 -
2639 - if (empty($intents)) {
2640 - return false;
2641 - }
2642 -
2643 - // Prefetch individual phrase vectors from wp_mxchat_intent_phrases (grouped by intent_id)
2644 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
2645 - $phrases_by_intent = [];
2646 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
2647 - $all_phrases = $wpdb->get_results("SELECT intent_id, phrase, embedding_vector FROM $phrases_table");
2648 - foreach ($all_phrases as $p) {
2649 - $phrases_by_intent[$p->intent_id][] = $p;
2650 - }
2651 - }
2652 -
2653 - $highest_similarity = -INF;
2654 - $matched_intent = null;
2655 -
2656 - // Array to store action analysis for testing panel
2657 - $action_analysis = [];
2658 -
2659 - foreach ($intents as $intent) {
2660 - // Additional check for enabled state
2661 - $is_enabled = isset($intent->enabled) ? (bool)$intent->enabled : true;
2662 - if (!$is_enabled) {
2663 - continue;
2664 - }
2665 -
2666 - // Check if this action is enabled for the current bot
2667 - if (!$this->is_action_enabled_for_bot($intent, $current_bot_id)) {
2668 - continue;
2669 - }
2670 -
2671 - $best_similarity = -INF;
2672 - $matched_phrase_text = '';
2673 -
2674 - // Check legacy embedding vector (existing behavior)
2675 - $intent_embedding_serialized = $intent->embedding_vector;
2676 - $intent_embedding = $intent_embedding_serialized
2677 - ? unserialize($intent_embedding_serialized, ['allowed_classes' => false])
2678 - : null;
2679 -
2680 - if (is_array($intent_embedding) && !empty($intent_embedding)) {
2681 - $legacy_similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $intent_embedding);
2682 - if ($legacy_similarity > $best_similarity) {
2683 - $best_similarity = $legacy_similarity;
2684 - $matched_phrase_text = 'legacy';
2685 - }
2686 - }
2687 -
2688 - // Check individual phrase vectors
2689 - if (isset($phrases_by_intent[$intent->id])) {
2690 - foreach ($phrases_by_intent[$intent->id] as $phrase_row) {
2691 - $phrase_embedding = $phrase_row->embedding_vector
2692 - ? unserialize($phrase_row->embedding_vector, ['allowed_classes' => false])
2693 - : null;
2694 - if (!is_array($phrase_embedding)) {
2695 - continue;
2696 - }
2697 - $phrase_similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $phrase_embedding);
2698 - if ($phrase_similarity > $best_similarity) {
2699 - $best_similarity = $phrase_similarity;
2700 - $matched_phrase_text = $phrase_row->phrase;
2701 - }
2702 - }
2703 - }
2704 -
2705 - // Skip if no valid embedding was found at all
2706 - if ($best_similarity === -INF) {
2707 - continue;
2708 - }
2709 -
2710 - $similarity = $best_similarity;
2711 - $intent_threshold = isset($intent->similarity_threshold) ? $intent->similarity_threshold : 0.85;
2712 -
2713 - // Store action analysis data for testing panel
2714 - $action_analysis[] = [
2715 - 'intent_label' => $intent->intent_label,
2716 - 'callback_function' => $intent->callback_function,
2717 - 'similarity' => round($similarity, 4),
2718 - 'similarity_percentage' => round($similarity * 100, 2),
2719 - 'threshold' => $intent_threshold,
2720 - 'threshold_percentage' => round($intent_threshold * 100, 2),
2721 - 'above_threshold' => $similarity >= $intent_threshold,
2722 - 'matched_phrase' => $matched_phrase_text,
2723 - 'triggered' => false // Will be updated below if this intent is triggered
2724 - ];
2725 -
2726 - if ($similarity >= $intent_threshold && $similarity > $highest_similarity) {
2727 - $highest_similarity = $similarity;
2728 - $matched_intent = $intent;
2729 - }
2730 - }
2731 -
2732 - // Mark the triggered action if any
2733 - if ($matched_intent) {
2734 - foreach ($action_analysis as &$action) {
2735 - if ($action['intent_label'] === $matched_intent->intent_label) {
2736 - $action['triggered'] = true;
2737 - break;
2738 - }
2739 - }
2740 - }
2741 -
2742 - // Sort actions by similarity (highest first) and store for testing panel
2743 - usort($action_analysis, function($a, $b) {
2744 - return $b['similarity'] <=> $a['similarity'];
2745 - });
2746 -
2747 - // Store action analysis for testing panel capture
2748 - $this->last_action_analysis = $action_analysis;
2749 -
2750 - // Around line 715 in your mxchat_check_intent_and_invoke_callback function
2751 - if ($matched_intent) {
2752 - // If the callback is a method on this instance (core callback), call it directly
2753 - if (method_exists($this, $matched_intent->callback_function)) {
2754 - $callback_result = call_user_func(
2755 - [$this, $matched_intent->callback_function],
2756 - $message,
2757 - $user_id,
2758 - $session_id,
2759 - $matched_intent,
2760 - $user_context ?? null
2761 - );
2762 - } else {
2763 - // Otherwise, use apply_filters for add-on callbacks
2764 - $callback_result = apply_filters(
2765 - $matched_intent->callback_function,
2766 - false,
2767 - $message,
2768 - $user_id,
2769 - $session_id,
2770 - $matched_intent
2771 - );
2772 - }
2773 -
2774 - // Handle the callback result properly
2775 - if ($callback_result !== false) {
2776 - // If callback returned an array with chat_mode, use it directly
2777 - if (is_array($callback_result) && isset($callback_result['chat_mode'])) {
2778 - $this->fallbackResponse = $callback_result;
2779 - return $callback_result; // Return the full array
2780 - } else {
2781 - $this->fallbackResponse = $callback_result;
2782 - return true;
2783 - }
2784 - }
2785 - }
2786 -
2787 - return false;
2788 -}
2789 -
2790 -/**
2791 - * Check if an action is enabled for a specific bot
2792 - */
2793 -private function is_action_enabled_for_bot($intent, $bot_id) {
2794 - // If enabled_bots column doesn't exist or is null, assume it's enabled for all bots (backward compatibility)
2795 - if (!isset($intent->enabled_bots) || empty($intent->enabled_bots)) {
2796 - return true;
2797 - }
2798 -
2799 - $enabled_bots = json_decode($intent->enabled_bots, true);
2800 -
2801 - // If JSON decode fails or returns empty array, assume enabled for all (backward compatibility)
2802 - if (!is_array($enabled_bots) || empty($enabled_bots)) {
2803 - return true;
2804 - }
2805 -
2806 - // Admin testing tab uses bot_id "testing" — treat it as "default" so all
2807 - // default-bot actions are testable from the admin panel
2808 - if ($bot_id === 'testing') {
2809 - $bot_id = 'default';
2810 - }
2811 -
2812 - // Check if the current bot is in the enabled bots list
2813 - return in_array($bot_id, $enabled_bots);
2814 -}
2815 -
2816 -// Helper function to clear PDF and Word document related transients
2817 -private function clear_pdf_transients($session_id) {
2818 - // PDF transients
2819 - delete_transient('mxchat_pdf_url_' . $session_id);
2820 - delete_transient('mxchat_pdf_embeddings_' . $session_id);
2821 - delete_transient('mxchat_include_pdf_in_context_' . $session_id);
2822 - delete_transient('mxchat_waiting_for_pdf_url_' . $session_id);
2823 -
2824 - // Word document transients
2825 - delete_transient('mxchat_word_url_' . $session_id);
2826 - delete_transient('mxchat_word_filename_' . $session_id);
2827 - delete_transient('mxchat_word_embeddings_' . $session_id);
2828 - delete_transient('mxchat_include_word_in_context_' . $session_id);
2829 - delete_transient('mxchat_waiting_for_word_' . $session_id);
2830 -}
2831 -
2832 -
2833 -
2834 -//verified good
2835 -public function mxchat_handle_email_capture($message, $user_id, $session_id) {
2836 - // Get the user's original instruction/message
2837 - $user_instruction = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Please provide your email address.", 'mxchat'));
2838 -
2839 - // Set instruction for AI - just pass along what the user wanted to say
2840 - $this->current_action_instruction = $user_instruction;
2841 -
2842 - // Set the transient to track email capture flow
2843 - set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
2844 -
2845 - // Return false to let the AI generate the response
2846 - return false;
2847 -}
2848 -
2849 -public function mxchat_generate_image($message, $user_id, $session_id) {
2850 - //error_log("Starting image generation for message: " . $message);
2851 -
2852 - // Prepare a prompt for OpenAI image generation
2853 - $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
2854 -
2855 - // Opt-in routing: when 'custom_provider_for_images' is on, route image gen
2856 - // through the configured Custom (OpenAI-compatible) /images/generations route.
2857 - if (!empty($this->options['custom_provider_for_images']) && $this->options['custom_provider_for_images'] === 'on') {
2858 - $image_response = $this->mxchat_generate_custom_image($prompt);
2859 - } else {
2860 - // Use the existing OpenAI API key
2861 - $openai_api_key = sanitize_text_field($this->options['api_key']);
2862 - // Call OpenAI GPT Image to generate an image
2863 - $image_response = $this->mxchat_generate_openai_image($prompt, $openai_api_key);
2864 - }
2865 -
2866 - // Check if the response contains an image URL
2867 - if (isset($image_response['imageUrl'])) {
2868 - $image_url = esc_url_raw($image_response['imageUrl']);
2869 -
2870 - // Construct the HTML with a CSS class instead of inline styles
2871 - $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
2872 - $response_text = esc_html__('Here is the image I generated:', 'mxchat');
2873 -
2874 - // Save the bot message with both text and HTML
2875 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2876 - $this->mxchat_save_chat_message($session_id, 'bot', $response_html);
2877 -
2878 - // Set the fallback response for the chat handler
2879 - $this->fallbackResponse = [
2880 - 'text' => $response_text,
2881 - 'html' => $response_html,
2882 - 'images' => [$image_url]
2883 - ];
2884 -
2885 - // For debugging/verification - Use json_encode to verify what's being set
2886 - //error_log("Image generation successful - fallbackResponse set: " . json_encode($this->fallbackResponse));
2887 -
2888 - // Return the response directly instead of relying on the property
2889 - return $this->fallbackResponse;
2890 - } else {
2891 - $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
2892 -
2893 - // Save the error message
2894 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2895 -
2896 - // Set the fallback response for the chat handler
2897 - $this->fallbackResponse = [
2898 - 'text' => $response_text,
2899 - 'html' => '',
2900 - 'images' => []
2901 - ];
2902 -
2903 - //error_log("DALL-E image generation error: " . esc_html($image_response['error'] ?? 'Unknown error.'));
2904 - //error_log("Error fallbackResponse set: " . json_encode($this->fallbackResponse));
2905 -
2906 - // Return the response directly instead of relying on the property
2907 - return $this->fallbackResponse;
2908 - }
2909 -}
2910 -
2911 -public function mxchat_generate_gemini_image($message, $user_id, $session_id) {
2912 - $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
2913 -
2914 - $gemini_api_key = sanitize_text_field($this->options['gemini_api_key'] ?? '');
2915 - if (empty($gemini_api_key)) {
2916 - $response_text = esc_html__("Gemini API key is not configured.", 'mxchat');
2917 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2918 - return ['text' => $response_text, 'html' => '', 'images' => []];
2919 - }
2920 -
2921 - $image_response = $this->mxchat_generate_imagen_image($prompt, $gemini_api_key);
2922 -
2923 - if (isset($image_response['imageUrl'])) {
2924 - $image_url = esc_url_raw($image_response['imageUrl']);
2925 -
2926 - $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
2927 - $response_text = esc_html__('Here is the image I generated:', 'mxchat');
2928 -
2929 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2930 - $this->mxchat_save_chat_message($session_id, 'bot', $response_html);
2931 -
2932 - $this->fallbackResponse = [
2933 - 'text' => $response_text,
2934 - 'html' => $response_html,
2935 - 'images' => [$image_url]
2936 - ];
2937 -
2938 - return $this->fallbackResponse;
2939 - } else {
2940 - $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
2941 -
2942 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
2943 -
2944 - $this->fallbackResponse = [
2945 - 'text' => $response_text,
2946 - 'html' => '',
2947 - 'images' => []
2948 - ];
2949 -
2950 - return $this->fallbackResponse;
2951 - }
2952 -}
2953 -
2954 -private function mxchat_save_generated_image($base64_data, $mime_type = 'image/png', $prefix = 'mxchat-generated') {
2955 - // Map the real mime type to a matching file extension so the saved file's
2956 - // extension always agrees with its bytes. A mismatch (e.g. Imagen returning
2957 - // webp bytes that were written into a ".png" file) makes the browser refuse
2958 - // to render the image even though the file saved successfully and the bot
2959 - // reported success — that was the Gemini/Imagen "image never renders" bug.
2960 - // OpenAI + custom-provider paths pass 'image/png' explicitly, so they are
2961 - // unaffected; this only matters for providers that return another type.
2962 - $mime_to_ext = [
2963 - 'image/jpeg' => 'jpg',
2964 - 'image/jpg' => 'jpg',
2965 - 'image/png' => 'png',
2966 - 'image/webp' => 'webp',
2967 - 'image/gif' => 'gif',
2968 - ];
2969 - $mime_type = strtolower(trim((string) $mime_type));
2970 - if (isset($mime_to_ext[$mime_type])) {
2971 - $extension = $mime_to_ext[$mime_type];
2972 - } else {
2973 - // Unknown/unsupported type: fall back to png and normalize the stored
2974 - // mime so the attachment record and the file extension stay consistent.
2975 - $extension = 'png';
2976 - $mime_type = 'image/png';
2977 - }
2978 - $filename = sanitize_file_name($prefix . '-' . wp_generate_uuid4() . '.' . $extension);
2979 - $decoded = base64_decode($base64_data);
2980 -
2981 - if ($decoded === false) {
2982 - return new \WP_Error('decode_failed', esc_html__('Failed to decode image data.', 'mxchat'));
2983 - }
2984 -
2985 - $upload = wp_upload_bits($filename, null, $decoded);
2986 -
2987 - if (!empty($upload['error'])) {
2988 - return new \WP_Error('upload_failed', $upload['error']);
2989 - }
2990 -
2991 - $attach_id = wp_insert_attachment([
2992 - 'post_mime_type' => $mime_type,
2993 - 'post_title' => $prefix,
2994 - 'post_content' => '',
2995 - 'post_status' => 'inherit',
2996 - ], $upload['file']);
2997 -
2998 - if (is_wp_error($attach_id)) {
2999 - return $attach_id;
3000 - }
3001 -
3002 - require_once ABSPATH . 'wp-admin/includes/image.php';
3003 - $metadata = wp_generate_attachment_metadata($attach_id, $upload['file']);
3004 - wp_update_attachment_metadata($attach_id, $metadata);
3005 -
3006 - return esc_url_raw(wp_get_attachment_url($attach_id));
3007 -}
3008 -
3009 -private function mxchat_generate_openai_image($prompt, $api_key, $model = 'gpt-image-1', $timeout = 60) {
3010 - $api_url = 'https://api.openai.com/v1/images/generations';
3011 - $body = json_encode([
3012 - 'prompt' => sanitize_text_field($prompt),
3013 - 'n' => 1,
3014 - 'size' => '1024x1024',
3015 - 'quality' => 'medium',
3016 - 'output_format' => 'png',
3017 - 'model' => sanitize_text_field($model),
3018 - ]);
3019 -
3020 - $args = [
3021 - 'body' => $body,
3022 - 'headers' => [
3023 - 'Content-Type' => 'application/json',
3024 - 'Authorization' => 'Bearer ' . sanitize_text_field($api_key),
3025 - ],
3026 - 'method' => 'POST',
3027 - 'timeout' => absint($timeout),
3028 - ];
3029 -
3030 - $response = wp_remote_post($api_url, $args);
3031 -
3032 - if (is_wp_error($response)) {
3033 - return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
3034 - }
3035 -
3036 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3037 -
3038 - $b64 = $response_body['data'][0]['b64_json'] ?? $response_body['data'][0]['b64'] ?? null;
3039 - if ($b64) {
3040 - $saved_url = $this->mxchat_save_generated_image($b64, 'image/png', 'mxchat-openai');
3041 - if (is_wp_error($saved_url)) {
3042 - return ['error' => $saved_url->get_error_message()];
3043 - }
3044 - return ['imageUrl' => $saved_url];
3045 - } else {
3046 - return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
3047 - }
3048 -}
3049 -
3050 -/**
3051 - * Generate an image via a Custom (OpenAI-compatible) provider's /images/generations route.
3052 - * Only called when the opt-in 'custom_provider_for_images' setting is on.
3053 - */
3054 -private function mxchat_generate_custom_image($prompt, $timeout = 90) {
3055 - $cfg = $this->mxchat_resolve_custom_provider();
3056 - if (empty($cfg['base_url'])) {
3057 - return ['error' => esc_html__('Custom provider Base URL is not configured.', 'mxchat')];
3058 - }
3059 - $url = $cfg['base_url'] . '/images/generations';
3060 - if (!empty($cfg['api_version'])) {
3061 - $url .= (strpos($url, '?') === false ? '?' : '&') . 'api-version=' . rawurlencode($cfg['api_version']);
3062 - }
3063 - $body = wp_json_encode([
3064 - 'prompt' => sanitize_text_field($prompt),
3065 - 'n' => 1,
3066 - 'size' => '1024x1024',
3067 - 'model' => $cfg['model'],
3068 - ]);
3069 - $response = wp_remote_post($url, [
3070 - 'headers' => $this->mxchat_custom_provider_assoc_headers($cfg),
3071 - 'body' => $body,
3072 - 'method' => 'POST',
3073 - 'timeout' => absint($timeout),
3074 - ]);
3075 - if (is_wp_error($response)) {
3076 - return ['error' => esc_html__('Error generating image (custom provider): ', 'mxchat') . $response->get_error_message()];
3077 - }
3078 - $resp = json_decode(wp_remote_retrieve_body($response), true);
3079 - // Try b64 first (matches OpenAI shape), then url-based fallback.
3080 - $b64 = $resp['data'][0]['b64_json'] ?? $resp['data'][0]['b64'] ?? null;
3081 - if ($b64) {
3082 - $saved = $this->mxchat_save_generated_image($b64, 'image/png', 'mxchat-custom');
3083 - if (is_wp_error($saved)) {
3084 - return ['error' => $saved->get_error_message()];
3085 - }
3086 - return ['imageUrl' => $saved];
3087 - }
3088 - $remote_url = $resp['data'][0]['url'] ?? null;
3089 - if ($remote_url) {
3090 - return ['imageUrl' => esc_url_raw($remote_url)];
3091 - }
3092 - $err_msg = $resp['error']['message'] ?? esc_html__('Custom provider did not return an image.', 'mxchat');
3093 - return ['error' => esc_html($err_msg)];
3094 -}
3095 -
3096 -private function mxchat_generate_imagen_image($prompt, $api_key, $timeout = 60) {
3097 - $api_url = 'https://generativelanguage.googleapis.com/v1beta/models/imagen-4.0-generate-001:predict';
3098 -
3099 - $body = json_encode([
3100 - 'instances' => [['prompt' => sanitize_text_field($prompt)]],
3101 - 'parameters' => [
3102 - 'sampleCount' => 1,
3103 - 'aspectRatio' => '1:1',
3104 - ],
3105 - ]);
3106 -
3107 - $args = [
3108 - 'body' => $body,
3109 - 'headers' => [
3110 - 'Content-Type' => 'application/json',
3111 - 'x-goog-api-key' => sanitize_text_field($api_key),
3112 - ],
3113 - 'method' => 'POST',
3114 - 'timeout' => absint($timeout),
3115 - ];
3116 -
3117 - $response = wp_remote_post($api_url, $args);
3118 -
3119 - if (is_wp_error($response)) {
3120 - return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
3121 - }
3122 -
3123 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3124 -
3125 - $b64 = $response_body['predictions'][0]['bytesBase64Encoded'] ?? $response_body['predictions'][0]['imageBytes'] ?? null;
3126 - if ($b64) {
3127 - $mime = $response_body['predictions'][0]['mimeType'] ?? 'image/png';
3128 - $saved_url = $this->mxchat_save_generated_image($b64, $mime, 'mxchat-gemini');
3129 - if (is_wp_error($saved_url)) {
3130 - return ['error' => $saved_url->get_error_message()];
3131 - }
3132 - return ['imageUrl' => $saved_url];
3133 - } else {
3134 - return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
3135 - }
3136 -}
3137 -
3138 -/**
3139 - * Handle web search requests.
3140 - *
3141 - * Sends the refined search query to the Brave Search API and uses the
3142 - * results to generate a conversational response with the AI model.
3143 - *
3144 - * @since 1.0.0
3145 - * @param string $message The user's search query.
3146 - * @param string $user_id The user identifier.
3147 - * @param string $session_id The current session ID.
3148 - * @return array Response array containing text with embedded HTML links
3149 - */
3150 -public function mxchat_handle_search_request($message, $user_id, $session_id) {
3151 - // Step 1: Interpret and refine the search query
3152 - $refined_search_query = $this->mxchat_interpret_search_query($message);
3153 - if (empty($refined_search_query)) {
3154 - return array(
3155 - 'text' => esc_html__('I apologize, but could you please rephrase your search request?', 'mxchat'),
3156 - 'html' => ''
3157 - );
3158 - }
3159 -
3160 - // Retrieve and validate API settings
3161 - $options = get_option('mxchat_options');
3162 - $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
3163 - $results_count = isset($options['brave_results_count']) ? absint($options['brave_results_count']) : 5;
3164 -
3165 - if (empty($api_key)) {
3166 - return array(
3167 - 'text' => esc_html__('Search functionality is temporarily unavailable. Please try again later.', 'mxchat'),
3168 - 'html' => ''
3169 - );
3170 - }
3171 -
3172 - // Build the API request URL
3173 - $api_url = add_query_arg(
3174 - array(
3175 - 'q' => rawurlencode($refined_search_query),
3176 - 'count' => $results_count,
3177 - 'text_decorations' => 'true',
3178 - 'rich_data' => 'true',
3179 - ),
3180 - 'https://api.search.brave.com/res/v1/web/search'
3181 - );
3182 -
3183 - // Attempt to retrieve cached results first
3184 - $transient_key = 'mxchat_search_' . md5($refined_search_query);
3185 - $results = get_transient($transient_key);
3186 -
3187 - if (false === $results) {
3188 - // SECURITY FIX: Changed to wp_safe_remote_get
3189 - $response = wp_safe_remote_get(
3190 - $api_url,
3191 - array(
3192 - 'headers' => array(
3193 - 'Accept' => 'application/json',
3194 - 'Accept-Encoding' => 'gzip',
3195 - 'X-Subscription-Token'=> $api_key,
3196 - ),
3197 - 'timeout' => 10,
3198 - )
3199 - );
3200 -
3201 - if (is_wp_error($response)) {
3202 - return array(
3203 - 'text' => esc_html__('I encountered an error while searching. Please try again.', 'mxchat'),
3204 - 'html' => ''
3205 - );
3206 - }
3207 -
3208 - $results = json_decode(wp_remote_retrieve_body($response), true);
3209 -
3210 - if (json_last_error() !== JSON_ERROR_NONE) {
3211 - return array(
3212 - 'text' => esc_html__('I received an invalid response from the search service.', 'mxchat'),
3213 - 'html' => ''
3214 - );
3215 - }
3216 -
3217 - // Cache results for one hour
3218 - set_transient($transient_key, $results, HOUR_IN_SECONDS);
3219 - }
3220 -
3221 - // Process results
3222 - if (!empty($results['web']['results']) && is_array($results['web']['results'])) {
3223 - // Create a more straightforward summary with HTML links
3224 - $search_results_text = '';
3225 -
3226 - // Add a simple intro
3227 - $search_results_text .= sprintf(
3228 - esc_html__("Here's what I found about '%s':", 'mxchat'),
3229 - esc_html($refined_search_query)
3230 - );
3231 -
3232 - // Add the top results with HTML links
3233 - foreach (array_slice($results['web']['results'], 0, 5) as $result) {
3234 - $title = isset($result['title']) ? wp_strip_all_tags($result['title']) : '';
3235 - $url = isset($result['url']) ? esc_url($result['url']) : '';
3236 - $description = isset($result['description']) ? wp_strip_all_tags($result['description']) : '';
3237 -
3238 - // Add a line break after the intro
3239 - $search_results_text .= '<br><br>';
3240 -
3241 - // Add title as a link
3242 - $search_results_text .= sprintf(
3243 - '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a><br>',
3244 - $url,
3245 - $title
3246 - );
3247 -
3248 - // Add a condensed description
3249 - $search_results_text .= sprintf("%s", $description);
3250 - }
3251 -
3252 - // Save to chat history
3253 - $this->mxchat_save_chat_message($session_id, 'bot', $search_results_text);
3254 -
3255 - // Return the formatted text with embedded HTML links
3256 - return array(
3257 - 'text' => $search_results_text,
3258 - 'html' => ''
3259 - );
3260 - } else {
3261 - return array(
3262 - 'text' => sprintf(
3263 - esc_html__('I searched for "%s" but couldn\'t find any relevant results. Would you like to try different search terms?', 'mxchat'),
3264 - esc_html($refined_search_query)
3265 - ),
3266 - 'html' => ''
3267 - );
3268 - }
3269 -}
3270 -
3271 -//very good
3272 -/**
3273 - * Handle image search requests from the chatbot
3274 - *
3275 - * @param string $message The user's search query
3276 - * @param int $user_id The user's ID
3277 - * @param string $session_id The chat session ID
3278 - * @return array Response array with text and HTML content
3279 - */
3280 -public function mxchat_handle_image_search_request($message, $user_id, $session_id) {
3281 - // Step 1: Interpret the search query using the user's selected AI model
3282 - $refined_search_query = $this->mxchat_interpret_search_query($message);
3283 -
3284 - // If no query was interpreted, return a fallback message
3285 - if (empty($refined_search_query)) {
3286 - return array(
3287 - 'text' => __("I'm sorry, I couldn't interpret your search query. Please specify what you'd like to see images of.", 'mxchat'),
3288 - 'html' => "",
3289 - );
3290 - }
3291 -
3292 - // Brave API URL
3293 - $api_url = 'https://api.search.brave.com/res/v1/images/search';
3294 -
3295 - // Retrieve Brave API settings
3296 - $options = get_option('mxchat_options');
3297 - $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
3298 -
3299 - if (empty($api_key)) {
3300 - return array(
3301 - 'text' => __("API key is not configured. Please set it in the Brave Search Settings.", 'mxchat'),
3302 - 'html' => "",
3303 - );
3304 - }
3305 -
3306 - $image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
3307 - $safe_search = isset($options['brave_safe_search']) ? sanitize_text_field($options['brave_safe_search']) : 'strict';
3308 -
3309 - // Append query parameters based on settings
3310 - $api_url = add_query_arg([
3311 - 'q' => rawurlencode($refined_search_query),
3312 - 'count' => $image_count,
3313 - 'safesearch' => $safe_search,
3314 - ], $api_url);
3315 -
3316 - // Implement caching
3317 - $transient_key = 'mxchat_image_search_' . md5($refined_search_query);
3318 - $body = get_transient($transient_key);
3319 -
3320 - if (false === $body) {
3321 - $args = [
3322 - 'headers' => [
3323 - 'Accept' => 'application/json',
3324 - 'Accept-Encoding' => 'gzip',
3325 - 'X-Subscription-Token' => $api_key,
3326 - ],
3327 - 'timeout' => 10,
3328 - ];
3329 -
3330 - // SECURITY FIX: Changed to wp_safe_remote_get
3331 - $response = wp_safe_remote_get($api_url, $args);
3332 -
3333 - if (is_wp_error($response)) {
3334 - return array(
3335 - 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
3336 - 'html' => "",
3337 - );
3338 - }
3339 -
3340 - $body = json_decode(wp_remote_retrieve_body($response), true);
3341 - set_transient($transient_key, $body, HOUR_IN_SECONDS);
3342 - }
3343 -
3344 - // Process the API response
3345 - if (isset($body['results']) && is_array($body['results']) && count($body['results']) > 0) {
3346 - $html_output = '<div class="mxchat-image-gallery">';
3347 -
3348 - // Get the configured image count (1-6)
3349 - $display_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
3350 - $display_count = min($display_count, count($body['results'])); // Make sure we don't exceed available images
3351 -
3352 - // Use only the requested number of images
3353 - for ($i = 0; $i < $display_count; $i++) {
3354 - $image = $body['results'][$i];
3355 - $image_url = isset($image['url']) ? esc_url($image['url']) : '';
3356 - $thumbnail_url = isset($image['thumbnail']['src']) ? esc_url($image['thumbnail']['src']) : '';
3357 - $title = isset($image['title']) ? esc_html($image['title']) : esc_html__('Image', 'mxchat');
3358 -
3359 - if ($image_url && $thumbnail_url) {
3360 - $html_output .= '<div class="mxchat-image-item">';
3361 - $html_output .= '<strong class="mxchat-image-title">' . $title . '</strong>';
3362 - $html_output .= '<a href="' . $image_url . '" target="_blank" rel="noopener noreferrer" class="mxchat-image-link">';
3363 - $html_output .= '<img src="' . $thumbnail_url . '" alt="' . $title . '" class="mxchat-image-thumbnail">';
3364 - $html_output .= '</a></div>';
3365 - }
3366 - }
3367 -
3368 - $html_output .= '</div>';
3369 -
3370 - // Create response text
3371 - $response_text = sprintf(__("Here are some images of %s:", 'mxchat'), $refined_search_query);
3372 -
3373 - // Save both response text and HTML to chat history
3374 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
3375 - $this->mxchat_save_chat_message($session_id, 'bot', $html_output);
3376 -
3377 - // Return the combined response
3378 - return array(
3379 - 'text' => $response_text,
3380 - 'html' => $html_output,
3381 - );
3382 - } else {
3383 - $response_text = __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat');
3384 -
3385 - // Save the error message to chat history
3386 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
3387 -
3388 - return array(
3389 - 'text' => $response_text,
3390 - 'html' => "",
3391 - );
3392 - }
3393 -}
3394 -
3395 -/**
3396 - * Interpret the search query using the user's selected AI model
3397 - *
3398 - * @param string $user_query The original query from the user
3399 - * @return string The refined search query
3400 - */
3401 -public function mxchat_interpret_search_query($user_query) {
3402 - $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');
3403 -
3404 - // Get options and determine the selected model
3405 - $options = $this->options ?? get_option('mxchat_options');
3406 - $selected_model = isset($options['model']) ? $options['model'] : 'gpt-5.1-chat-latest';
3407 -
3408 - // Custom (OpenAI-compatible) provider routes by model id, not prefix.
3409 - if ($selected_model === 'custom-provider') {
3410 - return $this->interpret_query_with_custom($user_query, $system_prompt);
3411 - }
3412 -
3413 - // Extract model prefix to determine the provider
3414 - $model_parts = explode('-', $selected_model);
3415 - $provider = strtolower($model_parts[0]);
3416 -
3417 - // Determine which API key to use based on the provider
3418 - switch ($provider) {
3419 - case 'gemini':
3420 - $api_key = isset($options['gemini_api_key']) ? sanitize_text_field($options['gemini_api_key']) : '';
3421 - if (empty($api_key)) {
3422 - return sanitize_text_field($user_query); // Default to original query if API key missing
3423 - }
3424 - return $this->interpret_query_with_gemini($user_query, $system_prompt, $api_key, $selected_model);
3425 -
3426 - case 'claude':
3427 - $api_key = isset($options['claude_api_key']) ? sanitize_text_field($options['claude_api_key']) : '';
3428 - if (empty($api_key)) {
3429 - return sanitize_text_field($user_query);
3430 - }
3431 - return $this->interpret_query_with_claude($user_query, $system_prompt, $api_key, $selected_model);
3432 -
3433 - case 'grok':
3434 - $api_key = isset($options['xai_api_key']) ? sanitize_text_field($options['xai_api_key']) : '';
3435 - if (empty($api_key)) {
3436 - return sanitize_text_field($user_query);
3437 - }
3438 - return $this->interpret_query_with_xai($user_query, $system_prompt, $api_key, $selected_model);
3439 -
3440 - case 'deepseek':
3441 - $api_key = isset($options['deepseek_api_key']) ? sanitize_text_field($options['deepseek_api_key']) : '';
3442 - if (empty($api_key)) {
3443 - return sanitize_text_field($user_query);
3444 - }
3445 - return $this->interpret_query_with_deepseek($user_query, $system_prompt, $api_key, $selected_model);
3446 -
3447 - case 'gpt':
3448 - default:
3449 - // Default to OpenAI for custom models or unrecognized prefixes
3450 - $api_key = isset($options['api_key']) ? sanitize_text_field($options['api_key']) : '';
3451 - if (empty($api_key)) {
3452 - return sanitize_text_field($user_query);
3453 - }
3454 - return $this->interpret_query_with_openai($user_query, $system_prompt, $api_key, $selected_model);
3455 - }
3456 -}
3457 -
3458 -/**
3459 - * Interpret query against the configured Custom (OpenAI-compatible) provider.
3460 - * Uses the same base URL + auth scheme as the chat dispatcher.
3461 - */
3462 -private function interpret_query_with_custom($user_query, $system_prompt) {
3463 - $cfg = $this->mxchat_resolve_custom_provider();
3464 - if (empty($cfg['base_url'])) {
3465 - return sanitize_text_field($user_query);
3466 - }
3467 - // plan-mxchat-20260715-7124f4: a custom OpenAI-compatible endpoint pointed at
3468 - // a gpt-5-class model rejects temperature!=1 and the legacy max_tokens key.
3469 - // Byte-identical for ordinary custom models (temperature kept, max_tokens
3470 - // used); only gpt-5-class custom models change (best-effort — custom
3471 - // endpoints vary).
3472 - $token_key = $this->mxchat_openai_token_param_for($cfg['model']);
3473 - $payload = [
3474 - 'model' => $cfg['model'],
3475 - 'messages' => [
3476 - ['role' => 'system', 'content' => $system_prompt],
3477 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
3478 - ],
3479 - $token_key => 20,
3480 - ];
3481 - if ($this->mxchat_openai_supports_temperature_for($cfg['model'])) {
3482 - $payload['temperature'] = 0.2;
3483 - }
3484 - $args = [
3485 - 'headers' => $this->mxchat_custom_provider_assoc_headers($cfg),
3486 - 'body' => wp_json_encode($payload),
3487 - 'method' => 'POST',
3488 - 'timeout' => 15,
3489 - ];
3490 - $response = wp_remote_post($cfg['chat_url'], $args);
3491 - if (is_wp_error($response)) {
3492 - return sanitize_text_field($user_query);
3493 - }
3494 - $body = json_decode(wp_remote_retrieve_body($response), true);
3495 - return isset($body['choices'][0]['message']['content'])
3496 - ? sanitize_text_field(trim($body['choices'][0]['message']['content']))
3497 - : sanitize_text_field($user_query);
3498 -}
3499 -
3500 -/**
3501 - * Convert the colon-style header list returned by mxchat_resolve_custom_provider
3502 - * into the assoc-array form wp_remote_post expects.
3503 - */
3504 -private function mxchat_custom_provider_assoc_headers($cfg) {
3505 - $headers = ['Content-Type' => 'application/json'];
3506 - if (!empty($cfg['api_key'])) {
3507 - if (($cfg['auth_scheme'] ?? 'bearer') === 'api-key') {
3508 - $headers['api-key'] = $cfg['api_key'];
3509 - } else {
3510 - $headers['Authorization'] = 'Bearer ' . $cfg['api_key'];
3511 - }
3512 - }
3513 - return $headers;
3514 -}
3515 -
3516 -/**
3517 - * Interpret query using OpenAI models
3518 - */
3519 -private function interpret_query_with_openai($user_query, $system_prompt, $api_key, $model = 'gpt-5.1-chat-latest') {
3520 - $url = 'https://api.openai.com/v1/chat/completions';
3521 - // plan-mxchat-20260715-7124f4: the default chat model is gpt-5.1-chat-latest
3522 - // and every gpt-5* rejects both a non-default temperature and the legacy
3523 - // max_tokens key (400). This call swallowed the 400 and silently degraded to
3524 - // the raw query on every gpt-5 install, quietly disabling product/image
3525 - // search-query interpretation. Derive capability from the core catalog
3526 - // (dcb71c) so this tracks future model adds; strpos fallback for a
3527 - // partial-upgrade window where the catalog method isn't loaded.
3528 - $token_key = $this->mxchat_openai_token_param_for($model);
3529 - $payload = [
3530 - 'model' => $model,
3531 - 'messages' => [
3532 - ['role' => 'system', 'content' => $system_prompt],
3533 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
3534 - ],
3535 - $token_key => 20,
3536 - ];
3537 - if ($this->mxchat_openai_supports_temperature_for($model)) {
3538 - $payload['temperature'] = 0.2;
3539 - }
3540 - $args = [
3541 - 'headers' => [
3542 - 'Authorization' => 'Bearer ' . $api_key,
3543 - 'Content-Type' => 'application/json',
3544 - ],
3545 - 'body' => wp_json_encode($payload),
3546 - 'method' => 'POST',
3547 - 'timeout' => 15,
3548 - ];
3549 -
3550 - $response = wp_remote_post($url, $args);
3551 - if (is_wp_error($response)) {
3552 - return sanitize_text_field($user_query);
3553 - }
3554 -
3555 - $body = json_decode(wp_remote_retrieve_body($response), true);
3556 - return isset($body['choices'][0]['message']['content'])
3557 - ? sanitize_text_field(trim($body['choices'][0]['message']['content']))
3558 - : sanitize_text_field($user_query);
3559 -}
3560 -
3561 -/**
3562 - * Anthropic removed temperature/top_p/top_k starting with Opus 4.7 (the API
3563 - * returns 400 if sent) — add new flagship model ids here. (We don't send
3564 - * top_p/top_k in any Claude body, so the list only needs to gate temperature
3565 - * stripping. We never send a `thinking` param either, which is required for
3566 - * claude-fable-5: it rejects an explicit thinking "disabled" — omit only.)
3567 - */
3568 -private function mxchat_claude_omits_temperature($model) {
3569 - // plan-mxchat-20260714-dcb71c: derive from the core model catalog (single
3570 - // source of truth). Every caller here passes a Claude model, so
3571 - // !supports_temperature() reproduces the old 4-id in_array() result exactly.
3572 - // Frozen list kept as fallback for a partial-upgrade window where the
3573 - // catalog method isn't loaded.
3574 - if (class_exists('MxChat_Model_Catalog') && method_exists('MxChat_Model_Catalog', 'supports_temperature')) {
3575 - return !MxChat_Model_Catalog::supports_temperature($model);
3576 - }
3577 - $no_temp = array('claude-opus-4-7', 'claude-opus-4-8', 'claude-fable-5', 'claude-sonnet-5');
3578 - return in_array($model, $no_temp, true);
3579 -}
3580 -
3581 -/**
3582 - * plan-mxchat-20260715-7124f4: OpenAI completion-token key for this model,
3583 - * sourced from the core catalog (gpt-5* → max_completion_tokens; else
3584 - * max_tokens). strpos fallback for a partial-upgrade window where the catalog
3585 - * method isn't loaded.
3586 - *
3587 - * @param string $model OpenAI(-compatible) model id.
3588 - * @return string 'max_completion_tokens' | 'max_tokens'
3589 - */
3590 -private function mxchat_openai_token_param_for($model) {
3591 - if (class_exists('MxChat_Model_Catalog') && method_exists('MxChat_Model_Catalog', 'openai_token_param')) {
3592 - return MxChat_Model_Catalog::openai_token_param($model);
3593 - }
3594 - return strpos((string) $model, 'gpt-5') === 0 ? 'max_completion_tokens' : 'max_tokens';
3595 -}
3596 -
3597 -/**
3598 - * plan-mxchat-20260715-7124f4: whether a NON-default temperature may be sent to
3599 - * this OpenAI(-compatible) model. gpt-5* accept only the default (1) — sending
3600 - * any other value 400s. Sourced from the core catalog; strpos fallback for a
3601 - * partial-upgrade window.
3602 - *
3603 - * @param string $model OpenAI(-compatible) model id.
3604 - * @return bool
3605 - */
3606 -private function mxchat_openai_supports_temperature_for($model) {
3607 - if (class_exists('MxChat_Model_Catalog') && method_exists('MxChat_Model_Catalog', 'supports_temperature')) {
3608 - return MxChat_Model_Catalog::supports_temperature($model);
3609 - }
3610 - return strpos((string) $model, 'gpt-5') !== 0;
3611 -}
3612 -
3613 -/**
3614 - * plan-mxchat-20260714-dcb71c: per-surface reasoning_effort, sourced from the
3615 - * core model catalog so a model add propagates automatically. The fallback is
3616 - * the frozen pre-dcb71c inline ladder, used only if the catalog method is
3617 - * unavailable (a partial-upgrade window). Byte-identical to the old inline
3618 - * blocks by construction — proven by the dcb71c equivalence harness.
3619 - *
3620 - * @param string $model Chat model id.
3621 - * @param string $context 'chat' | 'websearch'.
3622 - * @return string|null Effort to send, or null to omit the param.
3623 - */
3624 -private function mxchat_reasoning_effort_for($model, $context) {
3625 - if (class_exists('MxChat_Model_Catalog') && method_exists('MxChat_Model_Catalog', 'reasoning_effort_for')) {
3626 - return MxChat_Model_Catalog::reasoning_effort_for($model, $context);
3627 - }
3628 - return $this->mxchat_reasoning_effort_fallback($model, $context);
3629 -}
3630 -
3631 -private function mxchat_reasoning_effort_fallback($model, $context) {
3632 - if (strpos($model, 'gpt-5') !== 0) {
3633 - return null;
3634 - }
3635 - if ($context === 'websearch') {
3636 - $no_reasoning_web = array('gpt-5.2', 'gpt-5.3-chat-latest', 'gpt-5.4-mini', 'gpt-5.4-nano');
3637 - if (in_array($model, $no_reasoning_web, true)) return null;
3638 - if ($model === 'gpt-5.1-2025-11-13') return 'low';
3639 - if ($model === 'gpt-5.5') return 'low';
3640 - if ($model === 'gpt-5.4') return 'low';
3641 - if (in_array($model, array('gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'), true)) return 'low';
3642 - return null;
3643 - }
3644 - // 'chat'
3645 - $no_reasoning_models = array('gpt-5.2', 'gpt-5.1-chat-latest', 'gpt-5.3-chat-latest', 'gpt-5.4-mini', 'gpt-5.4-nano');
3646 - if (in_array($model, $no_reasoning_models, true)) return null;
3647 - if ($model === 'gpt-5.1-2025-11-13') return 'low';
3648 - if ($model === 'gpt-5.5') return 'none';
3649 - if ($model === 'gpt-5.4') return 'none';
3650 - if (in_array($model, array('gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'), true)) return 'low';
3651 - return 'minimal';
3652 -}
3653 -
3654 -/**
3655 - * Interpret query using Claude models
3656 - */
3657 -private function interpret_query_with_claude($user_query, $system_prompt, $api_key, $model) {
3658 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
3659 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
3660 - if ($model === 'claude-opus-4-20250514') { $model = 'claude-opus-4-8'; }
3661 - elseif ($model === 'claude-sonnet-4-20250514') { $model = 'claude-sonnet-4-6'; }
3662 - $url = 'https://api.anthropic.com/v1/messages';
3663 -
3664 - $payload = [
3665 - 'model' => $model,
3666 - 'system' => $system_prompt,
3667 - 'messages' => [
3668 - ['role' => 'user', 'content' => sanitize_text_field($user_query)]
3669 - ],
3670 - 'max_tokens' => 20,
3671 - 'temperature' => 0.2,
3672 - ];
3673 - if ($this->mxchat_claude_omits_temperature($model)) { unset($payload['temperature']); }
3674 -
3675 - $args = [
3676 - 'headers' => [
3677 - 'Content-Type' => 'application/json',
3678 - 'x-api-key' => $api_key,
3679 - 'anthropic-version' => '2023-06-01',
3680 - ],
3681 - 'body' => wp_json_encode($payload),
3682 - 'method' => 'POST',
3683 - 'timeout' => 15,
3684 - ];
3685 -
3686 - $response = wp_remote_post($url, $args);
3687 - if (is_wp_error($response)) {
3688 - return sanitize_text_field($user_query);
3689 - }
3690 -
3691 - $body = json_decode(wp_remote_retrieve_body($response), true);
3692 - // claude-fable-5 prepends a thinking block to content — take the first
3693 - // TEXT block, not content[0].
3694 - foreach ((array) ($body['content'] ?? array()) as $block) {
3695 - if (isset($block['type'], $block['text']) && $block['type'] === 'text' && trim($block['text']) !== '') {
3696 - return sanitize_text_field(trim($block['text']));
3697 - }
3698 - }
3699 -
3700 - return sanitize_text_field($user_query);
3701 -}
3702 -
3703 -/**
3704 - * Interpret query using Gemini models
3705 - */
3706 -private function interpret_query_with_gemini($user_query, $system_prompt, $api_key, $model) {
3707 - if ($model === 'gemini-3-pro-preview') {
3708 - $model = 'gemini-3.1-pro-preview';
3709 - }
3710 - // Use v1beta for preview models, v1 for stable models
3711 - $api_version = (strpos($model, 'preview') !== false || strpos($model, 'exp') !== false) ? 'v1beta' : 'v1';
3712 -
3713 - $url = "https://generativelanguage.googleapis.com/{$api_version}/models/{$model}:generateContent?key=" . urlencode($api_key);
3714 -
3715 - $args = [
3716 - 'headers' => [
3717 - 'Content-Type' => 'application/json',
3718 - ],
3719 - 'body' => wp_json_encode([
3720 - 'contents' => [
3721 - [
3722 - 'role' => 'user',
3723 - 'parts' => [
3724 - ['text' => $system_prompt . "\n\nQuery: " . sanitize_text_field($user_query)]
3725 - ]
3726 - ]
3727 - ],
3728 - 'generationConfig' => [
3729 - 'temperature' => 0.2,
3730 - 'maxOutputTokens' => 20,
3731 - ],
3732 - ]),
3733 - 'method' => 'POST',
3734 - 'timeout' => 15,
3735 - ];
3736 -
3737 - $response = wp_remote_post($url, $args);
3738 - if (is_wp_error($response)) {
3739 - return sanitize_text_field($user_query);
3740 - }
3741 -
3742 - $body = json_decode(wp_remote_retrieve_body($response), true);
3743 - if (!empty($body['candidates'][0]['content']['parts'][0]['text'])) {
3744 - return sanitize_text_field(trim($body['candidates'][0]['content']['parts'][0]['text']));
3745 - }
3746 -
3747 - return sanitize_text_field($user_query);
3748 -}
3749 -
3750 -/**
3751 - * Interpret query using X.AI (Grok) models
3752 - */
3753 -private function interpret_query_with_xai($user_query, $system_prompt, $api_key, $model) {
3754 - $url = 'https://api.xai.com/v1/chat/completions';
3755 -
3756 - $args = [
3757 - 'headers' => [
3758 - 'Content-Type' => 'application/json',
3759 - 'Authorization' => 'Bearer ' . $api_key,
3760 - ],
3761 - 'body' => wp_json_encode([
3762 - 'model' => $model,
3763 - 'messages' => [
3764 - ['role' => 'system', 'content' => $system_prompt],
3765 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
3766 - ],
3767 - 'temperature' => 0.2,
3768 - 'max_tokens' => 20,
3769 - ]),
3770 - 'method' => 'POST',
3771 - 'timeout' => 15,
3772 - ];
3773 -
3774 - $response = wp_remote_post($url, $args);
3775 - if (is_wp_error($response)) {
3776 - return sanitize_text_field($user_query);
3777 - }
3778 -
3779 - $body = json_decode(wp_remote_retrieve_body($response), true);
3780 - if (isset($body['choices'][0]['message']['content'])) {
3781 - return sanitize_text_field(trim($body['choices'][0]['message']['content']));
3782 - }
3783 -
3784 - return sanitize_text_field($user_query);
3785 -}
3786 -
3787 -/**
3788 - * Interpret query using DeepSeek models
3789 - */
3790 -private function interpret_query_with_deepseek($user_query, $system_prompt, $api_key, $model) {
3791 - $url = 'https://api.deepseek.com/v1/chat/completions';
3792 -
3793 - $args = [
3794 - 'headers' => [
3795 - 'Content-Type' => 'application/json',
3796 - 'Authorization' => 'Bearer ' . $api_key,
3797 - ],
3798 - 'body' => wp_json_encode([
3799 - 'model' => $model,
3800 - 'messages' => [
3801 - ['role' => 'system', 'content' => $system_prompt],
3802 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
3803 - ],
3804 - 'temperature' => 0.2,
3805 - 'max_tokens' => 20,
3806 - ]),
3807 - 'method' => 'POST',
3808 - 'timeout' => 15,
3809 - ];
3810 -
3811 - $response = wp_remote_post($url, $args);
3812 - if (is_wp_error($response)) {
3813 - return sanitize_text_field($user_query);
3814 - }
3815 -
3816 - $body = json_decode(wp_remote_retrieve_body($response), true);
3817 - if (isset($body['choices'][0]['message']['content'])) {
3818 - return sanitize_text_field(trim($body['choices'][0]['message']['content']));
3819 - }
3820 -
3821 - return sanitize_text_field($user_query);
3822 -}
3823 -
3824 -//very good
3825 -private function add_email_to_loops($email) {
3826 - // Sanitize the email
3827 - $email = sanitize_email($email);
3828 -
3829 - // Retrieve and sanitize options
3830 - $api_key = isset($this->options['loops_api_key']) ? sanitize_text_field($this->options['loops_api_key']) : '';
3831 - $mailing_list_id = isset($this->options['loops_mailing_list']) ? sanitize_text_field($this->options['loops_mailing_list']) : '';
3832 -
3833 - // Check for missing API key or mailing list ID
3834 - if (empty($api_key) || empty($mailing_list_id)) {
3835 - //error_log(esc_html__('Loops API key or mailing list ID is missing.', 'mxchat'));
3836 - return;
3837 - }
3838 -
3839 - $data = array(
3840 - 'email' => $email,
3841 - 'subscribed' => true,
3842 - 'source' => __('MxChat AI Chatbot', 'mxchat'),
3843 - 'mailingLists' => array($mailing_list_id => true),
3844 - );
3845 -
3846 - $url = 'https://app.loops.so/api/v1/contacts/create';
3847 - $args = array(
3848 - 'body' => wp_json_encode($data),
3849 - 'headers' => array(
3850 - 'Authorization' => 'Bearer ' . $api_key,
3851 - 'Content-Type' => 'application/json',
3852 - ),
3853 - 'method' => 'POST',
3854 - 'timeout' => 45,
3855 - );
3856 -
3857 - $response = wp_remote_post($url, $args);
3858 -
3859 - // Handle errors in the API request
3860 - if (is_wp_error($response)) {
3861 - //error_log(esc_html__('Error adding email to Loops: ', 'mxchat') . $response->get_error_message());
3862 - return;
3863 - }
3864 -
3865 - // Check for non-200 HTTP responses
3866 - $response_code = wp_remote_retrieve_response_code($response);
3867 - if ($response_code != 200) {
3868 - $response_body = wp_remote_retrieve_body($response);
3869 - //error_log(esc_html__('Loops API responded with code ', 'mxchat') . $response_code . ': ' . $response_body);
3870 - }
3871 -}
3872 -
3873 -public function mxchat_handle_pdf_discussion($message, $user_id, $session_id) {
3874 - // Get the maximum number of pages allowed from admin settings
3875 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
3876 -
3877 - // Retrieve options for dynamic texts
3878 - $trigger_text = $this->options['pdf_intent_trigger_text'] ?? __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
3879 - $success_text = $this->options['pdf_intent_success_text'] ?? __("I've processed the PDF. What questions do you have about it?", 'mxchat');
3880 - $error_text = $this->options['pdf_intent_error_text'] ?? __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
3881 -
3882 - // Check for explicit request for new PDF
3883 - $new_pdf_requested = stripos($message, 'new') !== false ||
3884 - stripos($message, 'another') !== false ||
3885 - stripos($message, 'different') !== false;
3886 -
3887 - // If user mentions adding/reading a PDF, set waiting flag
3888 - if (stripos($message, 'pdf') !== false ||
3889 - stripos($message, 'document') !== false ||
3890 - stripos($message, 'read') !== false) {
3891 - set_transient('mxchat_waiting_for_pdf_url_' . $session_id, true, HOUR_IN_SECONDS);
3892 - $this->fallbackResponse['text'] = $trigger_text;
3893 - return;
3894 - }
3895 -
3896 - // If we're waiting for a URL or user requested new PDF
3897 - if ($new_pdf_requested || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
3898 - if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
3899 - // Process URL... (rest of your existing URL processing code)
3900 - } else {
3901 - $this->fallbackResponse['text'] = $trigger_text;
3902 - }
3903 - return;
3904 - }
3905 -
3906 - // Default to proceeding with conversation if no specific PDF action is needed
3907 - $this->fallbackResponse['text'] = '';
3908 -}
3909 -
3910 -
3911 -/**
3912 - * Enhanced fetch_and_split_pdf_pages with SSRF protection
3913 - */
3914 -private function fetch_and_split_pdf_pages($pdf_source, $max_pages) {
3915 - // CLEAR DEBUG LOGGING
3916 - //error_log("=== MXCHAT PDF PROCESSING START ===");
3917 - //error_log("PDF Source: " . $pdf_source);
3918 - //error_log("Max Pages: " . $max_pages);
3919 - //error_log("Session ID: " . ($this->session_id ?? 'not set'));
3920 -
3921 - // Check if Advanced Claude Toolbar is available and enabled
3922 - $claude_available = function_exists('mxchatACT_is_advanced_claude_enabled');
3923 - $claude_enabled = $claude_available ? mxchatACT_is_advanced_claude_enabled() : false;
3924 -
3925 - //error_log("Claude Function Available: " . ($claude_available ? 'YES' : 'NO'));
3926 - //error_log("Claude Enabled: " . ($claude_enabled ? 'YES' : 'NO'));
3927 -
3928 - if ($claude_available && $claude_enabled) {
3929 - //error_log("🚀 ATTEMPTING CLAUDE PROCESSING...");
3930 -
3931 - // Attempt Claude processing first
3932 - $claude_result = apply_filters('mxchat_process_pdf_advanced', false, $pdf_source, $max_pages, $this->session_id);
3933 -
3934 - if ($claude_result !== false && is_array($claude_result) && !empty($claude_result)) {
3935 - //error_log("✅ CLAUDE PROCESSING SUCCESSFUL!");
3936 - //error_log("Claude returned " . count($claude_result) . " processed pages");
3937 -
3938 - // Log first page details for verification
3939 - if (isset($claude_result[0])) {
3940 - $first_page = $claude_result[0];
3941 - //error_log("First page enhanced: " . (isset($first_page['enhanced']) && $first_page['enhanced'] ? 'YES' : 'NO'));
3942 - //error_log("Processing method: " . ($first_page['processing_method'] ?? 'not set'));
3943 - //error_log("First page text preview: " . substr($first_page['text'] ?? '', 0, 100) . "...");
3944 - }
3945 -
3946 - //error_log("=== MXCHAT PDF PROCESSING END (CLAUDE) ===");
3947 - return $claude_result;
3948 - } else {
3949 - //error_log("❌ CLAUDE PROCESSING FAILED or returned invalid result");
3950 - //error_log("Claude result type: " . gettype($claude_result));
3951 - if (is_array($claude_result)) {
3952 - //error_log("Claude result count: " . count($claude_result));
3953 - }
3954 - }
3955 - }
3956 -
3957 - // Fallback to basic processing
3958 - //error_log("🔄 FALLING BACK TO BASIC PDF PROCESSING...");
3959 -
3960 - $upload_dir = wp_upload_dir();
3961 - $temp_file = null;
3962 -
3963 - try {
3964 - // Your existing basic processing code here...
3965 - // (I'll include the key parts with debug logging)
3966 -
3967 - if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
3968 - //error_log("Downloading PDF from URL...");
3969 -
3970 - // SECURITY FIX: Validate URL before processing
3971 - if (!$this->mxchat_is_safe_pdf_url($pdf_source)) {
3972 - //error_log("❌ SECURITY: Blocked unsafe PDF URL");
3973 - return false;
3974 - }
3975 -
3976 - $temp_file = wp_tempnam($pdf_source);
3977 -
3978 - // SECURITY FIX: Changed from wp_remote_get to wp_safe_remote_get
3979 - // Route through the shared MXChat crawler identity (plan bae78f/b6d93c) so
3980 - // every remote-content fetch presents one honest, versioned, filterable,
3981 - // allowlistable User-Agent. function_exists guard keeps the front-end/nopriv
3982 - // path safe if the helper (in the always-loaded main file) is ever unavailable.
3983 - $response = wp_safe_remote_get($pdf_source, [
3984 - 'timeout' => 60,
3985 - 'headers' => ['User-Agent' => function_exists('mxchat_ingest_user_agent') ? mxchat_ingest_user_agent() : 'MxChat PDF Processor']
3986 - ]);
3987 -
3988 - if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
3989 - $error_message = is_wp_error($response) ? $response->get_error_message() : 'HTTP ' . wp_remote_retrieve_response_code($response);
3990 - //error_log("❌ BASIC PROCESSING: Failed to download PDF: " . $error_message);
3991 - return false;
3992 - }
3993 -
3994 - global $wp_filesystem;
3995 - if (empty($wp_filesystem)) {
3996 - require_once ABSPATH . 'wp-admin/includes/file.php';
3997 - WP_Filesystem();
3998 - }
3999 - $wp_filesystem->put_contents($temp_file, wp_remote_retrieve_body($response), FS_CHMOD_FILE);
4000 - //error_log("✅ PDF downloaded successfully");
4001 - } else {
4002 - $temp_file = $pdf_source;
4003 - //error_log("Using local PDF file: " . $temp_file);
4004 - }
4005 -
4006 - // Parse PDF
4007 - //error_log("Parsing PDF with basic parser...");
4008 - mxchat_load_pdf_parser();
4009 - $parser = new \Smalot\PdfParser\Parser();
4010 - $pdf = $parser->parseFile($temp_file);
4011 - $pages = $pdf->getPages();
4012 -
4013 - //error_log("PDF contains " . count($pages) . " pages");
4014 -
4015 - if (count($pages) > $max_pages) {
4016 - //error_log("❌ BASIC PROCESSING: Too many pages (" . count($pages) . " > " . $max_pages . ")");
4017 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file) {
4018 - unlink($temp_file);
4019 - }
4020 - return 'too_many_pages';
4021 - }
4022 -
4023 - $embeddings = [];
4024 - $processed_pages = 0;
4025 -
4026 - foreach ($pages as $page_number => $page) {
4027 - $text = $page->getText();
4028 -
4029 - if (empty(trim($text))) {
4030 - //error_log("Skipping empty page: " . ($page_number + 1));
4031 - continue;
4032 - }
4033 -
4034 - $text = $this->mxchat_clean_text($text);
4035 -
4036 - $embedding = $this->mxchat_generate_embedding(
4037 - __("Page ", 'mxchat') . ($page_number + 1) . ": " . $text,
4038 - $this->options['api_key']
4039 - );
4040 -
4041 - if ($embedding) {
4042 - $embeddings[] = [
4043 - 'page_number' => $page_number + 1,
4044 - 'embedding' => $embedding,
4045 - 'text' => $text,
4046 - 'enhanced' => false, // CLEARLY MARK AS BASIC
4047 - 'processing_method' => 'basic_pdf_parser'
4048 - ];
4049 - $processed_pages++;
4050 - }
4051 - }
4052 -
4053 - //error_log("✅ BASIC PROCESSING COMPLETE: " . $processed_pages . " pages processed");
4054 -
4055 - // Cleanup
4056 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
4057 - unlink($temp_file);
4058 - }
4059 -
4060 - //error_log("=== MXCHAT PDF PROCESSING END (BASIC) ===");
4061 - return $embeddings;
4062 -
4063 - } catch (\Exception $e) {
4064 - //error_log("❌ BASIC PROCESSING ERROR: " . $e->getMessage());
4065 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
4066 - unlink($temp_file);
4067 - }
4068 - //error_log("=== MXCHAT PDF PROCESSING END (ERROR) ===");
4069 - return false;
4070 - }
4071 -}
4072 -
4073 -
4074 -/**
4075 - * Validate PDF URL for security
4076 - * Prevents SSRF attacks by blocking dangerous URLs
4077 - */
4078 -
4079 -private function mxchat_is_safe_pdf_url($url) {
4080 - // Use WordPress core function for comprehensive validation
4081 - // This blocks localhost, private IPs, and reserved IP ranges
4082 - $validated_url = wp_http_validate_url($url);
4083 -
4084 - if ($validated_url === false) {
4085 - return false;
4086 - }
4087 -
4088 - // Additional check: only allow HTTP/HTTPS schemes
4089 - $parsed = parse_url($url);
4090 - if (!isset($parsed['scheme']) || !in_array($parsed['scheme'], ['http', 'https'], true)) {
4091 - return false;
4092 - }
4093 -
4094 - return true;
4095 -}
4096 -
4097 -
4098 -private function mxchat_clean_text($text) {
4099 - // Remove excessive whitespace
4100 - $text = preg_replace('/\s+/', ' ', $text);
4101 -
4102 - // Remove control characters except newlines and tabs
4103 - $text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text);
4104 -
4105 - // Normalize line endings
4106 - $text = str_replace(["\r\n", "\r"], "\n", $text);
4107 -
4108 - // Trim whitespace
4109 - $text = trim($text);
4110 -
4111 - return $text;
4112 -}
4113 -
4114 -private function find_relevant_pdf_pages($query_embedding, $embeddings) {
4115 - //error_log(esc_html__("find_relevant_pdf_pages called.", 'mxchat'));
4116 -
4117 - $most_relevant = null;
4118 - $highest_similarity = -INF;
4119 -
4120 - foreach ($embeddings as $page_data) {
4121 - $similarity = $this->mxchat_calculate_cosine_similarity($query_embedding, $page_data['embedding']);
4122 -
4123 - if ($similarity > $highest_similarity) {
4124 - $highest_similarity = $similarity;
4125 - $most_relevant = $page_data['page_number'];
4126 - }
4127 - }
4128 -
4129 - if (!is_null($most_relevant)) {
4130 - $page_numbers = range(max(1, $most_relevant - 1), min(count($embeddings), $most_relevant + 1));
4131 - return array_filter($embeddings, function ($page) use ($page_numbers) {
4132 - return in_array($page['page_number'], $page_numbers);
4133 - });
4134 - }
4135 -
4136 - return [];
4137 -}
4138 -
4139 -
4140 -public function handle_pdf_upload() {
4141 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce(wp_unslash((string) $_POST['nonce']))) {
4142 - wp_send_json_error(array('message' => esc_html__('Invalid nonce.', 'mxchat')), 403);
4143 - }
4144 -
4145 - if (!isset($_FILES['pdf_file']) || !isset($_POST['session_id'])) {
4146 - wp_send_json_error(esc_html__('Missing required parameters.', 'mxchat'));
4147 - return;
4148 - }
4149 -
4150 - // SECURITY FIX: Check if PDF uploads are enabled in settings
4151 - $options = get_option('mxchat_options', array());
4152 - $show_pdf_button = isset($options['show_pdf_upload_button']) ? $options['show_pdf_upload_button'] : 'on';
4153 -
4154 - if ($show_pdf_button !== 'on') {
4155 - wp_send_json_error(esc_html__('PDF uploads are currently disabled.', 'mxchat'));
4156 - return;
4157 - }
4158 -
4159 - $file = $_FILES['pdf_file'];
4160 - $session_id = sanitize_text_field($_POST['session_id']);
4161 - $original_filename = sanitize_text_field($file['name']);
4162 -
4163 - // Update session owner if it changed (e.g. IP changed due to network switch)
4164 - $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
4165 - $session_owner = get_option("mxchat_session_owner_{$session_id}");
4166 -
4167 - if (!$session_owner || $session_owner !== $current_user_identifier) {
4168 - update_option("mxchat_session_owner_{$session_id}", $current_user_identifier, 'no');
4169 - }
4170 -
4171 - $file_type = wp_check_filetype($file['name'], ['pdf' => 'application/pdf']);
4172 - if ($file_type['type'] !== 'application/pdf') {
4173 - wp_send_json_error(esc_html__('Invalid file type. Only PDF files are allowed.', 'mxchat'));
4174 - return;
4175 - }
4176 -
4177 - $upload_dir = wp_upload_dir();
4178 -
4179 - // SECURITY FIX: Generate random filename without exposing session_id
4180 - $random_string = wp_generate_password(20, false, false); // 20 char alphanumeric string
4181 - $pdf_filename = 'mxchat_' . $random_string . '_' . time() . '.pdf';
4182 - $pdf_path = $upload_dir['path'] . '/' . $pdf_filename;
4183 -
4184 - if (!move_uploaded_file($file['tmp_name'], $pdf_path)) {
4185 - wp_send_json_error(esc_html__('Failed to upload file.', 'mxchat'));
4186 - return;
4187 - }
4188 -
4189 - $this->clear_pdf_transients($session_id);
4190 -
4191 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
4192 - $embeddings = $this->fetch_and_split_pdf_pages($pdf_path, $max_pages);
4193 -
4194 - if ($embeddings === 'too_many_pages') {
4195 - unlink($pdf_path);
4196 - $error_message = sprintf(
4197 - $this->options['pdf_intent_error_text'] ??
4198 - esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
4199 - $max_pages
4200 - );
4201 - wp_send_json_error($error_message);
4202 - return;
4203 - }
4204 -
4205 - if ($embeddings === false || empty($embeddings)) {
4206 - unlink($pdf_path);
4207 - $error_message = $this->options['pdf_intent_error_text'] ??
4208 - esc_html__('The uploaded PDF appears to be empty or contains unsupported content.', 'mxchat');
4209 - wp_send_json_error($error_message);
4210 - return;
4211 - }
4212 -
4213 - if (!empty($embeddings)) {
4214 - // Store the mapping between session and the random filename
4215 - set_transient('mxchat_pdf_url_' . $session_id, $pdf_path, HOUR_IN_SECONDS);
4216 - set_transient('mxchat_pdf_filename_' . $session_id, $original_filename, HOUR_IN_SECONDS);
4217 - set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
4218 - set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
4219 -
4220 - $success_message = $this->options['pdf_intent_success_text'] ??
4221 - esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat');
4222 -
4223 - wp_send_json_success([
4224 - 'message' => $success_message,
4225 - 'filename' => $original_filename
4226 - ]);
4227 - return;
4228 - }
4229 -
4230 - unlink($pdf_path);
4231 - $error_message = $this->options['pdf_intent_error_text'] ??
4232 - esc_html__('Sorry, I couldn\'t process the PDF. Please ensure it\'s a valid file.', 'mxchat');
4233 - wp_send_json_error($error_message);
4234 - return;
4235 -}
4236 -public function handle_pdf_remove() {
4237 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce(wp_unslash((string) $_POST['nonce']))) {
4238 - wp_send_json_error(array('message' => esc_html__('Invalid nonce.', 'mxchat')), 403);
4239 - }
4240 -
4241 - if (empty($_POST['session_id'])) {
4242 - wp_send_json_error(esc_html__('Session ID missing.', 'mxchat'));
4243 - wp_die();
4244 - }
4245 -
4246 - $session_id = sanitize_text_field($_POST['session_id']);
4247 - $pdf_path = get_transient('mxchat_pdf_url_' . $session_id);
4248 -
4249 - if ($pdf_path && file_exists($pdf_path)) {
4250 - unlink($pdf_path);
4251 - }
4252 -
4253 - $this->clear_pdf_transients($session_id);
4254 -
4255 - wp_send_json_success([
4256 - 'message' => esc_html__('PDF removed successfully.', 'mxchat')
4257 - ]);
4258 - wp_die();
4259 -}
4260 -
4261 -
4262 -function mxchat_fetch_new_messages() {
4263 - $session_id = sanitize_text_field($_POST['session_id']);
4264 - $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
4265 - $persistence_enabled = $_POST['persistence_enabled'] === 'true';
4266 - $initial_timestamp = isset($_POST['initial_timestamp']) ? intval($_POST['initial_timestamp']) : 0;
4267 -
4268 - if (empty($session_id)) {
4269 - //error_log(esc_html__('Fetch new messages error: Session ID missing.', 'mxchat'));
4270 - wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
4271 - wp_die();
4272 - }
4273 -
4274 - $history = get_option("mxchat_history_{$session_id}", []);
4275 -
4276 - //error_log("MxChat WhatsApp DEBUG: Fetch new messages for session {$session_id}");
4277 - //error_log("MxChat WhatsApp DEBUG: last_seen_id = " . var_export($last_seen_id, true));
4278 - //error_log("MxChat WhatsApp DEBUG: History count = " . count($history));
4279 - //error_log("MxChat WhatsApp DEBUG: Full history = " . print_r($history, true));
4280 -
4281 - $new_messages = array_filter($history, function ($message) use ($last_seen_id, $persistence_enabled, $initial_timestamp) {
4282 - //error_log("MxChat WhatsApp DEBUG: Checking message - ID: " . ($message['id'] ?? 'NO_ID') . ", Role: " . ($message['role'] ?? 'NO_ROLE'));
4283 -
4284 - // If persistence is enabled, show all new messages
4285 - if ($persistence_enabled) {
4286 - $has_id = !empty($message['id']);
4287 - $is_agent = $message['role'] === 'agent';
4288 -
4289 - // If last_seen_id is empty, 'NaN', or invalid, show all agent messages
4290 - if (empty($last_seen_id) || $last_seen_id === 'NaN' || $last_seen_id === 'undefined') {
4291 - $is_newer = true;
4292 - } else {
4293 - $is_newer = strcmp($message['id'] ?? '', $last_seen_id) > 0;
4294 - }
4295 -
4296 - //error_log("MxChat WhatsApp DEBUG: has_id={$has_id}, is_newer={$is_newer}, is_agent={$is_agent}");
4297 -
4298 - return $has_id && $is_newer && $is_agent;
4299 - }
4300 -
4301 - // If persistence is disabled, only show messages after initial timestamp
4302 - return !empty($message['id']) &&
4303 - $message['role'] === 'agent' &&
4304 - $message['timestamp'] > $initial_timestamp;
4305 - });
4306 -
4307 - //error_log("MxChat WhatsApp DEBUG: Filtered messages count = " . count($new_messages));
4308 -
4309 - // Include current chat mode so frontend can detect agent→AI transitions
4310 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
4311 -
4312 - wp_send_json_success([
4313 - 'new_messages' => array_values($new_messages),
4314 - 'chat_mode' => $chat_mode
4315 - ]);
4316 - wp_die();
4317 -}
4318 -public function mxchat_live_agent_handover($message, $user_id, $session_id) {
4319 - // First check if live agents are available.
4320 - // Outside the SLACK availability schedule this behaves exactly like the
4321 - // manual toggle being off — same away message, same stay-in-AI-mode path
4322 - // (plans 8ccaa2 + 99d7a4: each channel owns its own schedule). The schedule
4323 - // normally stops the tool being offered at all; this is the backstop for
4324 - // any path that calls the handover directly.
4325 - $live_agent_available = $this->options['live_agent_status'] ?? 'off';
4326 - $within_hours = !class_exists('MxChat_Live_Agent_Schedule')
4327 - || MxChat_Live_Agent_Schedule::is_within_hours('slack');
4328 - if ($live_agent_available !== 'on' || !$within_hours) {
4329 - $away_message = $this->options['live_agent_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
4330 - $this->fallbackResponse = [
4331 - 'text' => $away_message,
4332 - 'html' => '',
4333 - 'images' => [],
4334 - 'chat_mode' => 'ai'
4335 - ];
4336 - wp_send_json([
4337 - 'text' => $away_message,
4338 - 'html' => '',
4339 - 'chat_mode' => 'ai',
4340 - 'session_id' => $session_id
4341 - ]);
4342 - wp_die();
4343 - }
4344 -
4345 - $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
4346 -
4347 - if (empty($slack_bot_token)) {
4348 - return false;
4349 - }
4350 -
4351 - // Check if channel already exists for this session
4352 - $channel_id = get_option("mxchat_channel_{$session_id}", '');
4353 -
4354 - if (empty($channel_id)) {
4355 - // Create new channel with session ID as name
4356 - $channel_name = $this->generate_channel_name($session_id);
4357 -
4358 - //error_log("Attempting to create channel: $channel_name");
4359 -
4360 - $response = wp_remote_post('https://slack.com/api/conversations.create', [
4361 - 'headers' => [
4362 - 'Content-Type' => 'application/json',
4363 - 'Authorization' => 'Bearer ' . $slack_bot_token
4364 - ],
4365 - 'body' => json_encode([
4366 - 'name' => $channel_name,
4367 - 'is_private' => false // Public channel - anyone in workspace can join
4368 - ])
4369 - ]);
4370 -
4371 - if (!is_wp_error($response)) {
4372 - $response_body = wp_remote_retrieve_body($response);
4373 - $response_data = json_decode($response_body, true);
4374 -
4375 - //error_log("Channel creation response: " . $response_body);
4376 -
4377 - if (isset($response_data['ok']) && $response_data['ok']) {
4378 - $channel_id = $response_data['channel']['id'];
4379 - $actual_channel_name = $response_data['channel']['name'] ?? 'unknown';
4380 - //error_log("Channel created successfully: ID=$channel_id, Name=$actual_channel_name");
4381 - update_option("mxchat_channel_{$session_id}", $channel_id);
4382 -
4383 - // Auto-invite agents to the channel
4384 - $agent_user_ids = $this->options['live_agent_user_ids'] ?? '';
4385 -
4386 - if (!empty($agent_user_ids)) {
4387 - // Parse user IDs (one per line)
4388 - $user_ids = array_filter(array_map('trim', explode("\n", $agent_user_ids)));
4389 -
4390 - foreach ($user_ids as $user_id_to_invite) {
4391 - //error_log("Inviting user to channel: $user_id_to_invite");
4392 -
4393 - $invite_response = wp_remote_post('https://slack.com/api/conversations.invite', [
4394 - 'headers' => [
4395 - 'Content-Type' => 'application/json',
4396 - 'Authorization' => 'Bearer ' . $slack_bot_token
4397 - ],
4398 - 'body' => json_encode([
4399 - 'channel' => $channel_id,
4400 - 'users' => $user_id_to_invite
4401 - ])
4402 - ]);
4403 -
4404 - if (!is_wp_error($invite_response)) {
4405 - $invite_body = wp_remote_retrieve_body($invite_response);
4406 - $invite_data = json_decode($invite_body, true);
4407 - //error_log("Invite response for $user_id_to_invite: " . $invite_body);
4408 -
4409 - if (isset($invite_data['ok']) && $invite_data['ok']) {
4410 - //error_log("Successfully invited user $user_id_to_invite to channel");
4411 - } else {
4412 - //error_log("Failed to invite user $user_id_to_invite: " . ($invite_data['error'] ?? 'Unknown error'));
4413 - }
4414 - } else {
4415 - //error_log("WP Error inviting user $user_id_to_invite: " . $invite_response->get_error_message());
4416 - }
4417 - }
4418 - } else {
4419 - //error_log("No agent user IDs configured for auto-invite");
4420 - }
4421 - } else {
4422 - //error_log("Channel creation failed: " . ($response_data['error'] ?? 'Unknown error'));
4423 - }
4424 - } else {
4425 - //error_log("WP Error creating channel: " . $response->get_error_message());
4426 - }
4427 -
4428 - if (empty($channel_id)) {
4429 - return false; // Failed to create channel
4430 - }
4431 - }
4432 -
4433 - // Get recent chat history
4434 - $history = get_option("mxchat_history_{$session_id}", []);
4435 - $recent_history = array_slice($history, -5);
4436 -
4437 - // Format conversation context
4438 - $conversation_context = "";
4439 - if (!empty($recent_history)) {
4440 - $conversation_context = "*Recent Conversation:*\n";
4441 - foreach ($recent_history as $hist_message) {
4442 - $role_display = $hist_message['role'] === 'user' ? 'User' : 'AI';
4443 - $conversation_context .= ">{$role_display}: {$hist_message['content']}\n";
4444 - }
4445 - $conversation_context .= "\n";
4446 - }
4447 -
4448 - update_option("mxchat_mode_{$session_id}", 'agent');
4449 -
4450 - // Send message to channel
4451 - $channel_message = "🔔 *New Live Agent Request*\n\n";
4452 - $channel_message .= "*Session ID:* `{$session_id}`\n";
4453 - $channel_message .= "*User ID:* `{$user_id}`\n";
4454 -
4455 - // Surface the captured visitor identity so the agent knows who they're talking to —
4456 - // guest User IDs are 0, but the pre-chat gate / login / transcript often has name+email (plan-e2195b).
4457 - $visitor = $this->mxchat_get_visitor_identity($session_id);
4458 - if (!empty($visitor['name']) && !empty($visitor['email'])) {
4459 - $channel_message .= "*Visitor:* {$visitor['name']} <{$visitor['email']}>\n";
4460 - } elseif (!empty($visitor['email'])) {
4461 - $channel_message .= "*Visitor:* <{$visitor['email']}>\n";
4462 - } elseif (!empty($visitor['name'])) {
4463 - $channel_message .= "*Visitor:* {$visitor['name']}\n";
4464 - }
4465 - $channel_message .= "\n";
4466 -
4467 - if (!empty($conversation_context)) {
4468 - $channel_message .= $conversation_context;
4469 - }
4470 -
4471 - $channel_message .= "*Current Message:*\n{$message}\n\n";
4472 - $channel_message .= "_Reply directly in this channel - all messages will go to the user_";
4473 -
4474 - wp_remote_post('https://slack.com/api/chat.postMessage', [
4475 - 'headers' => [
4476 - 'Content-Type' => 'application/json',
4477 - 'Authorization' => 'Bearer ' . $slack_bot_token
4478 - ],
4479 - 'body' => json_encode([
4480 - 'channel' => $channel_id,
4481 - 'text' => $channel_message,
4482 - 'mrkdwn' => true
4483 - ])
4484 - ]);
4485 -
4486 - $success_message = $this->options['live_agent_notification_message'] ?? 'Live agent has been notified.';
4487 - $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
4488 -
4489 - $this->fallbackResponse = [
4490 - 'text' => $success_message,
4491 - 'html' => '',
4492 - 'images' => [],
4493 - 'chat_mode' => 'agent'
4494 - ];
4495 -
4496 - wp_send_json([
4497 - 'success' => true,
4498 - 'text' => $success_message,
4499 - 'html' => '',
4500 - 'chat_mode' => 'agent',
4501 - 'session_id' => $session_id,
4502 - 'fallbackResponse' => $this->fallbackResponse
4503 - ]);
4504 - wp_die();
4505 -}
4506 -
4507 -private function generate_channel_name($session_id) {
4508 - $email = null;
4509 - $name = null;
4510 -
4511 - // 1. First priority: Check if user is logged in and get their info
4512 - if (is_user_logged_in()) {
4513 - $current_user = wp_get_current_user();
4514 - if (!empty($current_user->user_email)) {
4515 - $email = $current_user->user_email;
4516 - //error_log("[DEBUG] Using logged-in user email for channel: {$email}");
4517 - }
4518 - if (!empty($current_user->display_name)) {
4519 - $name = $current_user->display_name;
4520 - //error_log("[DEBUG] Using logged-in user name for channel: {$name}");
4521 - }
4522 - }
4523 -
4524 - // 2. Second priority: Check for saved email/name from "require email to chat" option
4525 - if (empty($email)) {
4526 - $email_option_key = "mxchat_email_{$session_id}";
4527 - $saved_email = get_option($email_option_key);
4528 - if (!empty($saved_email)) {
4529 - $email = $saved_email;
4530 - //error_log("[DEBUG] Using saved email from session for channel: {$email}");
4531 - }
4532 - }
4533 -
4534 - if (empty($name)) {
4535 - $name_option_key = "mxchat_name_{$session_id}";
4536 - $saved_name = get_option($name_option_key);
4537 - if (!empty($saved_name)) {
4538 - $name = $saved_name;
4539 - //error_log("[DEBUG] Using saved name from session for channel: {$name}");
4540 - }
4541 - }
4542 -
4543 - // 3. Third priority: Check existing chat transcript for email/name
4544 - if (empty($email) || empty($name)) {
4545 - global $wpdb;
4546 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
4547 - $existing_data = $wpdb->get_row($wpdb->prepare(
4548 - "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",
4549 - $session_id
4550 - ));
4551 -
4552 - if ($existing_data) {
4553 - if (empty($email) && !empty($existing_data->user_email)) {
4554 - $email = $existing_data->user_email;
4555 - //error_log("[DEBUG] Using email from chat transcript for channel: {$email}");
4556 - }
4557 - if (empty($name) && !empty($existing_data->user_name)) {
4558 - $name = $existing_data->user_name;
4559 - //error_log("[DEBUG] Using name from chat transcript for channel: {$name}");
4560 - }
4561 - }
4562 - }
4563 -
4564 - // 4. Generate channel name based on priority: Name > Email > Session ID
4565 - $channel_name = '';
4566 -
4567 - if (!empty($name)) {
4568 - // Convert name to valid Slack channel name
4569 - $base_name = strtolower(trim($name));
4570 - // Replace spaces and invalid characters
4571 - $base_name = preg_replace('/[^a-z0-9\s]/', '', $base_name);
4572 - $base_name = preg_replace('/\s+/', '-', $base_name);
4573 - $base_name = trim($base_name, '-');
4574 -
4575 - // Get last 4 characters of session ID for uniqueness
4576 - $session_suffix = substr($session_id, -4);
4577 - $channel_name = 'chat-' . $base_name . '-' . strtolower($session_suffix);
4578 -
4579 - // Slack channel names have a 21 character limit
4580 - if (strlen($channel_name) > 21) {
4581 - // Calculate available space for name (21 - 'chat-' - '-' - session_suffix)
4582 - $available_space = 21 - 5 - 1 - strlen($session_suffix); // 'chat-' = 5, '-' = 1
4583 - $truncated_name = substr($base_name, 0, $available_space);
4584 - $truncated_name = rtrim($truncated_name, '-'); // Remove trailing hyphen
4585 - $channel_name = 'chat-' . $truncated_name . '-' . strtolower($session_suffix);
4586 - }
4587 -
4588 - //error_log("[DEBUG] Using name for channel: {$channel_name} (from name: {$name})");
4589 -
4590 - } elseif (!empty($email)) {
4591 - // Convert email to valid Slack channel name (your existing logic)
4592 - $channel_name = 'chat-' . strtolower(str_replace(['@', '.', '+', '_'], ['-at-', '-', '-plus-', '-'], $email));
4593 - // Remove any remaining invalid characters
4594 - $channel_name = preg_replace('/[^a-z0-9\-]/', '', $channel_name);
4595 - // Ensure it doesn't end with a hyphen
4596 - $channel_name = rtrim($channel_name, '-');
4597 - // Slack channel names have a 21 character limit, so truncate if needed
4598 - if (strlen($channel_name) > 21) {
4599 - $channel_name = substr($channel_name, 0, 21);
4600 - $channel_name = rtrim($channel_name, '-'); // Remove trailing hyphen if truncation created one
4601 - }
4602 -
4603 - //error_log("[DEBUG] Using email for channel: {$channel_name} (from email: {$email})");
4604 -
4605 - } else {
4606 - // Fallback to session ID if no name or email found
4607 - $channel_name = 'chat-' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $session_id));
4608 - //error_log("[DEBUG] No name or email found, using session ID for channel: {$channel_name}");
4609 - }
4610 -
4611 - // Final validation - ensure channel name meets Slack requirements
4612 - if (strlen($channel_name) > 21) {
4613 - $channel_name = substr($channel_name, 0, 21);
4614 - $channel_name = rtrim($channel_name, '-');
4615 - }
4616 -
4617 - //error_log("[DEBUG] Generated channel name: {$channel_name}");
4618 - return $channel_name;
4619 -}
4620 -
4621 -/**
4622 - * Telegram Live Agent Handover
4623 - * Creates a forum topic in the Telegram group and notifies agents
4624 - */
4625 -public function mxchat_telegram_live_agent_handover($message, $user_id, $session_id) {
4626 - // Check if Telegram agents are available. Telegram has its OWN availability
4627 - // schedule, independent of Slack's (plan 99d7a4 — each Integrations tab
4628 - // owns its scheduler). Backstop only; the tool is normally withheld
4629 - // off-hours.
4630 - $telegram_available = $this->options['telegram_status'] ?? 'off';
4631 - $within_hours = !class_exists('MxChat_Live_Agent_Schedule')
4632 - || MxChat_Live_Agent_Schedule::is_within_hours('telegram');
4633 - if ($telegram_available !== 'on' || !$within_hours) {
4634 - $away_message = $this->options['telegram_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
4635 - $this->fallbackResponse = [
4636 - 'text' => $away_message,
4637 - 'html' => '',
4638 - 'images' => [],
4639 - 'chat_mode' => 'ai'
4640 - ];
4641 - wp_send_json([
4642 - 'text' => $away_message,
4643 - 'html' => '',
4644 - 'chat_mode' => 'ai',
4645 - 'session_id' => $session_id
4646 - ]);
4647 - wp_die();
4648 - }
4649 -
4650 - $telegram_bot_token = $this->options['telegram_bot_token'] ?? '';
4651 - $telegram_group_id = $this->options['telegram_group_id'] ?? '';
4652 -
4653 - if (empty($telegram_bot_token) || empty($telegram_group_id)) {
4654 - return false;
4655 - }
4656 -
4657 - // Check if topic already exists for this session
4658 - $topic_id = get_option("mxchat_telegram_topic_{$session_id}", '');
4659 -
4660 - if (empty($topic_id)) {
4661 - // Generate topic name
4662 - $topic_name = $this->generate_telegram_topic_name($session_id);
4663 -
4664 - // Random icon color (Telegram forum topic colors)
4665 - $icon_colors = [0x6FB9F0, 0xFFD67E, 0xCB86DB, 0x8EEE98, 0xFF93B2, 0xFB6F5F];
4666 - $icon_color = $icon_colors[array_rand($icon_colors)];
4667 -
4668 - // Create forum topic
4669 - $response = wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/createForumTopic", [
4670 - 'headers' => ['Content-Type' => 'application/json'],
4671 - 'body' => json_encode([
4672 - 'chat_id' => $telegram_group_id,
4673 - 'name' => $topic_name,
4674 - 'icon_color' => $icon_color
4675 - ])
4676 - ]);
4677 -
4678 - if (!is_wp_error($response)) {
4679 - $response_body = wp_remote_retrieve_body($response);
4680 - $response_data = json_decode($response_body, true);
4681 -
4682 - if (isset($response_data['ok']) && $response_data['ok']) {
4683 - $topic_id = $response_data['result']['message_thread_id'];
4684 - update_option("mxchat_telegram_topic_{$session_id}", $topic_id);
4685 - update_option("mxchat_telegram_group_{$session_id}", $telegram_group_id);
4686 - }
4687 - }
4688 -
4689 - if (empty($topic_id)) {
4690 - return false; // Failed to create topic
4691 - }
4692 - }
4693 -
4694 - // Get recent chat history
4695 - $history = get_option("mxchat_history_{$session_id}", []);
4696 - $recent_history = array_slice($history, -5);
4697 -
4698 - // Format conversation context for Telegram (HTML format)
4699 - $conversation_context = "";
4700 - if (!empty($recent_history)) {
4701 - $conversation_context = "<b>Recent Conversation:</b>\n";
4702 - foreach ($recent_history as $hist_message) {
4703 - $role_display = $hist_message['role'] === 'user' ? '👤 User' : '🤖 AI';
4704 - $escaped_content = htmlspecialchars($hist_message['content'], ENT_QUOTES, 'UTF-8');
4705 - $conversation_context .= "{$role_display}: {$escaped_content}\n";
4706 - }
4707 - $conversation_context .= "\n";
4708 - }
4709 -
4710 - // Get user info
4711 - $user_email = get_option("mxchat_email_{$session_id}", 'Not provided');
4712 - $user_name = get_option("mxchat_name_{$session_id}", 'Anonymous');
4713 -
4714 - // Update session mode
4715 - update_option("mxchat_mode_{$session_id}", 'agent');
4716 -
4717 - // Send initial message to topic
4718 - $escaped_message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
4719 - $topic_message = "🔔 <b>New Live Agent Request</b>\n\n";
4720 - $topic_message .= "<b>Session ID:</b> <code>{$session_id}</code>\n";
4721 - $topic_message .= "<b>User:</b> {$user_name}\n";
4722 - $topic_message .= "<b>Email:</b> {$user_email}\n\n";
4723 -
4724 - if (!empty($conversation_context)) {
4725 - $topic_message .= $conversation_context;
4726 - }
4727 -
4728 - $topic_message .= "<b>Current Message:</b>\n{$escaped_message}\n\n";
4729 - $topic_message .= "<i>Reply in this topic - messages will be sent to the user</i>\n";
4730 - $topic_message .= "<i>Type #close, #end, #disconnect, or #done to end the session</i>";
4731 -
4732 - wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/sendMessage", [
4733 - 'headers' => ['Content-Type' => 'application/json'],
4734 - 'body' => json_encode([
4735 - 'chat_id' => $telegram_group_id,
4736 - 'message_thread_id' => $topic_id,
4737 - 'text' => $topic_message,
4738 - 'parse_mode' => 'HTML'
4739 - ])
4740 - ]);
4741 -
4742 - $success_message = $this->options['telegram_notification_message'] ?? "I've notified a support agent. Please allow a moment for them to respond.";
4743 - $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
4744 -
4745 - $this->fallbackResponse = [
4746 - 'text' => $success_message,
4747 - 'html' => '',
4748 - 'images' => [],
4749 - 'chat_mode' => 'agent'
4750 - ];
4751 -
4752 - wp_send_json([
4753 - 'success' => true,
4754 - 'text' => $success_message,
4755 - 'html' => '',
4756 - 'chat_mode' => 'agent',
4757 - 'session_id' => $session_id,
4758 - 'fallbackResponse' => $this->fallbackResponse
4759 - ]);
4760 - wp_die();
4761 -}
4762 -
4763 -/**
4764 - * Generate topic name for Telegram forum
4765 - */
4766 -private function generate_telegram_topic_name($session_id) {
4767 - $name = null;
4768 - $email = null;
4769 -
4770 - // Check logged in user
4771 - if (is_user_logged_in()) {
4772 - $current_user = wp_get_current_user();
4773 - if (!empty($current_user->display_name)) {
4774 - $name = $current_user->display_name;
4775 - }
4776 - if (!empty($current_user->user_email)) {
4777 - $email = $current_user->user_email;
4778 - }
4779 - }
4780 -
4781 - // Check session data
4782 - if (empty($name)) {
4783 - $name = get_option("mxchat_name_{$session_id}");
4784 - }
4785 - if (empty($email)) {
4786 - $email = get_option("mxchat_email_{$session_id}");
4787 - }
4788 -
4789 - // Generate topic name
4790 - $session_suffix = substr($session_id, -6);
4791 -
4792 - if (!empty($name)) {
4793 - // Clean name for topic (max 128 chars in Telegram)
4794 - $clean_name = preg_replace('/[^\p{L}\p{N}\s\-]/u', '', $name);
4795 - $clean_name = trim($clean_name);
4796 - if (strlen($clean_name) > 50) {
4797 - $clean_name = substr($clean_name, 0, 50);
4798 - }
4799 - return "Chat - {$clean_name} ({$session_suffix})";
4800 - } elseif (!empty($email)) {
4801 - // Use email prefix
4802 - $email_prefix = explode('@', $email)[0];
4803 - if (strlen($email_prefix) > 30) {
4804 - $email_prefix = substr($email_prefix, 0, 30);
4805 - }
4806 - return "Chat - {$email_prefix} ({$session_suffix})";
4807 - }
4808 -
4809 - return "Chat - {$session_suffix}";
4810 -}
4811 -
4812 -/**
4813 - * Send user message to Telegram agent
4814 - */
4815 -public function mxchat_send_user_message_to_telegram_agent($message, $user_id, $session_id) {
4816 - $telegram_bot_token = $this->options['telegram_bot_token'] ?? '';
4817 - $topic_id = get_option("mxchat_telegram_topic_{$session_id}", '');
4818 - $group_id = get_option("mxchat_telegram_group_{$session_id}", '');
4819 -
4820 - if (empty($telegram_bot_token) || empty($topic_id) || empty($group_id)) {
4821 - return false;
4822 - }
4823 -
4824 - $escaped_message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
4825 - $user_message = "👤 <b>User:</b> {$escaped_message}";
4826 -
4827 - $response = wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/sendMessage", [
4828 - 'headers' => ['Content-Type' => 'application/json'],
4829 - 'body' => json_encode([
4830 - 'chat_id' => $group_id,
4831 - 'message_thread_id' => $topic_id,
4832 - 'text' => $user_message,
4833 - 'parse_mode' => 'HTML'
4834 - ])
4835 - ]);
4836 -
4837 - return !is_wp_error($response);
4838 -}
4839 -
4840 -/**
4841 - * Handle incoming Telegram webhook
4842 - */
4843 -public function handle_telegram_webhook(WP_REST_Request $request) {
4844 - $body = $request->get_body();
4845 - $data = json_decode($body, true);
4846 -
4847 - //error_log('[MxChat Telegram DEBUG] Webhook received: ' . $body);
4848 -
4849 - // Handle message events from forum topics
4850 - if (isset($data['message'])) {
4851 - $message_data = $data['message'];
4852 -
4853 - // Skip if not from a forum topic
4854 - if (!isset($message_data['message_thread_id'])) {
4855 - //error_log('[MxChat Telegram DEBUG] Skipped: No message_thread_id (not a forum topic message)');
4856 - return new WP_REST_Response(['ok' => true]);
4857 - }
4858 -
4859 - // Skip bot messages
4860 - if (isset($message_data['from']['is_bot']) && $message_data['from']['is_bot']) {
4861 - //error_log('[MxChat Telegram DEBUG] Skipped: Message from bot');
4862 - return new WP_REST_Response(['ok' => true]);
4863 - }
4864 -
4865 - $chat_id = $message_data['chat']['id'] ?? '';
4866 - $topic_id = $message_data['message_thread_id'];
4867 - $message_text = $message_data['text'] ?? '';
4868 - $message_id = $message_data['message_id'] ?? '';
4869 - $from = $message_data['from'] ?? [];
4870 - $agent_name = trim(($from['first_name'] ?? '') . ' ' . ($from['last_name'] ?? ''));
4871 - if (empty($agent_name)) {
4872 - $agent_name = $from['username'] ?? 'Agent';
4873 - }
4874 -
4875 - //error_log("[MxChat Telegram DEBUG] Parsed: chat_id={$chat_id}, topic_id={$topic_id}, agent={$agent_name}, text={$message_text}");
4876 -
4877 - // Skip empty messages
4878 - if (empty($message_text)) {
4879 - //error_log('[MxChat Telegram DEBUG] Skipped: Empty message text');
4880 - return new WP_REST_Response(['ok' => true]);
4881 - }
4882 -
4883 - // Find session ID by topic ID - cast to string for comparison
4884 - global $wpdb;
4885 - $topic_id_str = strval($topic_id);
4886 - $session_option = $wpdb->get_var(
4887 - $wpdb->prepare(
4888 - "SELECT option_name FROM {$wpdb->options}
4889 - WHERE option_name LIKE %s
4890 - AND option_value = %s",
4891 - 'mxchat_telegram_topic_%',
4892 - $topic_id_str
4893 - )
4894 - );
4895 -
4896 - //error_log("[MxChat Telegram DEBUG] Looking for topic_id={$topic_id_str} in options, found: " . ($session_option ?: 'NULL'));
4897 -
4898 - if ($session_option) {
4899 - $session_id = str_replace('mxchat_telegram_topic_', '', $session_option);
4900 - //error_log("[MxChat Telegram DEBUG] Session ID: {$session_id}");
4901 -
4902 - // Verify the group ID matches
4903 - $stored_group_id = get_option("mxchat_telegram_group_{$session_id}", '');
4904 - //error_log("[MxChat Telegram DEBUG] Stored group_id={$stored_group_id}, received chat_id={$chat_id}");
4905 -
4906 - if (strval($stored_group_id) != strval($chat_id)) {
4907 - //error_log('[MxChat Telegram DEBUG] Skipped: Group ID mismatch');
4908 - return new WP_REST_Response(['ok' => true]);
4909 - }
4910 -
4911 - // Check for closure commands
4912 - $lower_text = strtolower(trim($message_text));
4913 - if (in_array($lower_text, ['#close', '#end', '#disconnect', '#done'])) {
4914 - //error_log("[MxChat Telegram DEBUG] Closure command received: {$lower_text}");
4915 - // End the live agent session
4916 - update_option("mxchat_mode_{$session_id}", 'ai');
4917 -
4918 - // Save disconnect message
4919 - $disconnect_message = "Live agent session ended. You're now chatting with the AI assistant.";
4920 - $this->mxchat_save_chat_message($session_id, 'bot', $disconnect_message);
4921 -
4922 - // Notify in Telegram
4923 - $telegram_bot_token = $this->options['telegram_bot_token'] ?? '';
4924 - if (!empty($telegram_bot_token)) {
4925 - wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/sendMessage", [
4926 - 'headers' => ['Content-Type' => 'application/json'],
4927 - 'body' => json_encode([
4928 - 'chat_id' => $chat_id,
4929 - 'message_thread_id' => $topic_id,
4930 - 'text' => "✅ Session closed. User returned to AI chatbot.",
4931 - 'parse_mode' => 'HTML'
4932 - ])
4933 - ]);
4934 -
4935 - // Optionally close the topic
4936 - wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/closeForumTopic", [
4937 - 'headers' => ['Content-Type' => 'application/json'],
4938 - 'body' => json_encode([
4939 - 'chat_id' => $chat_id,
4940 - 'message_thread_id' => $topic_id
4941 - ])
4942 - ]);
4943 - }
4944 -
4945 - return new WP_REST_Response(['ok' => true]);
4946 - }
4947 -
4948 - // Deduplicate messages
4949 - $message_key = md5($session_id . $message_id . $message_text);
4950 - $processed_messages = get_transient('mxchat_telegram_messages_' . $session_id) ?: [];
4951 -
4952 - if (in_array($message_key, $processed_messages)) {
4953 - //error_log('[MxChat Telegram DEBUG] Skipped: Duplicate message');
4954 - return new WP_REST_Response(['ok' => true]);
4955 - }
4956 -
4957 - $processed_messages[] = $message_key;
4958 - if (count($processed_messages) > 50) {
4959 - $processed_messages = array_slice($processed_messages, -50);
4960 - }
4961 - set_transient('mxchat_telegram_messages_' . $session_id, $processed_messages, HOUR_IN_SECONDS);
4962 -
4963 - // Save the agent message - format with agent name prefix for proper parsing
4964 - $formatted_message = "Agent: {$agent_name} - {$message_text}";
4965 - //error_log("[MxChat Telegram DEBUG] Saving agent message: {$formatted_message}");
4966 -
4967 - $this->mxchat_save_chat_message($session_id, 'agent', $formatted_message);
4968 -
4969 - // Verify the message was saved to history
4970 - $history = get_option("mxchat_history_{$session_id}", []);
4971 - $last_message = end($history);
4972 - //error_log("[MxChat Telegram DEBUG] History after save - count: " . count($history) . ", last message role: " . ($last_message['role'] ?? 'none'));
4973 -
4974 - // Send confirmation back to Telegram
4975 - $telegram_bot_token = $this->options['telegram_bot_token'] ?? '';
4976 - if (!empty($telegram_bot_token)) {
4977 - $confirm_key = 'mxchat_telegram_confirm_' . $message_key;
4978 - if (!get_transient($confirm_key)) {
4979 - wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/sendMessage", [
4980 - 'headers' => ['Content-Type' => 'application/json'],
4981 - 'body' => json_encode([
4982 - 'chat_id' => $chat_id,
4983 - 'message_thread_id' => $topic_id,
4984 - 'text' => "✅ <i>Message sent to user</i>",
4985 - 'parse_mode' => 'HTML',
4986 - 'reply_to_message_id' => $message_id
4987 - ])
4988 - ]);
4989 - set_transient($confirm_key, true, 300);
4990 - }
4991 - }
4992 - } else {
4993 - //error_log("[MxChat Telegram DEBUG] No session found for topic_id={$topic_id}");
4994 - }
4995 - } else {
4996 - //error_log('[MxChat Telegram DEBUG] No message in webhook data');
4997 - }
4998 -
4999 - return new WP_REST_Response(['ok' => true]);
5000 -}
5001 -
5002 -public function mxchat_send_user_message_to_agent($message, $user_id, $session_id) {
5003 - // Check if this is a Telegram agent session
5004 - $telegram_topic_id = get_option("mxchat_telegram_topic_{$session_id}", '');
5005 - if (!empty($telegram_topic_id)) {
5006 - return $this->mxchat_send_user_message_to_telegram_agent($message, $user_id, $session_id);
5007 - }
5008 -
5009 - // Otherwise, try Slack
5010 - $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
5011 - $channel_id = get_option("mxchat_channel_{$session_id}", '');
5012 -
5013 - if (empty($slack_bot_token) || empty($channel_id)) {
5014 - return false;
5015 - }
5016 -
5017 - $user_message = "💬 *User:* {$message}";
5018 -
5019 - $response = wp_remote_post('https://slack.com/api/chat.postMessage', [
5020 - 'headers' => [
5021 - 'Content-Type' => 'application/json',
5022 - 'Authorization' => 'Bearer ' . $slack_bot_token
5023 - ],
5024 - 'body' => json_encode([
5025 - 'channel' => $channel_id,
5026 - 'text' => $user_message,
5027 - 'mrkdwn' => true
5028 - ])
5029 - ]);
5030 -
5031 - return !is_wp_error($response);
5032 -}
5033 -public function handle_slack_interaction(WP_REST_Request $request) {
5034 - //error_log('Received Slack interaction');
5035 -
5036 - $payload = json_decode($request->get_param('payload'), true);
5037 - //error_log('Payload: ' . print_r($payload, true));
5038 -
5039 - // Handle button click
5040 - if ($payload['type'] === 'block_actions' && $payload['actions'][0]['action_id'] === 'reply_to_user') {
5041 - $session_id = $payload['actions'][0]['value'];
5042 - $trigger_id = $payload['trigger_id'];
5043 -
5044 - // Get Bot Token from settings
5045 - $slack_token = $this->options['live_agent_bot_token'] ?? '';
5046 -
5047 - if (empty($slack_token)) {
5048 - //error_log('Slack Bot Token not configured');
5049 - return new WP_REST_Response(['error' => esc_html__('Bot token not configured', 'mxchat')], 400);
5050 - }
5051 - $response = wp_remote_post('https://slack.com/api/views.open', [
5052 - 'headers' => [
5053 - 'Content-Type' => 'application/json',
5054 - 'Authorization' => 'Bearer ' . $slack_token
5055 - ],
5056 - 'body' => json_encode([
5057 - 'trigger_id' => $trigger_id,
5058 - 'view' => [
5059 - 'type' => 'modal',
5060 - 'callback_id' => 'reply_modal',
5061 - 'title' => [
5062 - 'type' => 'plain_text',
5063 - 'text' => __('Reply to User', 'mxchat')
5064 - ],
5065 - 'submit' => [
5066 - 'type' => 'plain_text',
5067 - 'text' => __('Send', 'mxchat')
5068 - ],
5069 - 'close' => [
5070 - 'type' => 'plain_text',
5071 - 'text' => __('Cancel', 'mxchat')
5072 - ],
5073 - 'blocks' => [
5074 - [
5075 - 'type' => 'input',
5076 - 'block_id' => 'reply_block',
5077 - 'label' => [
5078 - 'type' => 'plain_text',
5079 - 'text' => sprintf(__('Reply to session: %s', 'mxchat'), $session_id)
5080 - ],
5081 - 'element' => [
5082 - 'type' => 'plain_text_input',
5083 - 'action_id' => 'message',
5084 - 'multiline' => true,
5085 - 'placeholder' => [
5086 - 'type' => 'plain_text',
5087 - 'text' => __('Type your message here...', 'mxchat')
5088 - ]
5089 - ]
5090 - ]
5091 - ],
5092 - 'private_metadata' => $session_id
5093 - ]
5094 - ])
5095 - ]);
5096 -
5097 - //error_log('Views.open response: ' . print_r($response, true));
5098 -
5099 - // Return immediate acknowledgment
5100 - return new WP_REST_Response(['ok' => true]);
5101 - }
5102 -
5103 - // Handle modal submission
5104 -// Handle modal submission
5105 -if ($payload['type'] === 'view_submission') {
5106 - $session_id = $payload['view']['private_metadata'];
5107 - $message = $payload['view']['state']['values']['reply_block']['message']['value'];
5108 -
5109 - // Save the message (keep the message_id but don't include in response)
5110 - $this->mxchat_save_chat_message($session_id, 'agent', $message);
5111 -
5112 - // Keep the original response format for Slack
5113 - return new WP_REST_Response([
5114 - 'response_action' => 'clear'
5115 - ]);
5116 -}
5117 -
5118 - // Default acknowledgment
5119 - return new WP_REST_Response(['ok' => true]);
5120 -}
5121 -public function mxchat_handle_agent_response(WP_REST_Request $request) {
5122 - //error_log('Received agent response request');
5123 - //error_log('Request data: ' . print_r($request->get_params(), true));
5124 - // //error_log('Raw body: ' . file_get_contents('php://input'));
5125 -
5126 - // Get the data from Slack's slash command format
5127 - $command_text = $request->get_param('text');
5128 - // //error_log('Command text: ' . $command_text);
5129 -
5130 - if (empty($command_text)) {
5131 - //error_log(esc_html__('Agent response error: No command text received', 'mxchat'));
5132 - return new WP_REST_Response([
5133 - 'error' => esc_html__('Command text is required. Format: /reply session_id message', 'mxchat')
5134 - ], 400);
5135 - }
5136 -
5137 - // Split the command text into session_id and message
5138 - $parts = explode(' ', $command_text, 2);
5139 - if (count($parts) !== 2) {
5140 - //error_log('Agent response error: Invalid command format');
5141 - return new WP_REST_Response([
5142 - 'error' => esc_html__('Invalid format. Use: /reply session_id message', 'mxchat')
5143 - ], 400);
5144 - }
5145 -
5146 - $session_id = sanitize_text_field($parts[0]);
5147 - $message = sanitize_text_field($parts[1]);
5148 -
5149 - //error_log("Processing agent response - Session ID: $session_id, Message: $message");
5150 -
5151 - // Save the message
5152 - $message_id = $this->mxchat_save_chat_message($session_id, 'agent', $message);
5153 -
5154 - if (!$message_id) {
5155 - // //error_log('Failed to save agent message');
5156 - return new WP_REST_Response([
5157 - 'error' => esc_html__('Failed to save message', 'mxchat')
5158 - ], 500);
5159 - }
5160 -
5161 - // Return success response in Slack's expected format
5162 - return new WP_REST_Response([
5163 - 'response_type' => 'in_channel',
5164 - 'text' => esc_html__("Message sent successfully to session $session_id", 'mxchat')
5165 - ], 200);
5166 -}
5167 -public function mxchat_handle_switch_to_chatbot_intent($message, $user_id, $session_id) {
5168 - // Update mode to AI
5169 - update_option("mxchat_mode_{$session_id}", 'ai');
5170 -
5171 - // Clear any existing PDF context to start fresh
5172 - $this->clear_pdf_transients($session_id);
5173 -
5174 - // Set the response with explicit chat_mode
5175 - $this->fallbackResponse = [
5176 - 'text' => esc_html__('You are now chatting with the AI chatbot.', 'mxchat'),
5177 - 'html' => '',
5178 - 'images' => [],
5179 - 'chat_mode' => 'ai' // Ensure this is set
5180 - ];
5181 -
5182 - // Return the complete response array instead of just true
5183 - return $this->fallbackResponse;
5184 -}
5185 -
5186 -/**
5187 - * Normalize Slack mrkdwn before relaying an agent's message to the web visitor.
5188 - * Slack's Events API auto-wraps URLs as <https://url> or <https://url|Label>, wraps
5189 - * mentions as <@U…>/<#C…|name>, and HTML-escapes &, <, >. Relayed raw, the visitor
5190 - * sees a broken/doubled link with a trailing > (plan-e2195b). Unwrap links FIRST, then
5191 - * unescape entities LAST so extracted URLs (which can contain &amp;) are not corrupted.
5192 - */
5193 -private function normalize_slack_text($text) {
5194 - if (!is_string($text) || $text === '') {
5195 - return $text;
5196 - }
5197 -
5198 - $text = preg_replace_callback('/<([^>|]+)(?:\|([^>]*))?>/', function ($m) {
5199 - $target = $m[1];
5200 - $label = isset($m[2]) ? $m[2] : '';
5201 -
5202 - // User/channel mentions: <@U…> or <#C…|name> — prefer the human label, else drop the id.
5203 - if (isset($target[0]) && ($target[0] === '@' || $target[0] === '#')) {
5204 - return $label !== '' ? $label : '';
5205 - }
5206 - // mailto:/tel: — strip the scheme for display.
5207 - if (stripos($target, 'mailto:') === 0) {
5208 - $addr = substr($target, 7);
5209 - return ($label !== '' && $label !== $addr) ? "{$label} ({$addr})" : $addr;
5210 - }
5211 - if (stripos($target, 'tel:') === 0) {
5212 - $num = substr($target, 4);
5213 - return ($label !== '' && $label !== $num) ? "{$label} ({$num})" : $num;
5214 - }
5215 - // Regular URL: <url|Label> -> "Label (url)"; bare <url> -> "url".
5216 - if ($label !== '' && $label !== $target) {
5217 - return "{$label} ({$target})";
5218 - }
5219 - return $target;
5220 - }, $text);
5221 -
5222 - // Entity-unescape LAST (after link extraction) so &amp; inside URLs is repaired too.
5223 - $text = str_replace(array('&amp;', '&lt;', '&gt;'), array('&', '<', '>'), $text);
5224 -
5225 - return $text;
5226 -}
5227 -
5228 -/**
5229 - * Resolve the visitor's name + email for a session, mirroring generate_channel_name()'s
5230 - * priority order: logged-in user, then the pre-chat gate options (mxchat_email_/mxchat_name_),
5231 - * then the chat transcript. Returns ['name' => ..., 'email' => ...] (either may be ''). plan-e2195b.
5232 - */
5233 -private function mxchat_get_visitor_identity($session_id) {
5234 - $email = '';
5235 - $name = '';
5236 -
5237 - if (is_user_logged_in()) {
5238 - $current_user = wp_get_current_user();
5239 - if (!empty($current_user->user_email)) { $email = $current_user->user_email; }
5240 - if (!empty($current_user->display_name)) { $name = $current_user->display_name; }
5241 - }
5242 -
5243 - if (empty($email)) {
5244 - $saved_email = get_option("mxchat_email_{$session_id}", '');
5245 - if (!empty($saved_email)) { $email = $saved_email; }
5246 - }
5247 - if (empty($name)) {
5248 - $saved_name = get_option("mxchat_name_{$session_id}", '');
5249 - if (!empty($saved_name)) { $name = $saved_name; }
5250 - }
5251 -
5252 - if (empty($email) || empty($name)) {
5253 - global $wpdb;
5254 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
5255 - $existing_data = $wpdb->get_row($wpdb->prepare(
5256 - "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",
5257 - $session_id
5258 - ));
5259 - if ($existing_data) {
5260 - if (empty($email) && !empty($existing_data->user_email)) { $email = $existing_data->user_email; }
5261 - if (empty($name) && !empty($existing_data->user_name)) { $name = $existing_data->user_name; }
5262 - }
5263 - }
5264 -
5265 - return array('name' => $name, 'email' => $email);
5266 -}
5267 -
5268 -public function handle_slack_messages(WP_REST_Request $request) {
5269 - // Log the incoming request for debugging
5270 - //error_log('Slack events request received: ' . $request->get_body());
5271 -
5272 - $body = $request->get_body();
5273 - $data = json_decode($body, true);
5274 -
5275 - // Handle Slack URL verification
5276 - if (isset($data['type']) && $data['type'] === 'url_verification') {
5277 - //error_log('Slack URL verification challenge: ' . $data['challenge']);
5278 - return new WP_REST_Response($data['challenge'], 200, ['Content-Type' => 'text/plain']);
5279 - }
5280 -
5281 - // IMPORTANT: Handle Slack's event deduplication
5282 - if (isset($data['event_id'])) {
5283 - $event_id = $data['event_id'];
5284 - $processed_events = get_transient('mxchat_slack_events') ?: [];
5285 -
5286 - // Check if we've already processed this event
5287 - if (in_array($event_id, $processed_events)) {
5288 - //error_log("Duplicate event detected: $event_id");
5289 - return new WP_REST_Response(['ok' => true]);
5290 - }
5291 -
5292 - // Add this event to processed list
5293 - $processed_events[] = $event_id;
5294 - // Keep only last 100 events to prevent memory issues
5295 - if (count($processed_events) > 100) {
5296 - $processed_events = array_slice($processed_events, -100);
5297 - }
5298 - // Store for 1 hour
5299 - set_transient('mxchat_slack_events', $processed_events, HOUR_IN_SECONDS);
5300 - }
5301 -
5302 - // Handle message events
5303 - if (isset($data['event']) && $data['event']['type'] === 'message') {
5304 - $event = $data['event'];
5305 -
5306 - // Skip bot messages and messages with subtypes (like bot_message)
5307 - if (isset($event['bot_id']) || isset($event['subtype'])) {
5308 - return new WP_REST_Response(['ok' => true]);
5309 - }
5310 -
5311 - // Additional check: Skip if this is a threaded reply to our confirmation
5312 - if (isset($event['thread_ts']) && $event['thread_ts'] !== $event['ts']) {
5313 - return new WP_REST_Response(['ok' => true]);
5314 - }
5315 -
5316 - $channel_id = $event['channel'];
5317 - $message_text = $event['text'] ?? '';
5318 - $message_ts = $event['ts'] ?? '';
5319 -
5320 - // Find session ID by looking for matching channel
5321 - global $wpdb;
5322 - $session_option = $wpdb->get_var(
5323 - $wpdb->prepare(
5324 - "SELECT option_name FROM {$wpdb->options}
5325 - WHERE option_name LIKE 'mxchat_channel_%'
5326 - AND option_value = %s",
5327 - $channel_id
5328 - )
5329 - );
5330 -
5331 - if ($session_option) {
5332 - $session_id = str_replace('mxchat_channel_', '', $session_option);
5333 -
5334 - // Create a unique key for this specific message
5335 - $message_key = md5($session_id . $message_ts . $message_text);
5336 - $processed_messages = get_transient('mxchat_processed_messages_' . $session_id) ?: [];
5337 -
5338 - // Check if we've already processed this exact message
5339 - if (in_array($message_key, $processed_messages)) {
5340 - //error_log("Duplicate message detected for session $session_id");
5341 - return new WP_REST_Response(['ok' => true]);
5342 - }
5343 -
5344 - // Add to processed messages
5345 - $processed_messages[] = $message_key;
5346 - // Keep only last 50 messages per session
5347 - if (count($processed_messages) > 50) {
5348 - $processed_messages = array_slice($processed_messages, -50);
5349 - }
5350 - set_transient('mxchat_processed_messages_' . $session_id, $processed_messages, HOUR_IN_SECONDS);
5351 -
5352 - $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
5353 -
5354 - // Handle agent ending the chat — transfer back to AI
5355 - // Format: "!endchat" or "!endchat <custom message to user>"
5356 - if (preg_match('/^!endchat\b/i', trim($message_text))) {
5357 - update_option("mxchat_mode_{$session_id}", 'ai');
5358 -
5359 - // Extract custom message after !endchat, or use empty string
5360 - $custom_message = trim(preg_replace('/^!endchat\s*/i', '', trim($message_text)));
5361 -
5362 - // Send the agent's custom farewell message if provided
5363 - if (!empty($custom_message)) {
5364 - $this->mxchat_save_chat_message($session_id, 'agent', $this->normalize_slack_text($custom_message));
5365 - }
5366 -
5367 - // Confirm in Slack channel
5368 - if (!empty($slack_bot_token)) {
5369 - wp_remote_post('https://slack.com/api/chat.postMessage', [
5370 - 'headers' => [
5371 - 'Content-Type' => 'application/json',
5372 - 'Authorization' => 'Bearer ' . $slack_bot_token
5373 - ],
5374 - 'body' => json_encode([
5375 - 'channel' => $channel_id,
5376 - 'text' => "✅ *Chat ended.* User has been transferred back to AI mode.",
5377 - 'mrkdwn' => true
5378 - ])
5379 - ]);
5380 - }
5381 -
5382 - return new WP_REST_Response(['ok' => true]);
5383 - }
5384 -
5385 - // Save the agent message (normalize Slack link/entity formatting first — plan-e2195b)
5386 - $this->mxchat_save_chat_message($session_id, 'agent', $this->normalize_slack_text($message_text));
5387 -
5388 - // Send confirmation back to Slack (only once)
5389 - if (!empty($slack_bot_token)) {
5390 - // Use a transient to prevent duplicate confirmations
5391 - $confirm_key = 'mxchat_confirm_' . $message_key;
5392 - if (!get_transient($confirm_key)) {
5393 - wp_remote_post('https://slack.com/api/chat.postMessage', [
5394 - 'headers' => [
5395 - 'Content-Type' => 'application/json',
5396 - 'Authorization' => 'Bearer ' . $slack_bot_token
5397 - ],
5398 - 'body' => json_encode([
5399 - 'channel' => $channel_id,
5400 - 'text' => "✅ _Message sent to user_",
5401 - 'thread_ts' => $event['ts'] // Reply in thread
5402 - ])
5403 - ]);
5404 - // Set transient to prevent duplicate confirmations
5405 - set_transient($confirm_key, true, 300); // 5 minutes
5406 - }
5407 - }
5408 - }
5409 - }
5410 -
5411 - return new WP_REST_Response(['ok' => true]);
5412 -}
5413 -
5414 -// For the word upload handler
5415 -public function mxchat_handle_word_upload() {
5416 - // Delegate to word handler
5417 - $this->word_handler->mxchat_handle_word_upload();
5418 -}
5419 -
5420 -// For the word removal handler
5421 -public function mxchat_handle_word_remove() {
5422 - // Delegate to word handler
5423 - $this->word_handler->mxchat_handle_word_remove();
5424 -}
5425 -
5426 -// For the word status check
5427 -public function mxchat_check_word_status() {
5428 - // Delegate to word handler
5429 - $this->word_handler->mxchat_check_word_status();
5430 -}
5431 -
5432 -
5433 -private function mxchat_get_user_identifier() {
5434 - return MxChat_User::mxchat_get_user_identifier();
5435 -}
5436 -
5437 -private function mxchat_generate_embedding($text, $api_key) {
5438 - try {
5439 - // Get options and selected model
5440 - $options = get_option('mxchat_options');
5441 - $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
5442 -
5443 - // Opt-in: route embeddings through the Custom (OpenAI-compatible) provider.
5444 - // Off by default so existing sites see byte-identical behavior.
5445 - if (!empty($options['custom_provider_for_embeddings']) && $options['custom_provider_for_embeddings'] === 'on') {
5446 - return $this->mxchat_generate_embedding_custom($text);
5447 - }
5448 -
5449 - // Determine endpoint and API key based on model
5450 - if (strpos($selected_model, 'voyage') === 0) {
5451 - $endpoint = 'https://api.voyageai.com/v1/embeddings';
5452 - $api_key = $options['voyage_api_key'] ?? '';
5453 -
5454 - // Check if Voyage API key is missing
5455 - if (empty($api_key)) {
5456 - //error_log('Voyage API key is missing');
5457 - return [
5458 - 'error' => esc_html__('Voyage AI API key is not configured', 'mxchat'),
5459 - 'error_code' => 'missing_voyage_api_key'
5460 - ];
5461 - }
5462 - } elseif (strpos($selected_model, 'gemini-embedding') === 0) {
5463 - $endpoint = 'https://generativelanguage.googleapis.com/v1beta/models/' . $selected_model . ':embedContent';
5464 - $api_key = $options['gemini_api_key'] ?? '';
5465 -
5466 - // Check if Gemini API key is missing
5467 - if (empty($api_key)) {
5468 - //error_log('Gemini API key is missing');
5469 - return [
5470 - 'error' => esc_html__('Google Gemini API key is not configured', 'mxchat'),
5471 - 'error_code' => 'missing_gemini_api_key'
5472 - ];
5473 - }
5474 - } else {
5475 - $endpoint = 'https://api.openai.com/v1/embeddings';
5476 - // Use the passed API key for OpenAI
5477 -
5478 - // Check if OpenAI API key is missing
5479 - if (empty($api_key)) {
5480 - //error_log('OpenAI API key is missing');
5481 - return [
5482 - 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
5483 - 'error_code' => 'missing_openai_api_key'
5484 - ];
5485 - }
5486 - }
5487 -
5488 - // Check if text is empty
5489 - if (empty($text)) {
5490 - //error_log('Empty text provided for embedding generation');
5491 - return [
5492 - 'error' => esc_html__('No text provided for embedding generation', 'mxchat'),
5493 - 'error_code' => 'empty_embedding_text'
5494 - ];
5495 - }
5496 -
5497 - // Prepare request body based on provider
5498 - if (strpos($selected_model, 'gemini-embedding') === 0) {
5499 - // Gemini API format
5500 - $request_body = [
5501 - 'model' => 'models/' . $selected_model,
5502 - 'content' => [
5503 - 'parts' => [
5504 - ['text' => $text]
5505 - ]
5506 - ],
5507 - 'outputDimensionality' => 1536
5508 - ];
5509 -
5510 - // Prepare headers for Gemini (API key as query parameter)
5511 - $endpoint .= '?key=' . $api_key;
5512 - $headers = [
5513 - 'Content-Type' => 'application/json'
5514 - ];
5515 - } else {
5516 - // OpenAI/Voyage API format
5517 - $request_body = [
5518 - 'input' => $text,
5519 - 'model' => $selected_model
5520 - ];
5521 -
5522 - // Add output_dimension for voyage-3-large
5523 - if ($selected_model === 'voyage-3-large') {
5524 - $request_body['output_dimension'] = 2048;
5525 - }
5526 -
5527 - // Prepare headers for OpenAI/Voyage
5528 - $headers = [
5529 - 'Content-Type' => 'application/json',
5530 - 'Authorization' => 'Bearer ' . $api_key
5531 - ];
5532 - }
5533 -
5534 - // Prepare request arguments
5535 - $args = [
5536 - 'body' => wp_json_encode($request_body),
5537 - 'headers' => $headers,
5538 - 'timeout' => 60,
5539 - 'redirection' => 5,
5540 - 'blocking' => true,
5541 - 'httpversion' => '1.0',
5542 - 'sslverify' => true,
5543 - ];
5544 -
5545 - // Make the request
5546 - $response = wp_remote_post($endpoint, $args);
5547 -
5548 - // Handle WordPress errors
5549 - if (is_wp_error($response)) {
5550 - $error_message = $response->get_error_message();
5551 - //error_log('Embedding Generation Error: ' . $error_message);
5552 - return [
5553 - 'error' => esc_html__('Connection error when generating embeddings: ', 'mxchat') . esc_html($error_message),
5554 - 'error_code' => 'embedding_connection_error'
5555 - ];
5556 - }
5557 -
5558 - // Check HTTP status code
5559 - $status_code = wp_remote_retrieve_response_code($response);
5560 - if ($status_code !== 200) {
5561 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
5562 -
5563 - $error_message = isset($response_body['error']['message'])
5564 - ? $response_body['error']['message']
5565 - : 'HTTP Error ' . $status_code;
5566 -
5567 - $error_type = isset($response_body['error']['type'])
5568 - ? $response_body['error']['type']
5569 - : 'unknown';
5570 -
5571 - //error_log('Embedding API HTTP Error: ' . $status_code . ' - ' . $error_message);
5572 -
5573 - // Handle specific error types
5574 - switch ($error_type) {
5575 - case 'invalid_request_error':
5576 - if (strpos($error_message, 'API key') !== false) {
5577 - return [
5578 - 'error' => esc_html__('Invalid API key for embedding generation. Please check your API key configuration.', 'mxchat'),
5579 - 'error_code' => 'embedding_invalid_api_key'
5580 - ];
5581 - }
5582 - break;
5583 -
5584 - case 'authentication_error':
5585 - return [
5586 - 'error' => esc_html__('Authentication failed for embedding generation. Please check your API key.', 'mxchat'),
5587 - 'error_code' => 'embedding_auth_error'
5588 - ];
5589 -
5590 - case 'rate_limit_exceeded':
5591 - return [
5592 - 'error' => esc_html__('Rate limit exceeded for embedding generation. Please try again later.', 'mxchat'),
5593 - 'error_code' => 'embedding_rate_limit'
5594 - ];
5595 -
5596 - case 'quota_exceeded':
5597 - return [
5598 - 'error' => esc_html__('API quota exceeded for embedding generation. Please check your billing details.', 'mxchat'),
5599 - 'error_code' => 'embedding_quota_exceeded'
5600 - ];
5601 - }
5602 -
5603 - // Generic error fallback
5604 - return [
5605 - 'error' => esc_html__('Embedding API error - check embedding API key.: ', 'mxchat') . esc_html($error_message),
5606 - 'error_code' => 'embedding_api_error',
5607 - 'status_code' => $status_code
5608 - ];
5609 - }
5610 -
5611 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
5612 -
5613 - // Handle different response formats based on provider
5614 - if (strpos($selected_model, 'gemini-embedding') === 0) {
5615 - // Gemini API response format
5616 - if (isset($response_body['embedding']['values']) && is_array($response_body['embedding']['values'])) {
5617 - return $response_body['embedding']['values'];
5618 - } else {
5619 - //error_log('Invalid Gemini embedding response: ' . wp_json_encode($response_body));
5620 - return [
5621 - 'error' => esc_html__('Received invalid embedding data from the Gemini API.', 'mxchat'),
5622 - 'error_code' => 'invalid_gemini_embedding_response'
5623 - ];
5624 - }
5625 - } else {
5626 - // OpenAI/Voyage API response format
5627 - if (isset($response_body['data'][0]['embedding']) && is_array($response_body['data'][0]['embedding'])) {
5628 - return $response_body['data'][0]['embedding'];
5629 - } else {
5630 - //error_log('Invalid embedding response: ' . wp_json_encode($response_body));
5631 - return [
5632 - 'error' => esc_html__('Received invalid embedding data from the API.', 'mxchat'),
5633 - 'error_code' => 'invalid_embedding_response'
5634 - ];
5635 - }
5636 - }
5637 - } catch (Exception $e) {
5638 - //error_log('Embedding Exception: ' . $e->getMessage());
5639 - return [
5640 - 'error' => esc_html__('System error when generating embeddings: ', 'mxchat') . esc_html($e->getMessage()),
5641 - 'error_code' => 'embedding_exception'
5642 - ];
5643 - }
5644 -}
5645 -
5646 -
5647 -/**
5648 - * Generate embedding via a Custom (OpenAI-compatible) provider's /embeddings route.
5649 - * Only called when the opt-in 'custom_provider_for_embeddings' setting is on.
5650 - * Returns a numeric array (the embedding vector) on success, or ['error','error_code'] on failure.
5651 - */
5652 -private function mxchat_generate_embedding_custom($text) {
5653 - if (empty($text)) {
5654 - return ['error' => esc_html__('No text provided for embedding generation', 'mxchat'), 'error_code' => 'empty_embedding_text'];
5655 - }
5656 - $cfg = $this->mxchat_resolve_custom_provider();
5657 - if (empty($cfg['base_url'])) {
5658 - return ['error' => esc_html__('Custom provider Base URL is not configured.', 'mxchat'), 'error_code' => 'missing_custom_provider_base_url'];
5659 - }
5660 -
5661 - $options = get_option('mxchat_options');
5662 - $embed_url = $cfg['base_url'] . '/embeddings';
5663 - if (!empty($cfg['api_version'])) {
5664 - $embed_url .= (strpos($embed_url, '?') === false ? '?' : '&') . 'api-version=' . rawurlencode($cfg['api_version']);
5665 - }
5666 - $model = isset($options['custom_provider_embedding_model']) && trim((string) $options['custom_provider_embedding_model']) !== ''
5667 - ? trim((string) $options['custom_provider_embedding_model'])
5668 - : $cfg['model'];
5669 -
5670 - $response = wp_remote_post($embed_url, [
5671 - 'headers' => $this->mxchat_custom_provider_assoc_headers($cfg),
5672 - 'body' => wp_json_encode(['input' => $text, 'model' => $model]),
5673 - 'timeout' => 60,
5674 - ]);
5675 - if (is_wp_error($response)) {
5676 - return [
5677 - 'error' => esc_html__('Connection error when generating embeddings (custom provider): ', 'mxchat') . esc_html($response->get_error_message()),
5678 - 'error_code' => 'embedding_custom_connection_error',
5679 - ];
5680 - }
5681 - $status = wp_remote_retrieve_response_code($response);
5682 - $body = json_decode(wp_remote_retrieve_body($response), true);
5683 - if ($status !== 200) {
5684 - $msg = isset($body['error']['message']) ? $body['error']['message'] : 'HTTP ' . $status;
5685 - return [
5686 - 'error' => esc_html__('Custom embedding endpoint error: ', 'mxchat') . esc_html($msg),
5687 - 'error_code' => 'embedding_custom_api_error',
5688 - 'status_code' => $status,
5689 - ];
5690 - }
5691 - if (isset($body['data'][0]['embedding']) && is_array($body['data'][0]['embedding'])) {
5692 - return $body['data'][0]['embedding'];
5693 - }
5694 - return [
5695 - 'error' => esc_html__('Invalid embedding response from custom provider.', 'mxchat'),
5696 - 'error_code' => 'embedding_custom_invalid_response',
5697 - ];
5698 -}
5699 -
5700 -private function mxchat_find_relevant_content($user_embedding, $bot_id = 'default', $user_query = '') {
5701 - //error_log("MXCHAT DEBUG: find_relevant_content called with bot_id: " . $bot_id);
5702 -
5703 - // Check for OpenAI Vector Store first (takes priority when enabled)
5704 - $bot_vectorstore_config = $this->get_bot_vectorstore_config($bot_id);
5705 -
5706 - if ($bot_vectorstore_config['use_vectorstore']) {
5707 - // Get current model to verify it's an OpenAI model
5708 - $bot_options = $this->get_bot_options($bot_id);
5709 - $mxchat_options = get_option('mxchat_options', array());
5710 - $current_options = !empty($bot_options) ? $bot_options : $mxchat_options;
5711 - $selected_model = $current_options['model'] ?? 'gpt-5.1-chat-latest';
5712 -
5713 - if ($this->is_openai_chat_model($selected_model)) {
5714 - //error_log("MXCHAT DEBUG: Using OpenAI Vector Store for knowledge retrieval");
5715 - return $this->find_relevant_content_openai_vectorstore($user_query, $bot_id, $bot_vectorstore_config);
5716 - } else {
5717 - //error_log("MXCHAT DEBUG: Vector Store enabled but model is not OpenAI (" . $selected_model . "), skipping Vector Store");
5718 - }
5719 - }
5720 -
5721 - // Get bot-specific Pinecone configuration
5722 - $bot_pinecone_config = $this->get_bot_pinecone_config($bot_id);
5723 -
5724 - // Debug: Log the Pinecone configuration
5725 - //error_log("MXCHAT DEBUG: Pinecone config for bot '$bot_id':");
5726 - //error_log(" - use_pinecone: " . ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false'));
5727 - //error_log(" - api_key: " . (empty($bot_pinecone_config['api_key']) ? 'EMPTY' : 'SET (hidden)'));
5728 - //error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'NOT SET'));
5729 - //error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'NOT SET'));
5730 -
5731 - // Determine whether to use Pinecone based on bot configuration
5732 - $use_pinecone = isset($bot_pinecone_config['use_pinecone']) ? $bot_pinecone_config['use_pinecone'] : false;
5733 -
5734 - //error_log("MXCHAT DEBUG: Using " . ($use_pinecone ? "Pinecone" : "WordPress Database") . " for knowledge retrieval");
5735 -
5736 - if ($use_pinecone) {
5737 - return $this->find_relevant_content_pinecone($user_embedding, $bot_id, $bot_pinecone_config);
5738 - } else {
5739 - return $this->find_relevant_content_wordpress($user_embedding, $bot_id);
5740 - }
5741 -}
5742 -
5743 -private function find_relevant_content_wordpress($user_embedding, $bot_id = 'default') {
5744 - global $wpdb;
5745 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
5746 - // Initialize similarity analysis storage
5747 - $this->last_similarity_analysis = [
5748 - 'knowledge_base_type' => 'WordPress Database',
5749 - 'bot_id' => $bot_id,
5750 - 'top_matches' => [],
5751 - 'threshold_used' => 0,
5752 - 'total_checked' => 0
5753 - ];
5754 -
5755 - // NEW: Initialize valid URLs array
5756 - $valid_urls = [];
5757 -
5758 - // Get bot-specific options for similarity threshold
5759 - $bot_options = $this->get_bot_options($bot_id);
5760 - $current_options = !empty($bot_options) ? $bot_options : $this->options;
5761 -
5762 - // Get knowledge manager instance for role checking
5763 - $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
5764 -
5765 - // Get base similarity threshold from bot options or default options
5766 - $similarity_threshold = isset($current_options['similarity_threshold'])
5767 - ? ((int) $current_options['similarity_threshold']) / 100
5768 - : 0.35;
5769 - $this->last_similarity_analysis['threshold_used'] = $similarity_threshold;
5770 -
5771 - // Precompute bot_filter once, outside the streaming loop
5772 - $bot_filter = '';
5773 - if ($bot_id !== 'default') {
5774 - $column_exists = $wpdb->get_var("SHOW COLUMNS FROM {$system_prompt_table} LIKE 'bot_metadata'");
5775 - if ($column_exists) {
5776 - $bot_filter = $wpdb->prepare(" AND (bot_metadata = %s OR bot_metadata IS NULL OR bot_metadata = '')", $bot_id);
5777 - }
5778 - }
5779 -
5780 - // ===== STREAMING TOP-K PASS =====
5781 - // Stream rows in small batches, compute cosine similarity per row, and keep only:
5782 - // - top 10 by raw similarity (for the testing/debug display panel)
5783 - // - candidates above threshold with access (capped) for context assembly
5784 - // This bounds peak memory regardless of knowledge base size and avoids loading
5785 - // article_content for every row. article_content is fetched in Phase 2 for winners only.
5786 - $batch_size = 250;
5787 - $max_candidates = 200; // safety cap, well above rag_sources_limit * max_chunks_per_source
5788 - $top_display = [];
5789 - $candidates = [];
5790 - $total_checked = 0;
5791 - $offset = 0;
5792 -
5793 - do {
5794 - $batch = $wpdb->get_results($wpdb->prepare(
5795 - "SELECT id, embedding_vector, source_url, role_restriction
5796 - FROM {$system_prompt_table}
5797 - WHERE 1=1 {$bot_filter}
5798 - LIMIT %d OFFSET %d",
5799 - $batch_size,
5800 - $offset
5801 - ));
5802 -
5803 - if (empty($batch)) {
5804 - break;
5805 - }
5806 -
5807 - foreach ($batch as $row) {
5808 - $database_embedding = $row->embedding_vector
5809 - ? unserialize($row->embedding_vector, ['allowed_classes' => false])
5810 - : null;
5811 -
5812 - if (!is_array($database_embedding) || !is_array($user_embedding)) {
5813 - unset($database_embedding);
5814 - continue;
5815 - }
5816 -
5817 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
5818 - unset($database_embedding);
5819 -
5820 - $role_restriction = $row->role_restriction ?? 'public';
5821 - $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
5822 - $source_url = $row->source_url ?? '';
5823 -
5824 - // Maintain top 10 display buffer (insert-if-beats-worst)
5825 - if (count($top_display) < 10) {
5826 - $top_display[] = [
5827 - 'id' => $row->id,
5828 - 'similarity' => $similarity,
5829 - 'source_url' => $source_url,
5830 - 'role_restriction' => $role_restriction,
5831 - 'has_access' => $has_access,
5832 - ];
5833 - usort($top_display, function ($a, $b) {
5834 - return $b['similarity'] <=> $a['similarity'];
5835 - });
5836 - } elseif ($similarity > $top_display[9]['similarity']) {
5837 - $top_display[9] = [
5838 - 'id' => $row->id,
5839 - 'similarity' => $similarity,
5840 - 'source_url' => $source_url,
5841 - 'role_restriction' => $role_restriction,
5842 - 'has_access' => $has_access,
5843 - ];
5844 - usort($top_display, function ($a, $b) {
5845 - return $b['similarity'] <=> $a['similarity'];
5846 - });
5847 - }
5848 -
5849 - // Track candidates for context assembly (above threshold + has access)
5850 - if ($similarity >= $similarity_threshold && $has_access) {
5851 - $candidates[] = [
5852 - 'id' => $row->id,
5853 - 'similarity' => $similarity,
5854 - 'source_url' => $source_url,
5855 - ];
5856 - }
5857 -
5858 - $total_checked++;
5859 - }
5860 -
5861 - unset($batch);
5862 -
5863 - // Trim candidates periodically to cap memory during long scans
5864 - if (count($candidates) > $max_candidates) {
5865 - usort($candidates, function ($a, $b) {
5866 - return $b['similarity'] <=> $a['similarity'];
5867 - });
5868 - $candidates = array_slice($candidates, 0, $max_candidates);
5869 - }
5870 -
5871 - $offset += $batch_size;
5872 - } while (true);
5873 -
5874 - if ($total_checked === 0) {
5875 - $this->current_valid_urls = [];
5876 - return '';
5877 - }
5878 -
5879 - // Final candidates sort (best first)
5880 - if (count($candidates) > 1) {
5881 - usort($candidates, function ($a, $b) {
5882 - return $b['similarity'] <=> $a['similarity'];
5883 - });
5884 - }
5885 -
5886 - // ===== PHASE 2: FETCH ARTICLE CONTENT ONLY FOR WINNERS =====
5887 - // Gather unique IDs we actually need (top_display + candidates) and pull
5888 - // article_content in bounded IN() batches. This avoids loading content for
5889 - // every row during the similarity scan.
5890 - $needed_ids = [];
5891 - foreach ($top_display as $item) {
5892 - $needed_ids[$item['id']] = true;
5893 - }
5894 - foreach ($candidates as $item) {
5895 - $needed_ids[$item['id']] = true;
5896 - }
5897 - $needed_ids = array_keys($needed_ids);
5898 -
5899 - $content_map = [];
5900 - if (!empty($needed_ids)) {
5901 - foreach (array_chunk($needed_ids, 250) as $chunk_ids) {
5902 - $placeholders = implode(',', array_fill(0, count($chunk_ids), '%d'));
5903 - $rows = $wpdb->get_results($wpdb->prepare(
5904 - "SELECT id, article_content FROM {$system_prompt_table} WHERE id IN ($placeholders)",
5905 - ...$chunk_ids
5906 - ));
5907 - foreach ($rows as $r) {
5908 - $content_map[$r->id] = $r->article_content;
5909 - }
5910 - unset($rows);
5911 - }
5912 - }
5913 -
5914 - // Build the all_similarities display array from the top 10
5915 - $all_similarities = [];
5916 - foreach ($top_display as $item) {
5917 - $article_content_for_parse = $content_map[$item['id']] ?? '';
5918 - $parsed_for_display = MxChat_Chunker::parse_stored_chunk($article_content_for_parse);
5919 - $is_chunk = $parsed_for_display['is_chunked'];
5920 - $chunk_meta = $parsed_for_display['metadata'];
5921 -
5922 - if (!empty($item['source_url']) && $item['source_url'] !== '#') {
5923 - $source_display = $item['source_url'];
5924 - } else {
5925 - $content_preview = strip_tags($article_content_for_parse);
5926 - $content_preview = preg_replace('/\s+/', ' ', $content_preview);
5927 - $source_display = substr(trim($content_preview), 0, 50) . '...';
5928 - }
5929 -
5930 - $all_similarities[] = [
5931 - 'document_id' => $item['id'],
5932 - 'similarity' => $item['similarity'],
5933 - 'similarity_percentage' => round($item['similarity'] * 100, 2),
5934 - 'above_threshold' => $item['similarity'] >= $similarity_threshold,
5935 - 'source_display' => $source_display,
5936 - 'content_preview' => substr(strip_tags($parsed_for_display['text'] ?? ''), 0, 100) . '...',
5937 - 'used_for_context' => false,
5938 - 'role_restriction' => $item['role_restriction'],
5939 - 'has_access' => $item['has_access'],
5940 - 'filtered_out' => !$item['has_access'],
5941 - 'is_chunk' => $is_chunk,
5942 - 'chunk_index' => $is_chunk ? ($chunk_meta['chunk_index'] ?? 0) : null,
5943 - 'total_chunks' => $is_chunk ? ($chunk_meta['total_chunks'] ?? 1) : null
5944 - ];
5945 - }
5946 -
5947 - // Build url_groups from candidates for chunk reassembly
5948 - $url_groups = array();
5949 - foreach ($candidates as $cand) {
5950 - $article_content = $content_map[$cand['id']] ?? '';
5951 - $parsed = MxChat_Chunker::parse_stored_chunk($article_content);
5952 - $is_chunked = $parsed['is_chunked'];
5953 - $chunk_index = $parsed['metadata']['chunk_index'] ?? 0;
5954 - $text_content = $parsed['text'];
5955 -
5956 - $source_url = $cand['source_url'];
5957 - $group_key = !empty($source_url) ? $source_url : '_manual_' . $cand['id'];
5958 -
5959 - if (!isset($url_groups[$group_key])) {
5960 - $url_groups[$group_key] = array(
5961 - 'source_url' => $source_url,
5962 - 'best_score' => 0,
5963 - 'is_chunked' => $is_chunked,
5964 - 'chunks' => array(),
5965 - 'single_text' => '',
5966 - 'single_id' => null
5967 - );
5968 - }
5969 -
5970 - if ($cand['similarity'] > $url_groups[$group_key]['best_score']) {
5971 - $url_groups[$group_key]['best_score'] = $cand['similarity'];
5972 - }
5973 -
5974 - if ($is_chunked) {
5975 - $url_groups[$group_key]['is_chunked'] = true;
5976 - $url_groups[$group_key]['chunks'][] = array(
5977 - 'id' => $cand['id'],
5978 - 'score' => $cand['similarity'],
5979 - 'chunk_index' => $chunk_index,
5980 - 'text' => $text_content
5981 - );
5982 - } else {
5983 - $url_groups[$group_key]['single_text'] = $text_content;
5984 - $url_groups[$group_key]['single_id'] = $cand['id'];
5985 - }
5986 - }
5987 -
5988 - // Sort ALL similarities for testing display (highest first)
5989 - usort($all_similarities, function ($a, $b) {
5990 - return $b['similarity'] <=> $a['similarity'];
5991 - });
5992 -
5993 - // Sort URL groups by best score (highest first)
5994 - uasort($url_groups, function($a, $b) {
5995 - return $b['best_score'] <=> $a['best_score'];
5996 - });
5997 -
5998 - // Get RAG sources limit from options (default 6, min 3, max 10)
5999 - $rag_sources_limit = isset($current_options['rag_sources_limit']) ? intval($current_options['rag_sources_limit']) : 3;
6000 - if ($rag_sources_limit < 3) $rag_sources_limit = 3;
6001 - if ($rag_sources_limit > 10) $rag_sources_limit = 10;
6002 -
6003 - // Take top N unique URLs based on user setting
6004 - $top_urls = array_slice($url_groups, 0, $rag_sources_limit, true);
6005 -
6006 - // Track which document IDs are used for context
6007 - $used_document_ids = [];
6008 - foreach ($top_urls as $group) {
6009 - if ($group['is_chunked']) {
6010 - foreach ($group['chunks'] as $chunk) {
6011 - $used_document_ids[] = $chunk['id'];
6012 - }
6013 - } elseif ($group['single_id']) {
6014 - $used_document_ids[] = $group['single_id'];
6015 - }
6016 - }
6017 -
6018 - // Update the all_similarities array to mark which were actually used
6019 - foreach ($all_similarities as &$similarity_item) {
6020 - $similarity_item['used_for_context'] = in_array($similarity_item['document_id'], $used_document_ids);
6021 - }
6022 -
6023 - // Store top 10 for testing panel
6024 - $this->last_similarity_analysis['top_matches'] = array_slice($all_similarities, 0, 10);
6025 - $this->last_similarity_analysis['total_checked'] = $total_checked;
6026 -
6027 - // Initialize final content
6028 - $content = '';
6029 - $matches_used = 0;
6030 - $total_chunks_used = 0;
6031 - $max_total_chunks = isset($current_options['rag_chunks_limit']) ? intval($current_options['rag_chunks_limit']) : 15;
6032 - if ($max_total_chunks < 8) $max_total_chunks = 8;
6033 - if ($max_total_chunks > 20) $max_total_chunks = 20;
6034 - $max_chunks_per_source = 5; // Cap per individual source to limit token usage
6035 -
6036 - // Check if citation links are enabled (default to 'on' for backwards compatibility)
6037 - // Use fresh options to ensure we get the latest setting value
6038 - $fresh_options = get_option('mxchat_options', []);
6039 - $citation_links_enabled = isset($fresh_options['citation_links_toggle']) ? ($fresh_options['citation_links_toggle'] === 'on') : true;
6040 -
6041 - // Build content from top sources
6042 - foreach ($top_urls as $group_key => $group) {
6043 - $source_url = $group['source_url']; // Use actual source_url, not the group key
6044 -
6045 - // Stop if we've hit the total chunk limit
6046 - if ($total_chunks_used >= $max_total_chunks) {
6047 - break;
6048 - }
6049 -
6050 - $full_text = '';
6051 - $chunks_in_this_source = 1; // Default for non-chunked content
6052 -
6053 - if ($group['is_chunked']) {
6054 - // Calculate how many chunks we can still use (respect both total and per-source caps)
6055 - $chunks_remaining = min($max_chunks_per_source, $max_total_chunks - $total_chunks_used);
6056 -
6057 - // Fetch chunks for this URL with limit
6058 - $full_text = $this->reassemble_chunks_from_wordpress($source_url, $chunks_remaining, $chunks_in_this_source);
6059 -
6060 - // If fetching all chunks fails, fall back to matched chunks
6061 - if (empty($full_text)) {
6062 - // Sort matched chunks by index and concatenate
6063 - usort($group['chunks'], function($a, $b) {
6064 - return $a['chunk_index'] <=> $b['chunk_index'];
6065 - });
6066 -
6067 - $chunk_texts = array();
6068 - $chunks_in_this_source = 0;
6069 - foreach ($group['chunks'] as $chunk) {
6070 - if ($total_chunks_used + $chunks_in_this_source >= $max_total_chunks) {
6071 - break;
6072 - }
6073 - $chunk_texts[] = $chunk['text'];
6074 - $chunks_in_this_source++;
6075 - }
6076 - $full_text = implode("\n\n", $chunk_texts);
6077 - }
6078 - } else {
6079 - $full_text = $group['single_text'];
6080 - $chunks_in_this_source = 1;
6081 - }
6082 -
6083 - if (!empty($full_text)) {
6084 - // Strip URLs from content if citation links are disabled
6085 - if (!$citation_links_enabled) {
6086 - $full_text = preg_replace('#\bhttps?://[^\s<>"\']+#i', '', $full_text);
6087 - $full_text = preg_replace('/\s+/', ' ', trim($full_text)); // Clean up extra spaces
6088 - }
6089 -
6090 - // Use numbered reference for URL-based entries, plain info label for manual entries
6091 - // Manual entries are stored with an internal mxchat:// placeholder URL — never expose them as citations
6092 - if (!empty($source_url) && $source_url !== '#' && strpos($source_url, 'mxchat://') !== 0) {
6093 - $matches_used++;
6094 - $content .= "## Reference " . $matches_used . " ##\n";
6095 - $content .= $full_text . "\n\n";
6096 -
6097 - // Only include citation URLs if citation links are enabled
6098 - if ($citation_links_enabled) {
6099 - $valid_urls[] = $source_url;
6100 - $content .= "URL: " . $source_url . "\n\n";
6101 - }
6102 -
6103 - // Video-backed source → queue the consent-safe embed (03ba33)
6104 - $this->maybe_queue_youtube_embed($source_url, $full_text);
6105 - } else {
6106 - // Manual entry — no reference number, no citation
6107 - $content .= "## Information ##\n";
6108 - $content .= $full_text . "\n\n";
6109 - }
6110 -
6111 - // Extract any URLs from the text content itself (only if citation links enabled)
6112 - if ($citation_links_enabled) {
6113 - preg_match_all(
6114 - '#\bhttps?://[^\s<>"\']+#i',
6115 - $full_text,
6116 - $content_urls
6117 - );
6118 - if (!empty($content_urls[0])) {
6119 - $valid_urls = array_merge($valid_urls, $content_urls[0]);
6120 - }
6121 - }
6122 -
6123 - $total_chunks_used += $chunks_in_this_source;
6124 - }
6125 - }
6126 -
6127 - // NEW: Store unique valid URLs for validation
6128 - $this->current_valid_urls = array_unique($valid_urls);
6129 -
6130 - // Store sources and chunks counts for testing/transcript display
6131 - $this->last_similarity_analysis['sources_used'] = $matches_used;
6132 - $this->last_similarity_analysis['total_chunks_used'] = $total_chunks_used;
6133 -
6134 - // Allow add-ons to act on similarity results (e.g. WooCommerce product card display)
6135 - do_action('mxchat_similarity_results', $this->last_similarity_analysis['top_matches'], $bot_id);
6136 -
6137 - // Add response guidelines
6138 - if (empty($top_urls)) {
6139 - $content = "No reference information was found for this query.\n\n";
6140 - } else {
6141 - // Build response guidelines based on citation links setting
6142 - $content .= "\n## Response Guidelines ##\n" .
6143 - "You are an AI Chatbot. Answer naturally and helpfully using only the information from the references above. " .
6144 - "Be conversational and friendly, but never mention your knowledge base or training data. " .
6145 - "If you don't have specific information or are uncertain about any details, it's always " .
6146 - "better to honestly say you don't know rather than making up or guessing at answers. " .
6147 - "When information is incomplete, let them know you are unsure.\n\n";
6148 -
6149 - // Only add hyperlink instructions if citation links are enabled
6150 - if ($citation_links_enabled) {
6151 - $content .= "CRITICAL: When creating hyperlinks, always use proper markdown format with descriptive text: " .
6152 - "[descriptive text](url). NEVER use empty brackets like [](url). The text in brackets must describe what the link is about. " .
6153 - "Only cite references that have a URL. Do not cite or add source labels to Information sections that have no URL.";
6154 - } else {
6155 - $content .= "IMPORTANT: Do not include any citation links, source URLs, or hyperlinks in your responses. " .
6156 - "Simply provide helpful answers based on the reference information without citing sources.";
6157 - }
6158 - }
6159 -
6160 - return trim($content);
6161 -}
6162 -
6163 -/**
6164 - * plan-mxchat-20260717-03ba33 — if a KB source used for context is a single
6165 - * YouTube video, queue ONE consent-safe embed for the response html channel.
6166 - * Called from BOTH retrieval builders (WordPress DB + Pinecone) inside their
6167 - * real-URL winner branch, in ranked order — so the first (best) video wins and
6168 - * later matches are ignored. Only KB/admin-ingested sources ever reach this
6169 - * point; a URL a visitor pastes in chat never does.
6170 - */
6171 -private function maybe_queue_youtube_embed($source_url, $full_text) {
6172 - if (!empty($this->videoEmbedHtml)) {
6173 - return; // one video per response
6174 - }
6175 - $video_id = MxChat_Utils::parse_youtube_id($source_url);
6176 - if (empty($video_id)) {
6177 - return;
6178 - }
6179 - // Ingestion writes "YouTube Video: {title}" / "Channel: {name}" / "URL: …"
6180 - // header lines into the indexed text. NOTE: when citation links are
6181 - // disabled the winner loop collapses ALL whitespace to single spaces
6182 - // before this runs, so the title must be terminated by the next header
6183 - // label, not by end-of-line. Fall back to a generic label when absent
6184 - // (e.g. a YouTube watch page imported through the plain URL source).
6185 - $title = '';
6186 - if (preg_match('/YouTube Video:\s*(.+?)(?=\s+Channel:\s|\s+URL:\s|\r|\n|$)/i', (string) $full_text, $m)) {
6187 - $title = trim(mb_substr(trim($m[1]), 0, 140));
6188 - if (preg_match('#^https?://#i', $title)) {
6189 - $title = ''; // header carried the URL, not a real title
6190 - }
6191 - }
6192 - $this->videoEmbedHtml = $this->build_youtube_embed_html($video_id, $title, $source_url);
6193 -}
6194 -
6195 -/**
6196 - * Consent-safe click-to-load YouTube facade. No Google iframe is created until
6197 - * the visitor taps play (chat-script.js swaps the facade for a
6198 - * youtube-nocookie.com iframe). The caption always carries a plain "Watch on
6199 - * YouTube" link, which is also the graceful degrade on strict-CSP sites where
6200 - * third-party frames are blocked.
6201 - */
6202 -private function build_youtube_embed_html($video_id, $title, $watch_url) {
6203 - $video_id = preg_replace('/[^A-Za-z0-9_-]/', '', (string) $video_id);
6204 - if ($video_id === '') {
6205 - return '';
6206 - }
6207 - $thumb = 'https://i.ytimg.com/vi/' . $video_id . '/hqdefault.jpg';
6208 - $label = ($title !== '') ? $title : __('YouTube video', 'mxchat');
6209 -
6210 - $html = '<div class="mxchat-youtube-embed" data-video-id="' . esc_attr($video_id) . '">';
6211 - $html .= '<button type="button" class="mxchat-youtube-facade" aria-label="' . esc_attr(sprintf(__('Play video: %s', 'mxchat'), $label)) . '">';
6212 - $html .= '<img class="mxchat-youtube-thumb" src="' . esc_url($thumb) . '" alt="' . esc_attr($label) . '" loading="lazy" />';
6213 - $html .= '<span class="mxchat-youtube-play" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg></span>';
6214 - $html .= '</button>';
6215 - $html .= '<div class="mxchat-youtube-caption">';
6216 - $html .= '<span class="mxchat-youtube-title">' . esc_html($label) . '</span>';
6217 - $html .= '<a class="mxchat-youtube-link" href="' . esc_url($watch_url) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Watch on YouTube', 'mxchat') . '</a>';
6218 - $html .= '</div>';
6219 - $html .= '</div>';
6220 - return $html;
6221 -}
6222 -
6223 -/**
6224 - * Fetch and reassemble chunks for a URL from WordPress database
6225 - *
6226 - * @param string $source_url The source URL to fetch chunks for
6227 - * @param int $max_chunks Maximum number of chunks to return (0 = unlimited)
6228 - * @param int &$chunk_count Reference to store the actual number of chunks returned
6229 - * @return string Reassembled content from chunks
6230 - */
6231 -private function reassemble_chunks_from_wordpress($source_url, $max_chunks = 0, &$chunk_count = 0) {
6232 - global $wpdb;
6233 - $table = $wpdb->prefix . 'mxchat_system_prompt_content';
6234 -
6235 - // Fetch all rows with this source_url
6236 - $rows = $wpdb->get_results($wpdb->prepare(
6237 - "SELECT article_content FROM {$table}
6238 - WHERE source_url = %s
6239 - ORDER BY id ASC",
6240 - $source_url
6241 - ));
6242 -
6243 - if (empty($rows)) {
6244 - $chunk_count = 0;
6245 - return '';
6246 - }
6247 -
6248 - // Parse and sort chunks by index
6249 - $chunks = array();
6250 - foreach ($rows as $row) {
6251 - $parsed = MxChat_Chunker::parse_stored_chunk($row->article_content);
6252 -
6253 - if ($parsed['is_chunked']) {
6254 - $chunk_index = $parsed['metadata']['chunk_index'] ?? 0;
6255 - $chunks[$chunk_index] = $parsed['text'];
6256 - } else {
6257 - // Non-chunked content - just return it
6258 - $chunks[] = $parsed['text'];
6259 - }
6260 - }
6261 -
6262 - // Sort by chunk index
6263 - ksort($chunks);
6264 -
6265 - // Apply chunk limit if specified
6266 - if ($max_chunks > 0 && count($chunks) > $max_chunks) {
6267 - $chunks = array_slice($chunks, 0, $max_chunks, true);
6268 - }
6269 -
6270 - // Store actual chunk count
6271 - $chunk_count = count($chunks);
6272 -
6273 - // Reassemble content
6274 - return implode("\n\n", $chunks);
6275 -}
6276 -
6277 -private function find_relevant_content_pinecone($user_embedding, $bot_id = 'default', $bot_config = null) {
6278 - global $wpdb;
6279 -
6280 - //error_log("MXCHAT DEBUG: find_relevant_content_pinecone called");
6281 - //error_log(" - bot_id: " . $bot_id);
6282 - //error_log(" - user_embedding is array: " . (is_array($user_embedding) ? 'yes' : 'no'));
6283 - //error_log(" - user_embedding count: " . (is_array($user_embedding) ? count($user_embedding) : 'N/A'));
6284 -
6285 - // Use bot-specific config or fall back to default
6286 - if ($bot_config === null) {
6287 - $bot_config = $this->get_bot_pinecone_config($bot_id);
6288 - }
6289 -
6290 - $api_key = $bot_config['api_key'] ?? '';
6291 - $host = $bot_config['host'] ?? '';
6292 - $namespace = $bot_config['namespace'] ?? '';
6293 -
6294 - //error_log("MXCHAT DEBUG: Pinecone query parameters:");
6295 - //error_log(" - API Key: " . (empty($api_key) ? 'EMPTY - ERROR!' : 'Present (length: ' . strlen($api_key) . ')'));
6296 - //error_log(" - Host: " . (empty($host) ? 'EMPTY - ERROR!' : $host));
6297 - //error_log(" - Namespace: " . (empty($namespace) ? 'EMPTY (will use default)' : $namespace));
6298 -
6299 - // Initialize similarity analysis storage
6300 - $this->last_similarity_analysis = [
6301 - 'knowledge_base_type' => 'Pinecone',
6302 - 'bot_id' => $bot_id,
6303 - 'namespace' => $namespace,
6304 - 'top_matches' => [],
6305 - 'threshold_used' => 0,
6306 - 'total_checked' => 0
6307 - ];
6308 -
6309 - // NEW: Initialize valid URLs array
6310 - $valid_urls = [];
6311 -
6312 - if (empty($host) || empty($api_key)) {
6313 - //error_log("MXCHAT DEBUG ERROR: Missing Pinecone host or API key!");
6314 - //error_log(" - Host empty: " . (empty($host) ? 'YES' : 'NO'));
6315 - //error_log(" - API key empty: " . (empty($api_key) ? 'YES' : 'NO'));
6316 - // Store empty array for valid URLs since we can't proceed
6317 - $this->current_valid_urls = [];
6318 - return '';
6319 - }
6320 -
6321 - // Get knowledge manager instance for role checking
6322 - $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
6323 -
6324 - // Get the similarity threshold from the bot options or main options
6325 - $bot_options = $this->get_bot_options($bot_id);
6326 - $current_options = !empty($bot_options) ? $bot_options : get_option('mxchat_options', []);
6327 -
6328 - $similarity_threshold = isset($current_options['similarity_threshold'])
6329 - ? ((int) $current_options['similarity_threshold']) / 100
6330 - : 0.35;
6331 -
6332 - $this->last_similarity_analysis['threshold_used'] = $similarity_threshold;
6333 -
6334 - // Prepare the query request for Pinecone
6335 - $api_endpoint = "https://{$host}/query";
6336 -
6337 - $request_body = array(
6338 - 'vector' => $user_embedding,
6339 - 'topK' => 50, // Increased for chunked content grouping - need more candidates to find top N unique URLs
6340 - 'includeMetadata' => true,
6341 - 'includeValues' => true
6342 - );
6343 -
6344 - // Add namespace if specified for this bot
6345 - if (!empty($namespace)) {
6346 - $request_body['namespace'] = $namespace;
6347 - }
6348 -
6349 - //error_log("MXCHAT DEBUG: About to call Pinecone API");
6350 - //error_log(" - Endpoint: " . $api_endpoint);
6351 - //error_log(" - Namespace in request: " . (!empty($namespace) ? $namespace : 'NOT SET'));
6352 -
6353 - $response = wp_remote_post($api_endpoint, array(
6354 - 'headers' => array(
6355 - 'Api-Key' => $api_key,
6356 - 'accept' => 'application/json',
6357 - 'content-type' => 'application/json'
6358 - ),
6359 - 'body' => wp_json_encode($request_body),
6360 - 'timeout' => 30
6361 - ));
6362 -
6363 - if (is_wp_error($response)) {
6364 - //error_log("MXCHAT DEBUG ERROR: WP Error in Pinecone request: " . $response->get_error_message());
6365 - // Store empty array for valid URLs
6366 - $this->current_valid_urls = [];
6367 - return '';
6368 - }
6369 -
6370 - $response_code = wp_remote_retrieve_response_code($response);
6371 - //error_log("MXCHAT DEBUG: Pinecone response code: " . $response_code);
6372 -
6373 - if ($response_code !== 200) {
6374 - $response_body = wp_remote_retrieve_body($response);
6375 - //error_log("MXCHAT DEBUG ERROR: Pinecone API error response: " . substr($response_body, 0, 500));
6376 - // Store empty array for valid URLs
6377 - $this->current_valid_urls = [];
6378 - return '';
6379 - }
6380 -
6381 - // ADD DETAILED DEBUG SECTION HERE
6382 - $response_body = wp_remote_retrieve_body($response);
6383 - //error_log("MXCHAT DEBUG: Raw Pinecone response length: " . strlen($response_body));
6384 -
6385 - $results = json_decode($response_body, true);
6386 -
6387 - if (json_last_error() !== JSON_ERROR_NONE) {
6388 - //error_log("MXCHAT DEBUG ERROR: JSON decode error: " . json_last_error_msg());
6389 - //error_log("MXCHAT DEBUG: First 500 chars of response: " . substr($response_body, 0, 500));
6390 - // Store empty array for valid URLs
6391 - $this->current_valid_urls = [];
6392 - return '';
6393 - }
6394 -
6395 - //error_log("MXCHAT DEBUG: Pinecone response structure:");
6396 - //error_log(" - Has 'matches' key: " . (isset($results['matches']) ? 'yes' : 'no'));
6397 - //error_log(" - Has 'namespace' key: " . (isset($results['namespace']) ? 'yes (' . $results['namespace'] . ')' : 'no'));
6398 -
6399 - if (empty($results['matches'])) {
6400 - //error_log("MXCHAT DEBUG: No matches found in Pinecone response");
6401 - //error_log("MXCHAT DEBUG: Response keys: " . implode(', ', array_keys($results)));
6402 - // Store empty array for valid URLs
6403 - $this->current_valid_urls = [];
6404 - return '';
6405 - }
6406 -
6407 - //error_log("MXCHAT DEBUG: Found " . count($results['matches']) . " matches in Pinecone");
6408 -
6409 - // Log first match details for debugging
6410 - if (!empty($results['matches'][0])) {
6411 - $first_match = $results['matches'][0];
6412 - //error_log("MXCHAT DEBUG: First match details:");
6413 - //error_log(" - Score: " . ($first_match['score'] ?? 'no score'));
6414 - //error_log(" - Has metadata: " . (isset($first_match['metadata']) ? 'yes' : 'no'));
6415 - if (isset($first_match['metadata'])) {
6416 - //error_log(" - Metadata keys: " . implode(', ', array_keys($first_match['metadata'])));
6417 - }
6418 - }
6419 -
6420 - // Initialize the final content
6421 - $content = '';
6422 - $matches_used = 0;
6423 - $matches_used_for_context = [];
6424 - $total_chunks_used = 0;
6425 - $max_total_chunks = isset($current_options['rag_chunks_limit']) ? intval($current_options['rag_chunks_limit']) : 15;
6426 - if ($max_total_chunks < 8) $max_total_chunks = 8;
6427 - if ($max_total_chunks > 20) $max_total_chunks = 20;
6428 - $max_chunks_per_source = 5; // Cap per individual source to limit token usage
6429 -
6430 - // Check if citation links are enabled (default to 'on' for backwards compatibility)
6431 - // Use fresh options to ensure we get the latest setting value
6432 - $fresh_options = get_option('mxchat_options', []);
6433 - $citation_links_enabled = isset($fresh_options['citation_links_toggle']) ? ($fresh_options['citation_links_toggle'] === 'on') : true;
6434 -
6435 - // NEW CHUNKING LOGIC: Group results by source_url for chunk reassembly
6436 - $url_groups = array();
6437 -
6438 - foreach ($results['matches'] as $index => $match) {
6439 - // Skip if similarity is below threshold
6440 - if ($match['score'] < $similarity_threshold) {
6441 - continue;
6442 - }
6443 -
6444 - $metadata = $match['metadata'] ?? array();
6445 - $source_url = $metadata['source_url'] ?? '';
6446 - $match_id = $match['id'] ?? '';
6447 -
6448 - // LAZY ROLE CHECK: Only check role for content we're actually considering
6449 - $role_restriction = $this->get_single_vector_role($match_id, $metadata);
6450 - $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
6451 -
6452 - // Skip if user doesn't have access
6453 - if (!$has_access) {
6454 - continue;
6455 - }
6456 -
6457 - // Use a unique key for manual entries without a source URL
6458 - $group_key = !empty($source_url) ? $source_url : '_manual_' . $match_id;
6459 -
6460 - // Group by source URL (or unique key for manual entries)
6461 - if (!isset($url_groups[$group_key])) {
6462 - $url_groups[$group_key] = array(
6463 - 'source_url' => $source_url,
6464 - 'best_score' => 0,
6465 - 'is_chunked' => isset($metadata['is_chunked']) && $metadata['is_chunked'],
6466 - 'chunks' => array(),
6467 - 'single_text' => ''
6468 - );
6469 - }
6470 -
6471 - // Track best score for this group
6472 - if ($match['score'] > $url_groups[$group_key]['best_score']) {
6473 - $url_groups[$group_key]['best_score'] = $match['score'];
6474 - }
6475 -
6476 - // Store chunk info or single text
6477 - if ($url_groups[$group_key]['is_chunked']) {
6478 - $url_groups[$group_key]['chunks'][] = array(
6479 - 'id' => $match_id,
6480 - 'score' => $match['score'],
6481 - 'chunk_index' => $metadata['chunk_index'] ?? 0,
6482 - 'text' => $metadata['text'] ?? ''
6483 - );
6484 - } else {
6485 - // Non-chunked content - just store the text
6486 - $url_groups[$group_key]['single_text'] = $metadata['text'] ?? '';
6487 - $url_groups[$group_key]['single_id'] = $match_id;
6488 - }
6489 - }
6490 -
6491 - // Sort URL groups by best score (highest first)
6492 - uasort($url_groups, function($a, $b) {
6493 - return $b['best_score'] <=> $a['best_score'];
6494 - });
6495 -
6496 - // Get RAG sources limit from options (default 6, min 3, max 10)
6497 - $rag_sources_limit = isset($current_options['rag_sources_limit']) ? intval($current_options['rag_sources_limit']) : 3;
6498 - if ($rag_sources_limit < 3) $rag_sources_limit = 3;
6499 - if ($rag_sources_limit > 10) $rag_sources_limit = 10;
6500 -
6501 - // Take top N unique URLs based on user setting
6502 - $top_urls = array_slice($url_groups, 0, $rag_sources_limit, true);
6503 -
6504 - // Track which match IDs are actually used for context
6505 - foreach ($top_urls as $group) {
6506 - if ($group['is_chunked']) {
6507 - foreach ($group['chunks'] as $chunk) {
6508 - $matches_used_for_context[] = $chunk['id'];
6509 - }
6510 - } elseif (!empty($group['single_id'])) {
6511 - $matches_used_for_context[] = $group['single_id'];
6512 - }
6513 - }
6514 -
6515 - // Build content from top sources
6516 - foreach ($top_urls as $group_key => $group) {
6517 - $source_url = $group['source_url']; // Use actual source_url, not the group key
6518 -
6519 - // Stop if we've hit the total chunk limit
6520 - if ($total_chunks_used >= $max_total_chunks) {
6521 - break;
6522 - }
6523 -
6524 - $full_text = '';
6525 - $chunks_in_this_source = 1; // Default for non-chunked content
6526 -
6527 - if ($group['is_chunked']) {
6528 - // Calculate how many chunks we can still use (respect both total and per-source caps)
6529 - $chunks_remaining = min($max_chunks_per_source, $max_total_chunks - $total_chunks_used);
6530 -
6531 - // Fetch chunks for this URL with limit
6532 - $full_text = $this->reassemble_chunks_from_pinecone($source_url, $bot_config, $chunks_remaining, $chunks_in_this_source);
6533 -
6534 - // If fetching all chunks fails, fall back to matched chunks
6535 - if (empty($full_text)) {
6536 - // Sort matched chunks by index and concatenate
6537 - usort($group['chunks'], function($a, $b) {
6538 - return $a['chunk_index'] <=> $b['chunk_index'];
6539 - });
6540 -
6541 - $chunk_texts = array();
6542 - $chunks_in_this_source = 0;
6543 - foreach ($group['chunks'] as $chunk) {
6544 - if ($total_chunks_used + $chunks_in_this_source >= $max_total_chunks) {
6545 - break;
6546 - }
6547 - $chunk_texts[] = $chunk['text'];
6548 - $chunks_in_this_source++;
6549 - }
6550 - $full_text = implode("\n\n", $chunk_texts);
6551 - }
6552 - } else {
6553 - $full_text = $group['single_text'];
6554 - $chunks_in_this_source = 1;
6555 - }
6556 -
6557 - if (!empty($full_text)) {
6558 - // Strip URLs from content if citation links are disabled
6559 - if (!$citation_links_enabled) {
6560 - $full_text = preg_replace('#\bhttps?://[^\s<>"\']+#i', '', $full_text);
6561 - $full_text = preg_replace('/\s+/', ' ', trim($full_text)); // Clean up extra spaces
6562 - }
6563 -
6564 - // Use numbered reference for URL-based entries, plain info label for manual entries
6565 - // Manual entries are stored with an internal mxchat:// placeholder URL — never expose them as citations
6566 - if (!empty($source_url) && $source_url !== '#' && strpos($source_url, 'mxchat://') !== 0) {
6567 - $matches_used++;
6568 - $content .= "## Reference " . $matches_used . " ##\n";
6569 - $content .= $full_text . "\n\n";
6570 -
6571 - // Only include citation URLs if citation links are enabled
6572 - if ($citation_links_enabled) {
6573 - $valid_urls[] = $source_url;
6574 - $content .= "URL: " . $source_url . "\n\n";
6575 - }
6576 -
6577 - // Video-backed source → queue the consent-safe embed (03ba33)
6578 - $this->maybe_queue_youtube_embed($source_url, $full_text);
6579 - } else {
6580 - // Manual entry — no reference number, no citation. Count it as a USED
6581 - // source (plan-mxchat-20260622-c1fe6a): without this, manual/Direct-Content
6582 - // entries (empty or mxchat:// source_url) never increment $matches_used, so
6583 - // the gate below (`if ($matches_used === 0)`) discards manual-only context on
6584 - // the Pinecone backend and the model is told "No reference information was
6585 - // found" — even though the testing panel reports used_for_context:true. It
6586 - // also corrects the cosmetic sources_used:0 the panel/transcript showed. The
6587 - // sibling local/WP-DB builder gates on empty($top_urls), so it never had this
6588 - // bug; this brings Pinecone to parity. Manual entries are still uncited (not
6589 - // added to $valid_urls, no "URL:" line).
6590 - $matches_used++;
6591 - $content .= "## Information ##\n";
6592 - $content .= $full_text . "\n\n";
6593 - }
6594 -
6595 - // Extract any URLs from the text content itself (only if citation links enabled)
6596 - if ($citation_links_enabled) {
6597 - preg_match_all(
6598 - '#\bhttps?://[^\s<>"\']+#i',
6599 - $full_text,
6600 - $content_urls
6601 - );
6602 - if (!empty($content_urls[0])) {
6603 - $valid_urls = array_merge($valid_urls, $content_urls[0]);
6604 - }
6605 - }
6606 -
6607 - $total_chunks_used += $chunks_in_this_source;
6608 - }
6609 - }
6610 -
6611 - // Process ALL matches for testing data (top 10) - with role checking for testing display
6612 - $all_matches = [];
6613 - foreach ($results['matches'] as $index => $match) {
6614 - if ($index >= 10) break; // Limit to top 10 for testing
6615 -
6616 - $match_id = $match['id'] ?? '';
6617 -
6618 - // Check role access for testing display (use cache if available)
6619 - $role_restriction = $this->get_single_vector_role($match_id, $match['metadata']);
6620 - $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
6621 -
6622 - $source_display = '';
6623 - if (!empty($match['metadata']['source_url'])) {
6624 - $source_display = $match['metadata']['source_url'];
6625 - } else {
6626 - $content_preview = strip_tags($match['metadata']['text'] ?? '');
6627 - $content_preview = preg_replace('/\s+/', ' ', $content_preview);
6628 - $source_display = substr(trim($content_preview), 0, 50) . '...';
6629 - }
6630 -
6631 - $match_id_for_display = $match['id'] ?? $index;
6632 -
6633 - // Check for chunk metadata in Pinecone
6634 - $is_chunk = isset($match['metadata']['is_chunked']) && $match['metadata']['is_chunked'];
6635 - $chunk_index = isset($match['metadata']['chunk_index']) ? intval($match['metadata']['chunk_index']) : null;
6636 - $total_chunks = isset($match['metadata']['total_chunks']) ? intval($match['metadata']['total_chunks']) : null;
6637 -
6638 - // Also detect chunk from vector ID pattern: {hash}_chunk_{index}
6639 - if (!$is_chunk && MxChat_Chunker::is_chunk_vector_id($match_id_for_display)) {
6640 - $is_chunk = true;
6641 - }
6642 -
6643 - $all_matches[] = [
6644 - 'document_id' => $match_id_for_display,
6645 - 'similarity' => $match['score'],
6646 - 'similarity_percentage' => round($match['score'] * 100, 2),
6647 - 'above_threshold' => $match['score'] >= $similarity_threshold,
6648 - 'source_display' => $source_display,
6649 - 'content_preview' => substr(strip_tags($match['metadata']['text'] ?? ''), 0, 100) . '...',
6650 - 'used_for_context' => in_array($match_id_for_display, $matches_used_for_context),
6651 - 'role_restriction' => $role_restriction,
6652 - 'has_access' => $has_access,
6653 - 'filtered_out' => !$has_access,
6654 - 'is_chunk' => $is_chunk,
6655 - 'chunk_index' => $chunk_index,
6656 - 'total_chunks' => $total_chunks
6657 - ];
6658 - }
6659 -
6660 - // Store for testing panel
6661 - $this->last_similarity_analysis['top_matches'] = $all_matches;
6662 - $this->last_similarity_analysis['total_checked'] = count($results['matches']);
6663 - $this->last_similarity_analysis['sources_used'] = $matches_used;
6664 - $this->last_similarity_analysis['total_chunks_used'] = $total_chunks_used;
6665 -
6666 - // NEW: Store unique valid URLs for validation
6667 - $this->current_valid_urls = array_unique($valid_urls);
6668 -
6669 - // Allow add-ons to act on similarity results (e.g. WooCommerce product card display)
6670 - do_action('mxchat_similarity_results', $this->last_similarity_analysis['top_matches'], $bot_id);
6671 -
6672 - // Add response guidelines
6673 - if ($matches_used === 0) {
6674 - $content = "No reference information was found for this query.\n\n";
6675 - } else {
6676 - // Build response guidelines based on citation links setting
6677 - $content .= "\n## Response Guidelines ##\n" .
6678 - "You are an AI Chatbot. Answer naturally and helpfully using only the information from the references above. " .
6679 - "Be conversational and friendly, but never mention your knowledge base or training data. " .
6680 - "If you don't have specific information or are uncertain about any details, it's always " .
6681 - "better to honestly say you don't know rather than making up or guessing at answers. " .
6682 - "When information is incomplete, let them know you are unsure.\n\n";
6683 -
6684 - // Only add hyperlink instructions if citation links are enabled
6685 - if ($citation_links_enabled) {
6686 - $content .= "CRITICAL: When creating hyperlinks, always use proper markdown format with descriptive text: " .
6687 - "[descriptive text](url). NEVER use empty brackets like [](url). The text in brackets must describe what the link is about. " .
6688 - "Only cite references that have a URL. Do not cite or add source labels to Information sections that have no URL.";
6689 - } else {
6690 - $content .= "IMPORTANT: Do not include any citation links, source URLs, or hyperlinks in your responses. " .
6691 - "Simply provide helpful answers based on the reference information without citing sources.";
6692 - }
6693 - }
6694 -
6695 - return trim($content);
6696 -}
6697 -
6698 -/**
6699 - * Get role restriction for a single vector (with caching)
6700 - */
6701 -private function get_single_vector_role($vector_id, $metadata = array()) {
6702 - global $wpdb;
6703 -
6704 - if (empty($vector_id)) {
6705 - return 'public';
6706 - }
6707 -
6708 - // Check cache first
6709 - $cache_key = 'mxchat_vector_role_' . $vector_id;
6710 - $cached_role = wp_cache_get($cache_key, 'mxchat_vector_roles');
6711 -
6712 - if ($cached_role !== false) {
6713 - return $cached_role;
6714 - }
6715 -
6716 - $role_restriction = 'public';
6717 -
6718 - // First try Pinecone metadata
6719 - if (!empty($metadata['role_restriction'])) {
6720 - $role_restriction = $metadata['role_restriction'];
6721 - } else {
6722 - // Check WordPress table for user-modified roles
6723 - $roles_table = $wpdb->prefix . 'mxchat_pinecone_roles';
6724 - $stored_role = $wpdb->get_var($wpdb->prepare(
6725 - "SELECT role_restriction FROM {$roles_table} WHERE vector_id = %s",
6726 - $vector_id
6727 - ));
6728 -
6729 - if ($stored_role) {
6730 - $role_restriction = $stored_role;
6731 - }
6732 - }
6733 -
6734 - // Cache individual role for 1 hour
6735 - wp_cache_set($cache_key, $role_restriction, 'mxchat_vector_roles', 3600);
6736 -
6737 - return $role_restriction;
6738 -}
6739 -
6740 -/**
6741 - * Fetch and reassemble all chunks for a URL from Pinecone
6742 - *
6743 - * @param string $source_url The source URL to fetch chunks for
6744 - * @param array $bot_config Bot-specific Pinecone configuration
6745 - * @return string Reassembled content from all chunks
6746 - */
6747 -private function reassemble_chunks_from_pinecone($source_url, $bot_config, $max_chunks = 0, &$chunk_count = 0) {
6748 - $api_key = $bot_config['api_key'] ?? '';
6749 - $host = $bot_config['host'] ?? '';
6750 - $namespace = $bot_config['namespace'] ?? '';
6751 -
6752 - if (empty($host) || empty($api_key)) {
6753 - $chunk_count = 0;
6754 - return '';
6755 - }
6756 -
6757 - $base_hash = md5($source_url);
6758 -
6759 - // Use Pinecone list API to find all chunk vectors with this prefix
6760 - $list_url = "https://{$host}/vectors/list";
6761 -
6762 - // Limit to max_chunks if specified, otherwise fetch up to 100
6763 - $fetch_limit = ($max_chunks > 0 && $max_chunks < 100) ? $max_chunks : 100;
6764 -
6765 - $list_body = array(
6766 - 'prefix' => $base_hash . '_chunk_',
6767 - 'limit' => $fetch_limit
6768 - );
6769 -
6770 - if (!empty($namespace)) {
6771 - $list_body['namespace'] = $namespace;
6772 - }
6773 -
6774 - $list_response = wp_remote_post($list_url, array(
6775 - 'headers' => array(
6776 - 'Api-Key' => $api_key,
6777 - 'accept' => 'application/json',
6778 - 'content-type' => 'application/json'
6779 - ),
6780 - 'body' => wp_json_encode($list_body),
6781 - 'timeout' => 30
6782 - ));
6783 -
6784 - if (is_wp_error($list_response)) {
6785 - //error_log('[MXCHAT-CHUNK] List API error: ' . $list_response->get_error_message());
6786 - return '';
6787 - }
6788 -
6789 - $list_data = json_decode(wp_remote_retrieve_body($list_response), true);
6790 -
6791 - if (empty($list_data['vectors'])) {
6792 - //error_log('[MXCHAT-CHUNK] No chunk vectors found for URL: ' . $source_url);
6793 - return '';
6794 - }
6795 -
6796 - // Extract vector IDs
6797 - $vector_ids = array();
6798 - foreach ($list_data['vectors'] as $vector) {
6799 - if (isset($vector['id'])) {
6800 - $vector_ids[] = $vector['id'];
6801 - }
6802 - }
6803 -
6804 - if (empty($vector_ids)) {
6805 - return '';
6806 - }
6807 -
6808 - // Fetch all chunk content
6809 - $fetch_url = "https://{$host}/vectors/fetch";
6810 -
6811 - $fetch_body = array(
6812 - 'ids' => $vector_ids
6813 - );
6814 -
6815 - if (!empty($namespace)) {
6816 - $fetch_body['namespace'] = $namespace;
6817 - }
6818 -
6819 - $fetch_response = wp_remote_post($fetch_url, array(
6820 - 'headers' => array(
6821 - 'Api-Key' => $api_key,
6822 - 'accept' => 'application/json',
6823 - 'content-type' => 'application/json'
6824 - ),
6825 - 'body' => wp_json_encode($fetch_body),
6826 - 'timeout' => 30
6827 - ));
6828 -
6829 - if (is_wp_error($fetch_response)) {
6830 - //error_log('[MXCHAT-CHUNK] Fetch API error: ' . $fetch_response->get_error_message());
6831 - return '';
6832 - }
6833 -
6834 - $fetch_data = json_decode(wp_remote_retrieve_body($fetch_response), true);
6835 -
6836 - if (empty($fetch_data['vectors'])) {
6837 - return '';
6838 - }
6839 -
6840 - // Sort chunks by index and reassemble
6841 - $chunks = array();
6842 - foreach ($fetch_data['vectors'] as $id => $vector) {
6843 - $metadata = $vector['metadata'] ?? array();
6844 - $chunk_index = $metadata['chunk_index'] ?? 0;
6845 - $text = $metadata['text'] ?? '';
6846 -
6847 - // Store chunk with its index
6848 - $chunks[$chunk_index] = $text;
6849 - }
6850 -
6851 - // Sort by chunk index
6852 - ksort($chunks);
6853 -
6854 - // Apply chunk limit if specified
6855 - if ($max_chunks > 0 && count($chunks) > $max_chunks) {
6856 - $chunks = array_slice($chunks, 0, $max_chunks, true);
6857 - }
6858 -
6859 - // Store actual chunk count
6860 - $chunk_count = count($chunks);
6861 -
6862 - // Reassemble content
6863 - return implode("\n\n", $chunks);
6864 -}
6865 -
6866 -/**
6867 - * Search for relevant content using OpenAI Vector Store (File Search)
6868 - *
6869 - * @param string $user_query The user's query text
6870 - * @param string $bot_id The bot ID
6871 - * @param array $vectorstore_config Vector Store configuration
6872 - * @return string Formatted context string with references
6873 - */
6874 -private function find_relevant_content_openai_vectorstore($user_query, $bot_id = 'default', $vectorstore_config = array()) {
6875 - //error_log("MXCHAT DEBUG: find_relevant_content_openai_vectorstore called");
6876 - //error_log(" - bot_id: " . $bot_id);
6877 - //error_log(" - user_query length: " . strlen($user_query));
6878 -
6879 - // Get OpenAI API key
6880 - $mxchat_options = get_option('mxchat_options', array());
6881 - $api_key = $mxchat_options['api_key'] ?? '';
6882 -
6883 - // Reset vectorstore error tracking
6884 - $this->last_vectorstore_error = null;
6885 -
6886 - if (empty($api_key)) {
6887 - //error_log("MXCHAT DEBUG ERROR: OpenAI API key not configured");
6888 - $this->last_vectorstore_error = 'Vector Store search failed: OpenAI API key is not configured.';
6889 - $this->current_valid_urls = [];
6890 - return '';
6891 - }
6892 -
6893 - // Get Vector Store configuration
6894 - if (empty($vectorstore_config)) {
6895 - $vectorstore_config = $this->get_bot_vectorstore_config($bot_id);
6896 - }
6897 -
6898 - $vectorstore_ids_string = $vectorstore_config['vectorstore_ids'] ?? '';
6899 - $max_results = $vectorstore_config['max_results'] ?? 5;
6900 -
6901 - if (empty($vectorstore_ids_string)) {
6902 - //error_log("MXCHAT DEBUG ERROR: No Vector Store IDs configured");
6903 - $this->last_vectorstore_error = 'Vector Store search failed: No Vector Store IDs are configured for this bot.';
6904 - $this->current_valid_urls = [];
6905 - return '';
6906 - }
6907 -
6908 - // Parse Vector Store IDs
6909 - $vectorstore_ids = array_map('trim', explode(',', $vectorstore_ids_string));
6910 - $vectorstore_ids = array_filter($vectorstore_ids); // Remove empty values
6911 -
6912 - //error_log("MXCHAT DEBUG: Vector Store IDs: " . implode(', ', $vectorstore_ids));
6913 - //error_log("MXCHAT DEBUG: Max results: " . $max_results);
6914 -
6915 - // Initialize similarity analysis storage
6916 - $this->last_similarity_analysis = [
6917 - 'knowledge_base_type' => 'OpenAI Vector Store',
6918 - 'bot_id' => $bot_id,
6919 - 'vectorstore_ids' => $vectorstore_ids,
6920 - 'top_matches' => [],
6921 - 'threshold_used' => 0,
6922 - 'total_checked' => 0
6923 - ];
6924 -
6925 - $valid_urls = [];
6926 -
6927 - // Get the selected model
6928 - $bot_options = $this->get_bot_options($bot_id);
6929 - $current_options = !empty($bot_options) ? $bot_options : $mxchat_options;
6930 - $selected_model = $current_options['model'] ?? 'gpt-5.1-chat-latest';
6931 -
6932 - // Verify it's an OpenAI model
6933 - if (!$this->is_openai_chat_model($selected_model)) {
6934 - //error_log("MXCHAT DEBUG ERROR: Vector Store search requires OpenAI model. Current: " . $selected_model);
6935 - $this->last_vectorstore_error = 'Vector Store search requires an OpenAI model. Current model: ' . $selected_model;
6936 - $this->current_valid_urls = [];
6937 - return '';
6938 - }
6939 -
6940 - // Use OpenAI Responses API with file_search tool
6941 - $request_body = array(
6942 - 'model' => $selected_model,
6943 - 'input' => $user_query,
6944 - 'tools' => array(
6945 - array(
6946 - 'type' => 'file_search',
6947 - 'vector_store_ids' => $vectorstore_ids,
6948 - 'max_num_results' => intval($max_results)
6949 - )
6950 - ),
6951 - 'include' => array('output[*].file_search_call.search_results')
6952 - );
6953 -
6954 - //error_log("MXCHAT VECTORSTORE: ========== REQUEST START ==========");
6955 - //error_log("MXCHAT VECTORSTORE: Model: " . $selected_model);
6956 - //error_log("MXCHAT VECTORSTORE: Query: " . substr($user_query, 0, 200));
6957 - //error_log("MXCHAT VECTORSTORE: Vector Store IDs: " . implode(', ', $vectorstore_ids));
6958 - //error_log("MXCHAT VECTORSTORE: Max Results: " . $max_results);
6959 - //error_log("MXCHAT VECTORSTORE: Request body: " . wp_json_encode($request_body));
6960 -
6961 - $response = wp_remote_post('https://api.openai.com/v1/responses', array(
6962 - 'headers' => array(
6963 - 'Authorization' => 'Bearer ' . $api_key,
6964 - 'Content-Type' => 'application/json'
6965 - ),
6966 - 'body' => wp_json_encode($request_body),
6967 - 'timeout' => 60
6968 - ));
6969 -
6970 - if (is_wp_error($response)) {
6971 - //error_log("MXCHAT VECTORSTORE ERROR: WP Error: " . $response->get_error_message());
6972 - $this->last_vectorstore_error = 'Vector Store API request failed: ' . $response->get_error_message();
6973 - $this->current_valid_urls = [];
6974 - return '';
6975 - }
6976 -
6977 - $response_code = wp_remote_retrieve_response_code($response);
6978 - //error_log("MXCHAT VECTORSTORE: Response code: " . $response_code);
6979 -
6980 - $response_body = wp_remote_retrieve_body($response);
6981 - //error_log("MXCHAT VECTORSTORE: Raw response (first 2000 chars): " . substr($response_body, 0, 2000));
6982 -
6983 - if ($response_code !== 200) {
6984 - //error_log("MXCHAT VECTORSTORE ERROR: API error response: " . $response_body);
6985 - $api_error_detail = '';
6986 - $decoded_error = json_decode($response_body, true);
6987 - if (isset($decoded_error['error']['message'])) {
6988 - $api_error_detail = $decoded_error['error']['message'];
6989 - }
6990 - $this->last_vectorstore_error = 'Vector Store API returned HTTP ' . $response_code . ($api_error_detail ? ': ' . $api_error_detail : '');
6991 - $this->current_valid_urls = [];
6992 - return '';
6993 - }
6994 - $result = json_decode($response_body, true);
6995 -
6996 - if (json_last_error() !== JSON_ERROR_NONE) {
6997 - //error_log("MXCHAT VECTORSTORE ERROR: JSON decode error: " . json_last_error_msg());
6998 - $this->last_vectorstore_error = 'Vector Store response could not be parsed: ' . json_last_error_msg();
6999 - $this->current_valid_urls = [];
7000 - return '';
7001 - }
7002 -
7003 - // Debug: Log the structure of the result
7004 - //error_log("MXCHAT VECTORSTORE: Result keys: " . implode(', ', array_keys($result)));
7005 - if (isset($result['output'])) {
7006 - //error_log("MXCHAT VECTORSTORE: Output count: " . count($result['output']));
7007 - foreach ($result['output'] as $idx => $out) {
7008 - //error_log("MXCHAT VECTORSTORE: Output[$idx] type: " . ($out['type'] ?? 'unknown'));
7009 - //error_log("MXCHAT VECTORSTORE: Output[$idx] keys: " . implode(', ', array_keys($out)));
7010 - }
7011 - } else {
7012 - //error_log("MXCHAT VECTORSTORE: No 'output' key in result!");
7013 - }
7014 -
7015 - // Extract file search results from the response
7016 - $content = '';
7017 - $matches_used = 0;
7018 - $all_matches = [];
7019 -
7020 - // The Responses API returns output array with tool results
7021 - if (isset($result['output']) && is_array($result['output'])) {
7022 - foreach ($result['output'] as $output_item) {
7023 - // Look for file_search_call results
7024 - if (isset($output_item['type']) && $output_item['type'] === 'file_search_call') {
7025 - //error_log("MXCHAT VECTORSTORE: Found file_search_call output item");
7026 - //error_log("MXCHAT VECTORSTORE: file_search_call keys: " . implode(', ', array_keys($output_item)));
7027 -
7028 - // Check for search_results in the output item directly
7029 - $search_results = $output_item['search_results'] ?? $output_item['results'] ?? [];
7030 - //error_log("MXCHAT VECTORSTORE: Search results count: " . count($search_results));
7031 -
7032 - if (empty($search_results)) {
7033 - //error_log("MXCHAT VECTORSTORE: No search results found in file_search_call");
7034 - //error_log("MXCHAT VECTORSTORE: file_search_call content: " . wp_json_encode($output_item));
7035 - }
7036 -
7037 - foreach ($search_results as $index => $search_result) {
7038 - $filename = $search_result['filename'] ?? '';
7039 - $score = $search_result['score'] ?? 0;
7040 - $text_content = '';
7041 -
7042 - // Extract text content from the result
7043 - // The text can be directly on the result OR nested under content array
7044 - if (isset($search_result['text']) && !empty($search_result['text'])) {
7045 - // Direct text field (OpenAI's actual format)
7046 - $text_content = $search_result['text'];
7047 - //error_log("MXCHAT VECTORSTORE: Found text directly on result[$index], length: " . strlen($text_content));
7048 - } elseif (isset($search_result['content']) && is_array($search_result['content'])) {
7049 - // Nested content array format
7050 - foreach ($search_result['content'] as $content_item) {
7051 - if (isset($content_item['text'])) {
7052 - $text_content .= $content_item['text'] . "\n";
7053 - }
7054 - }
7055 - //error_log("MXCHAT VECTORSTORE: Found text in content array for result[$index], length: " . strlen($text_content));
7056 - } else {
7057 - //error_log("MXCHAT VECTORSTORE: No text found for result[$index]. Keys: " . implode(', ', array_keys($search_result)));
7058 - }
7059 -
7060 - if (!empty($text_content)) {
7061 - $content .= "## Reference " . ($matches_used + 1) . " ##\n";
7062 - $content .= trim($text_content) . "\n\n";
7063 -
7064 - if (!empty($filename)) {
7065 - $content .= "Source: " . $filename . "\n\n";
7066 - }
7067 -
7068 - // Extract URLs from content
7069 - preg_match_all(
7070 - '#\bhttps?://[^\s<>"\']+#i',
7071 - $text_content,
7072 - $content_urls
7073 - );
7074 - if (!empty($content_urls[0])) {
7075 - $valid_urls = array_merge($valid_urls, $content_urls[0]);
7076 - }
7077 -
7078 - $matches_used++;
7079 - }
7080 -
7081 - // Store for similarity analysis
7082 - $all_matches[] = [
7083 - 'document_id' => $filename ?: ('result_' . $index),
7084 - 'similarity' => $score,
7085 - 'similarity_percentage' => round($score * 100, 2),
7086 - 'above_threshold' => true,
7087 - 'source_display' => $filename,
7088 - 'content_preview' => substr(strip_tags($text_content), 0, 100) . '...',
7089 - 'used_for_context' => true,
7090 - 'role_restriction' => 'public',
7091 - 'has_access' => true,
7092 - 'filtered_out' => false
7093 - ];
7094 - }
7095 - }
7096 -
7097 - // Also check for message content with annotations (citations)
7098 - if (isset($output_item['type']) && $output_item['type'] === 'message') {
7099 - if (isset($output_item['content']) && is_array($output_item['content'])) {
7100 - foreach ($output_item['content'] as $content_block) {
7101 - if (isset($content_block['annotations']) && is_array($content_block['annotations'])) {
7102 - foreach ($content_block['annotations'] as $annotation) {
7103 - if (isset($annotation['filename'])) {
7104 - $filename = $annotation['filename'];
7105 - $score = $annotation['score'] ?? 0;
7106 - $text_content = '';
7107 -
7108 - if (isset($annotation['content']) && is_array($annotation['content'])) {
7109 - foreach ($annotation['content'] as $ann_content) {
7110 - if (isset($ann_content['text'])) {
7111 - $text_content .= $ann_content['text'] . "\n";
7112 - }
7113 - }
7114 - }
7115 -
7116 - if (!empty($text_content) && $matches_used < $max_results) {
7117 - $content .= "## Reference " . ($matches_used + 1) . " ##\n";
7118 - $content .= trim($text_content) . "\n\n";
7119 - $content .= "Source: " . $filename . "\n\n";
7120 -
7121 - preg_match_all(
7122 - '#\bhttps?://[^\s<>"\']+#i',
7123 - $text_content,
7124 - $content_urls
7125 - );
7126 - if (!empty($content_urls[0])) {
7127 - $valid_urls = array_merge($valid_urls, $content_urls[0]);
7128 - }
7129 -
7130 - $matches_used++;
7131 -
7132 - $all_matches[] = [
7133 - 'document_id' => $filename,
7134 - 'similarity' => $score,
7135 - 'similarity_percentage' => round($score * 100, 2),
7136 - 'above_threshold' => true,
7137 - 'source_display' => $filename,
7138 - 'content_preview' => substr(strip_tags($text_content), 0, 100) . '...',
7139 - 'used_for_context' => true,
7140 - 'role_restriction' => 'public',
7141 - 'has_access' => true,
7142 - 'filtered_out' => false
7143 - ];
7144 - }
7145 - }
7146 - }
7147 - }
7148 - }
7149 - }
7150 - }
7151 - }
7152 - }
7153 -
7154 - // Store for testing panel
7155 - $this->last_similarity_analysis['top_matches'] = $all_matches;
7156 - $this->last_similarity_analysis['total_checked'] = count($all_matches);
7157 -
7158 - // Store unique valid URLs for validation
7159 - $this->current_valid_urls = array_unique($valid_urls);
7160 -
7161 - // Allow add-ons to act on similarity results (e.g. WooCommerce product card display)
7162 - do_action('mxchat_similarity_results', $this->last_similarity_analysis['top_matches'], $bot_id);
7163 -
7164 - //error_log("MXCHAT VECTORSTORE: ========== SEARCH COMPLETE ==========");
7165 - //error_log("MXCHAT VECTORSTORE: Matches used: " . $matches_used);
7166 - //error_log("MXCHAT VECTORSTORE: All matches count: " . count($all_matches));
7167 - //error_log("MXCHAT VECTORSTORE: Content length: " . strlen($content));
7168 - if ($matches_used > 0) {
7169 - //error_log("MXCHAT VECTORSTORE: Content preview: " . substr($content, 0, 500));
7170 - }
7171 -
7172 - // Check if citation links are enabled
7173 - $citation_links_enabled = ($mxchat_options['citation_links_toggle'] ?? 'on') === 'on';
7174 -
7175 - // Add response guidelines
7176 - if ($matches_used === 0) {
7177 - //error_log("MXCHAT VECTORSTORE: No matches found - returning empty reference message");
7178 - $content = "No reference information was found for this query.\n\n";
7179 - } else {
7180 - // Build response guidelines based on citation links setting
7181 - $content .= "\n## Response Guidelines ##\n" .
7182 - "You are an AI Chatbot. Answer naturally and helpfully using only the information from the references above. " .
7183 - "Be conversational and friendly, but never mention your knowledge base or training data. " .
7184 - "If you don't have specific information or are uncertain about any details, it's always " .
7185 - "better to honestly say you don't know rather than making up or guessing at answers. " .
7186 - "When information is incomplete, let them know you are unsure.\n\n";
7187 -
7188 - // Only add hyperlink instructions if citation links are enabled
7189 - if ($citation_links_enabled) {
7190 - $content .= "CRITICAL: When creating hyperlinks, always use proper markdown format with descriptive text: " .
7191 - "[descriptive text](url). NEVER use empty brackets like [](url). The text in brackets must describe what the link is about.";
7192 - } else {
7193 - $content .= "IMPORTANT: Do not include any citation links, source URLs, or hyperlinks in your responses. " .
7194 - "Simply provide helpful answers based on the reference information without citing sources.";
7195 - }
7196 - }
7197 -
7198 - //error_log("MXCHAT DEBUG: Vector Store search complete. Matches used: " . $matches_used);
7199 -
7200 - return trim($content);
7201 -}
7202 -
7203 -/**
7204 - * Check if the given model is an OpenAI chat model
7205 - *
7206 - * @param string $model The model ID
7207 - * @return bool True if it's an OpenAI model
7208 - */
7209 -private function is_openai_chat_model($model) {
7210 - $openai_prefixes = array('gpt-', 'o1-', 'o3-');
7211 - foreach ($openai_prefixes as $prefix) {
7212 - if (strpos($model, $prefix) === 0) {
7213 - return true;
7214 - }
7215 - }
7216 - return false;
7217 -}
7218 -
7219 -/**
7220 - * Get bot-specific Vector Store configuration
7221 - *
7222 - * @param string $bot_id The bot ID
7223 - * @return array Configuration array
7224 - */
7225 -private function get_bot_vectorstore_config($bot_id = 'default') {
7226 - // Admin Testing tab bot → resolve the DEFAULT bot's backend (see
7227 - // get_bot_pinecone_config). This getter already passes the real default
7228 - // config into the filter, so it was not broken — normalized anyway so the
7229 - // Testing bot can never drift from the front-end default.
7230 - if ($bot_id === 'testing') {
7231 - $bot_id = 'default';
7232 - }
7233 -
7234 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
7235 -
7236 - // Default global settings
7237 - $default_config = array(
7238 - 'use_vectorstore' => ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') === '1',
7239 - 'vectorstore_ids' => $vectorstore_options['mxchat_vectorstore_ids'] ?? '',
7240 - 'max_results' => $vectorstore_options['mxchat_vectorstore_max_results'] ?? 5
7241 - );
7242 -
7243 - // Allow multi-bot plugin to override with bot-specific settings
7244 - $bot_config = apply_filters('mxchat_get_bot_vectorstore_config', $default_config, $bot_id);
7245 -
7246 - // Preserve max_results from global settings if not set in bot config
7247 - if (!isset($bot_config['max_results'])) {
7248 - $bot_config['max_results'] = $default_config['max_results'];
7249 - }
7250 -
7251 - return $bot_config;
7252 -}
7253 -
7254 -private function mxchat_find_relevant_products($user_embedding) {
7255 - //error_log('MXChat Vector Search: Starting product search...');
7256 -
7257 - // Retrieve the add-on settings from the database
7258 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
7259 -
7260 - // Determine whether Pinecone is enabled
7261 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
7262 -
7263 - //error_log('Pinecone enabled flag: ' . $use_pinecone);
7264 -
7265 - if ($use_pinecone === 1) {
7266 - //error_log('MXChat Vector Search: Using Pinecone database for products');
7267 - return $this->find_relevant_products_pinecone($user_embedding);
7268 - } else {
7269 - //error_log('MXChat Vector Search: Using WordPress database for products');
7270 - return $this->find_relevant_products_wordpress($user_embedding);
7271 - }
7272 -}
7273 -private function find_relevant_products_wordpress($user_embedding) {
7274 - global $wpdb;
7275 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
7276 -
7277 - if (!is_array($user_embedding)) {
7278 - return '';
7279 - }
7280 -
7281 - // Streaming top-K pass: scan rows in small batches, keep only the top 3
7282 - // results above the similarity threshold. Peak memory is bounded by
7283 - // $batch_size embedding rows plus a 3-element top list.
7284 - $batch_size = 250;
7285 - $similarity_threshold = 0.85;
7286 - $top_k = 3;
7287 - $top_results = [];
7288 - $offset = 0;
7289 -
7290 - do {
7291 - $batch = $wpdb->get_results($wpdb->prepare(
7292 - "SELECT id, embedding_vector
7293 - FROM {$system_prompt_table}
7294 - LIMIT %d OFFSET %d",
7295 - $batch_size,
7296 - $offset
7297 - ));
7298 -
7299 - if (empty($batch)) {
7300 - break;
7301 - }
7302 -
7303 - foreach ($batch as $row) {
7304 - $database_embedding = $row->embedding_vector
7305 - ? unserialize($row->embedding_vector, ['allowed_classes' => false])
7306 - : null;
7307 -
7308 - if (!is_array($database_embedding)) {
7309 - unset($database_embedding);
7310 - continue;
7311 - }
7312 -
7313 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
7314 - unset($database_embedding);
7315 -
7316 - if ($similarity < $similarity_threshold) {
7317 - continue;
7318 - }
7319 -
7320 - // Insert into bounded top-K (kept sorted descending)
7321 - if (count($top_results) < $top_k) {
7322 - $top_results[] = ['id' => $row->id, 'similarity' => $similarity];
7323 - usort($top_results, function ($a, $b) {
7324 - return $b['similarity'] <=> $a['similarity'];
7325 - });
7326 - } elseif ($similarity > $top_results[$top_k - 1]['similarity']) {
7327 - $top_results[$top_k - 1] = ['id' => $row->id, 'similarity' => $similarity];
7328 - usort($top_results, function ($a, $b) {
7329 - return $b['similarity'] <=> $a['similarity'];
7330 - });
7331 - }
7332 - }
7333 -
7334 - unset($batch);
7335 - $offset += $batch_size;
7336 - } while (true);
7337 -
7338 - if (empty($top_results)) {
7339 - return '';
7340 - }
7341 -
7342 - $content = '';
7343 - foreach ($top_results as $result) {
7344 - $chunk_content = $this->fetch_content_with_product_links($result['id']);
7345 - $content .= $chunk_content . "\n\n";
7346 - }
7347 -
7348 - return trim($content);
7349 -}
7350 -
7351 -
7352 -private function find_relevant_products_pinecone($user_embedding) {
7353 - //error_log('Starting Pinecone product search...');
7354 -
7355 - $options = get_option('mxchat_pinecone_addon_options', array());
7356 - $api_key = $options['mxchat_pinecone_api_key'] ?? '';
7357 - $host = $options['mxchat_pinecone_host'] ?? '';
7358 -
7359 - if (empty($host) || empty($api_key)) {
7360 - //error_log('Pinecone credentials not properly configured for product search');
7361 - return '';
7362 - }
7363 -
7364 - $similarity_threshold = 0.85;
7365 - $api_endpoint = "https://{$host}/query";
7366 -
7367 - $request_body = array(
7368 - 'vector' => $user_embedding,
7369 - 'topK' => 5,
7370 - 'includeMetadata' => true,
7371 - 'includeValues' => true,
7372 - 'filter' => array(
7373 - 'type' => 'product'
7374 - )
7375 - );
7376 -
7377 - //error_log('Sending request to Pinecone with body: ' . wp_json_encode($request_body));
7378 -
7379 - $response = wp_remote_post($api_endpoint, array(
7380 - 'headers' => array(
7381 - 'Api-Key' => $api_key,
7382 - 'accept' => 'application/json',
7383 - 'content-type' => 'application/json'
7384 - ),
7385 - 'body' => wp_json_encode($request_body),
7386 - 'timeout' => 30
7387 - ));
7388 -
7389 - if (is_wp_error($response)) {
7390 - //error_log('Pinecone product query error: ' . $response->get_error_message());
7391 - return '';
7392 - }
7393 -
7394 - $response_code = wp_remote_retrieve_response_code($response);
7395 - //error_log('Pinecone response code: ' . $response_code);
7396 -
7397 - if ($response_code !== 200) {
7398 - //error_log('Pinecone API error during product search: ' . wp_remote_retrieve_body($response));
7399 - return '';
7400 - }
7401 -
7402 - $results = json_decode(wp_remote_retrieve_body($response), true);
7403 - //error_log('Pinecone raw response: ' . wp_remote_retrieve_body($response));
7404 -
7405 - if (empty($results['matches'])) {
7406 - //error_log('No matches found in Pinecone response');
7407 - return '';
7408 - }
7409 -
7410 - $content = '';
7411 - foreach ($results['matches'] as $match) {
7412 - if ($match['score'] < $similarity_threshold) {
7413 - //error_log("Match below threshold: " . $match['score']);
7414 - continue;
7415 - }
7416 -
7417 - if (!empty($match['metadata']['text'])) {
7418 - $content .= $match['metadata']['text'];
7419 - if (!empty($match['metadata']['source_url'])) {
7420 - $content .= "\n\nFor more details, check out this product: " . esc_url($match['metadata']['source_url']);
7421 - }
7422 - $content .= "\n\n";
7423 - }
7424 - }
7425 -
7426 - return trim($content);
7427 -}
7428 -
7429 -
7430 -private function fetch_content_with_product_links($most_relevant_id) {
7431 - global $wpdb;
7432 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
7433 -
7434 - // Fetch the article content and associated product URL
7435 - $query = $wpdb->prepare("SELECT article_content, source_url FROM {$system_prompt_table} WHERE id = %d", $most_relevant_id);
7436 - $result = $wpdb->get_row($query);
7437 -
7438 - if ($result) {
7439 - // Append the product link to the content if available
7440 - $content = $result->article_content;
7441 - if (!empty($result->source_url)) {
7442 - $content .= "\n\nFor more details, check out this product: " . esc_url($result->source_url);
7443 - }
7444 - return $content;
7445 - }
7446 -
7447 - return null;
7448 -}
7449 -
7450 -/**
7451 - * Get system instructions for a specific bot or default
7452 - * Checks for multi-bot add-on and uses bot-specific instructions if available
7453 - * Automatically strips URLs if citation links are disabled
7454 - * Replaces {visitor_name} placeholder with actual visitor name if available
7455 - *
7456 - * @param string $bot_id The bot ID to get instructions for
7457 - * @param string $session_id Optional session ID to lookup visitor name
7458 - */
7459 -private function get_system_instructions($bot_id = 'default', $session_id = '') {
7460 - $instructions = '';
7461 -
7462 - // Check if multi-bot add-on is active
7463 - if (class_exists('MxChat_Multi_Bot_Core_Manager') && $bot_id !== 'default') {
7464 - // Get bot-specific options from multi-bot add-on
7465 - $bot_options = apply_filters('mxchat_get_bot_options', array(), $bot_id);
7466 -
7467 - // If bot has custom system instructions, use those
7468 - if (!empty($bot_options['system_prompt_instructions'])) {
7469 - $instructions = $bot_options['system_prompt_instructions'];
7470 - }
7471 - }
7472 -
7473 - // Fall back to default system instructions
7474 - if (empty($instructions)) {
7475 - $instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
7476 - }
7477 -
7478 - // Check if citation links are disabled - if so, strip URLs from instructions
7479 - $fresh_options = get_option('mxchat_options', []);
7480 - $citation_links_enabled = isset($fresh_options['citation_links_toggle']) ? ($fresh_options['citation_links_toggle'] === 'on') : true;
7481 -
7482 - if (!$citation_links_enabled && !empty($instructions)) {
7483 - $instructions = preg_replace('#\bhttps?://[^\s<>"\']+#i', '', $instructions);
7484 - $instructions = preg_replace('/\s+/', ' ', trim($instructions)); // Clean up extra spaces
7485 - }
7486 -
7487 - // Replace {visitor_name} placeholder with actual visitor name if available
7488 - if (!empty($instructions) && !empty($session_id) && stripos($instructions, '{visitor_name}') !== false) {
7489 - $name_option_key = "mxchat_name_{$session_id}";
7490 - $visitor_name = get_option($name_option_key, '');
7491 -
7492 - if (!empty($visitor_name)) {
7493 - $instructions = str_ireplace('{visitor_name}', sanitize_text_field($visitor_name), $instructions);
7494 - } else {
7495 - // Remove placeholder if no name is available
7496 - $instructions = str_ireplace('{visitor_name}', '', $instructions);
7497 - $instructions = preg_replace('/\s{2,}/', ' ', trim($instructions)); // Clean up extra spaces
7498 - }
7499 - }
7500 -
7501 - // Allow developers to filter system instructions and process shortcodes
7502 - $instructions = apply_filters('mxchat_system_instructions', $instructions, $bot_id, $session_id);
7503 - $instructions = do_shortcode($instructions);
7504 -
7505 - return $instructions;
7506 -}
7507 -/**
7508 - * Get the current bot ID from session or request context
7509 - */
7510 -private function get_current_bot_id($session_id = '') {
7511 - // First, check if bot_id is passed in the current request
7512 - if (isset($_POST['bot_id']) && !empty($_POST['bot_id'])) {
7513 - return sanitize_key($_POST['bot_id']);
7514 - }
7515 -
7516 - // If not in POST, try to get it from session data
7517 - if (!empty($session_id)) {
7518 - $bot_id = get_option("mxchat_session_bot_{$session_id}", '');
7519 - if (!empty($bot_id)) {
7520 - return $bot_id;
7521 - }
7522 - }
7523 -
7524 - // Fall back to default
7525 - return 'default';
7526 -}
7527 -/* ====================================================================== *
7528 - * Native function-calling loop (plan-mxchat-20260617-a41dee)
7529 - *
7530 - * Model-driven tool use. The model is offered MxChat's enabled callbacks as
7531 - * tools (sourced from MxChat_Tool_Registry, the single source the admin AI
7532 - * Tools checklist also reads). When the model calls a tool, the matching
7533 - * callback runs through its EXISTING permission checks, its output is fed
7534 - * back, and the loop continues up to a depth cap. INDEPENDENT of the
7535 - * intent→callback router — it runs only after intents miss, and works with
7536 - * ZERO Actions created.
7537 - *
7538 - * Entered ONLY when: function calling is enabled + the active model is
7539 - * tool-capable + at least one tool is enabled. Default-off, so existing
7540 - * installs never enter this branch (byte-for-byte unchanged behavior). The
7541 - * tool round is buffered (non-streaming) per the plan; the final answer is
7542 - * emitted via the same SSE/JSON envelopes the normal path uses.
7543 - * ====================================================================== */
7544 -
7545 -/** Gate: should the function-calling loop handle this turn? */
7546 -private function mxchat_fc_should_run($selected_model) {
7547 - if (!class_exists('MxChat_Tool_Registry') || !MxChat_Tool_Registry::is_enabled()) {
7548 - return false;
7549 - }
7550 - if (class_exists('MxChat_Model_Catalog') && !MxChat_Model_Catalog::supports_tools($selected_model)) {
7551 - return false;
7552 - }
7553 - $tools = MxChat_Tool_Registry::enabled_tools();
7554 - return !empty($tools);
7555 -}
7556 -
7557 -private function mxchat_fc_log($msg) {
7558 - if (defined('MXCHAT_DEV_MODE') && MXCHAT_DEV_MODE) {
7559 - error_log('[MxChat FC] ' . $msg);
7560 - }
7561 -}
7562 -
7563 -/**
7564 - * Resolve provider transport details. Returns null when FC can't run for this
7565 - * model/config (missing key, unsupported provider) so the caller falls back to
7566 - * the normal path. OpenAI/xAI/DeepSeek/OpenRouter/Custom share the
7567 - * OpenAI-compatible 'openai' family; Claude and Gemini are distinct.
7568 - */
7569 -private function mxchat_fc_resolve_provider($selected_model, $opts) {
7570 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
7571 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
7572 - if ($selected_model === 'claude-opus-4-20250514') { $selected_model = 'claude-opus-4-8'; }
7573 - elseif ($selected_model === 'claude-sonnet-4-20250514') { $selected_model = 'claude-sonnet-4-6'; }
7574 - if ($selected_model === 'openrouter') {
7575 - $model = isset($opts['openrouter_selected_model']) ? $opts['openrouter_selected_model'] : '';
7576 - $key = isset($opts['openrouter_api_key']) ? $opts['openrouter_api_key'] : '';
7577 - if ($model === '' || $key === '') return null;
7578 - return array('family'=>'openai','model'=>$model,'url'=>'https://openrouter.ai/api/v1/chat/completions',
7579 - 'headers'=>array('Content-Type'=>'application/json','Authorization'=>'Bearer '.$key),'tag'=>'openai');
7580 - }
7581 - $prefix = strtolower(explode('-', $selected_model)[0]);
7582 - switch ($prefix) {
7583 - case 'gpt': case 'o1': case 'o3': case 'o4':
7584 - $key = isset($opts['api_key']) ? $opts['api_key'] : '';
7585 - if ($key === '') return null;
7586 - return array('family'=>'openai','model'=>$selected_model,'url'=>'https://api.openai.com/v1/chat/completions',
7587 - 'headers'=>array('Content-Type'=>'application/json','Authorization'=>'Bearer '.$key),'tag'=>'openai');
7588 - case 'claude':
7589 - $key = isset($opts['claude_api_key']) ? $opts['claude_api_key'] : '';
7590 - if ($key === '') return null;
7591 - return array('family'=>'anthropic','model'=>$selected_model,'url'=>'https://api.anthropic.com/v1/messages',
7592 - 'headers'=>array('Content-Type'=>'application/json','x-api-key'=>$key,'anthropic-version'=>'2023-06-01'),'tag'=>'anthropic');
7593 - case 'gemini':
7594 - $key = isset($opts['gemini_api_key']) ? $opts['gemini_api_key'] : '';
7595 - if ($key === '') return null;
7596 - return array('family'=>'gemini','model'=>$selected_model,'key'=>$key,'tag'=>'gemini');
7597 - case 'grok': case 'xai':
7598 - $key = isset($opts['xai_api_key']) ? $opts['xai_api_key'] : '';
7599 - if ($key === '') return null;
7600 - return array('family'=>'openai','model'=>$selected_model,'url'=>'https://api.x.ai/v1/chat/completions',
7601 - 'headers'=>array('Content-Type'=>'application/json','Authorization'=>'Bearer '.$key),'tag'=>'xai');
7602 - case 'deepseek':
7603 - $key = isset($opts['deepseek_api_key']) ? $opts['deepseek_api_key'] : '';
7604 - if ($key === '') return null;
7605 - return array('family'=>'openai','model'=>$selected_model,'url'=>'https://api.deepseek.com/v1/chat/completions',
7606 - 'headers'=>array('Content-Type'=>'application/json','Authorization'=>'Bearer '.$key),'tag'=>'openai');
7607 - case 'custom':
7608 - $base = isset($opts['custom_provider_base_url']) ? rtrim($opts['custom_provider_base_url'], '/') : '';
7609 - $key = isset($opts['custom_provider_api_key']) ? $opts['custom_provider_api_key'] : '';
7610 - $model = isset($opts['custom_provider_model']) ? $opts['custom_provider_model'] : '';
7611 - if ($base === '' || $model === '') return null;
7612 - $url = (strpos($base, 'chat/completions') !== false) ? $base : $base . '/chat/completions';
7613 - $headers = array('Content-Type'=>'application/json');
7614 - if ($key !== '') $headers['Authorization'] = 'Bearer '.$key;
7615 - return array('family'=>'openai','model'=>$model,'url'=>$url,'headers'=>$headers,'tag'=>'openai');
7616 - }
7617 - return null;
7618 -}
7619 -
7620 -/**
7621 - * Top-level function-calling attempt. Returns:
7622 - * ['handled'=>true, 'text'=>'<final answer>'] when the model used ≥1 tool
7623 - * ['handled'=>false] otherwise (caller falls back
7624 - * to the normal streamed path)
7625 - */
7626 -private function mxchat_fc_attempt($message, $relevant_content, $conversation_history, $selected_model, $opts, $session_id, $user_id) {
7627 - $prov = $this->mxchat_fc_resolve_provider($selected_model, $opts);
7628 - if (!$prov) {
7629 - return array('handled' => false);
7630 - }
7631 - $tools = MxChat_Tool_Registry::enabled_tools();
7632 - if (empty($tools)) {
7633 - return array('handled' => false);
7634 - }
7635 -
7636 - $bot_id = $this->get_current_bot_id($session_id);
7637 - $system = $this->get_system_instructions($bot_id, $session_id);
7638 -
7639 - // Force callbacks into return-mode (some echo SSE directly when streaming);
7640 - // we buffer the whole tool round, then emit once. Restored in finally.
7641 - $prev_streaming = $this->is_streaming;
7642 - $this->is_streaming = false;
7643 - try {
7644 - if ($prov['family'] === 'anthropic') {
7645 - return $this->mxchat_fc_loop_anthropic($prov, $system, $relevant_content, $conversation_history, $tools, $message, $user_id, $session_id);
7646 - } elseif ($prov['family'] === 'gemini') {
7647 - return $this->mxchat_fc_loop_gemini($prov, $system, $relevant_content, $conversation_history, $tools, $message, $user_id, $session_id);
7648 - }
7649 - return $this->mxchat_fc_loop_openai($prov, $system, $relevant_content, $conversation_history, $tools, $message, $user_id, $session_id);
7650 - } catch (\Throwable $e) {
7651 - $this->mxchat_fc_log('attempt threw: ' . $e->getMessage());
7652 - return array('handled' => false);
7653 - } finally {
7654 - $this->is_streaming = $prev_streaming;
7655 - }
7656 -}
7657 -
7658 -/** Normalize MxChat history rows to [{role:user|assistant, content}]. */
7659 -private function mxchat_fc_normalize_history($conversation_history) {
7660 - $out = array();
7661 - if (!is_array($conversation_history)) return $out;
7662 - foreach ($conversation_history as $m) {
7663 - if (!is_array($m) || !isset($m['role']) || !isset($m['content'])) continue;
7664 - $role = $m['role'];
7665 - if ($role === 'bot' || $role === 'agent') $role = 'assistant';
7666 - if (!in_array($role, array('user', 'assistant'), true)) $role = 'user';
7667 - $out[] = array('role' => $role, 'content' => (string) $m['content']);
7668 - }
7669 - return $out;
7670 -}
7671 -
7672 -/** Execute the matched callback for a tool call. Returns ['ok'=>bool,'content'=>string]. */
7673 -private function mxchat_fc_execute_tool($tool_name, $args, $orig_message, $user_id, $session_id) {
7674 - $tool = MxChat_Tool_Registry::tool_by_name($tool_name, true); // enabled-only
7675 - if (!$tool) {
7676 - return array('ok' => false, 'content' => 'This tool is not available or not enabled.');
7677 - }
7678 - $fn = $tool['callback'];
7679 -
7680 - // MxChat callbacks are message-driven: hand them the model's `query`
7681 - // (falling back to the original user message).
7682 - $query = '';
7683 - if (is_array($args) && isset($args['query']) && is_string($args['query'])) {
7684 - $query = $args['query'];
7685 - }
7686 - if ($query === '') $query = $orig_message;
7687 -
7688 - // Synthetic intent row (matches wp_mxchat_intents columns → no undefined-prop warnings).
7689 - $synthetic_intent = (object) array(
7690 - 'id' => 0, 'intent_label' => $tool['label'], 'phrases' => '',
7691 - 'embedding_vector' => '', 'callback_function' => $fn,
7692 - 'similarity_threshold' => 0.0, 'enabled' => 1, 'enabled_bots' => null,
7693 - );
7694 -
7695 - try {
7696 - if (!empty($tool['is_addon'])) {
7697 - $result = apply_filters($fn, false, $query, $user_id, $session_id, $synthetic_intent);
7698 - } elseif (method_exists($this, $fn)) {
7699 - $result = call_user_func(array($this, $fn), $query, $user_id, $session_id, $synthetic_intent, null);
7700 - } else {
7701 - return array('ok' => false, 'content' => 'Tool implementation not found.');
7702 - }
7703 - } catch (\Throwable $e) {
7704 - $this->mxchat_fc_log("tool {$fn} threw: " . $e->getMessage());
7705 - return array('ok' => false, 'content' => 'The tool failed to run.');
7706 - }
7707 -
7708 - // plan-mxchat-20260617-48a57a — surface UI-bearing tool output.
7709 - // If the callback produced a UI element (generated image, product card, image
7710 - // gallery), its html MUST reach the FRONTEND as a real rendered bot message —
7711 - // NOT be stripped to text and handed to the model to paraphrase (that was the
7712 - // bug: under function calling, UI-bearing actions rendered nothing). Capture
7713 - // the html here; the FC outcome handler emits it in the response envelope.
7714 - $ui = $this->mxchat_fc_ui_payload_from($result);
7715 - if ($ui['html'] !== '' || !empty($ui['images'])) {
7716 - if ($ui['html'] !== '') {
7717 - $this->fc_ui_html .= ($this->fc_ui_html !== '' ? "\n" : '') . $ui['html'];
7718 - }
7719 - if (!empty($ui['images']) && is_array($ui['images'])) {
7720 - $this->fc_ui_images = array_merge($this->fc_ui_images, $ui['images']);
7721 - }
7722 - $this->fc_ui_captured = true;
7723 -
7724 - // Persist the html to the transcript ONLY if the callback did not already
7725 - // do so itself. Core image/search callbacks self-save (text + html);
7726 - // add-on callbacks (e.g. woo product cards) return html for the caller to
7727 - // save. ui_self_saves carries this from the registry; default by source
7728 - // (core self-saves, add-on does not) when a tool predates the flag.
7729 - $self_saves = array_key_exists('ui_self_saves', $tool)
7730 - ? !empty($tool['ui_self_saves'])
7731 - : empty($tool['is_addon']);
7732 - if ($ui['html'] !== '' && !$self_saves) {
7733 - $this->mxchat_save_chat_message($session_id, 'bot', $ui['html']);
7734 - }
7735 -
7736 - // Hand the MODEL a short acknowledgment (never the raw or stripped html)
7737 - // so the loop can add a one-line caption without trying to re-describe a
7738 - // visual it cannot see and without duplicating the displayed element.
7739 - $summary = isset($ui['text']) ? trim((string) $ui['text']) : '';
7740 - $ack = __('[A visual result has already been shown to the user in the chat. Do not repeat or describe it in detail — reply with at most a brief one-line caption.]', 'mxchat');
7741 - $content = $summary !== '' ? ($ack . ' ' . $summary) : $ack;
7742 - $this->mxchat_fc_log("executed {$fn} → [ui payload surfaced] " . substr($content, 0, 120));
7743 - return array('ok' => true, 'content' => $content);
7744 - }
7745 -
7746 - $content = $this->mxchat_fc_stringify_result($result);
7747 - $this->mxchat_fc_log("executed {$fn} → " . substr($content, 0, 160));
7748 - return array('ok' => true, 'content' => $content);
7749 -}
7750 -
7751 -/**
7752 - * Extract a UI payload (html + images + text) from a tool callback's return,
7753 - * falling back to $this->fallbackResponse for callbacks that return true after
7754 - * setting it. plan-mxchat-20260617-48a57a.
7755 - *
7756 - * @return array{html:string,images:array,text:string}
7757 - */
7758 -private function mxchat_fc_ui_payload_from($result) {
7759 - $src = null;
7760 - if (is_array($result)) {
7761 - $src = $result;
7762 - } elseif ($result === true && isset($this->fallbackResponse) && is_array($this->fallbackResponse)) {
7763 - $src = $this->fallbackResponse;
7764 - }
7765 - $html = (is_array($src) && isset($src['html']) && is_string($src['html'])) ? $src['html'] : '';
7766 - $images = (is_array($src) && isset($src['images']) && is_array($src['images'])) ? $src['images'] : array();
7767 - $text = (is_array($src) && isset($src['text'])) ? (string) $src['text'] : '';
7768 - return array('html' => $html, 'images' => $images, 'text' => $text);
7769 -}
7770 -
7771 -/** Coerce a callback's return (string|array|true|false) into a tool-result string. */
7772 -private function mxchat_fc_stringify_result($result) {
7773 - if (is_string($result)) {
7774 - return $result === '' ? 'No result.' : $result;
7775 - }
7776 - if ($result === true) {
7777 - // Callbacks that set fallbackResponse and return true.
7778 - $fb = isset($this->fallbackResponse) ? $this->fallbackResponse : null;
7779 - if (is_array($fb)) {
7780 - if (!empty($fb['text'])) return (string) $fb['text'];
7781 - if (!empty($fb['html'])) return wp_strip_all_tags((string) $fb['html']);
7782 - }
7783 - return 'Done.';
7784 - }
7785 - if ($result === false || $result === null) {
7786 - return 'No result.';
7787 - }
7788 - if (is_array($result)) {
7789 - if (isset($result['text']) && $result['text'] !== '') return (string) $result['text'];
7790 - if (isset($result['html']) && $result['html'] !== '') return wp_strip_all_tags((string) $result['html']);
7791 - $json = wp_json_encode($result);
7792 - return $json !== false ? $json : 'No result.';
7793 - }
7794 - return (string) $result;
7795 -}
7796 -
7797 -/** HTTP code + decoded body for a function-calling request. */
7798 -private function mxchat_fc_post($url, $body, $headers, $tag) {
7799 - $args = array(
7800 - 'body' => wp_json_encode($body),
7801 - 'headers' => $headers,
7802 - 'timeout' => 60,
7803 - 'redirection' => 5,
7804 - 'blocking' => true,
7805 - 'httpversion' => '1.0',
7806 - 'sslverify' => true,
7807 - );
7808 - $response = $this->mxchat_provider_call_with_retry($url, $args, $tag);
7809 - if (is_wp_error($response)) {
7810 - return array('code' => 0, 'data' => null, 'error' => $response->get_error_message());
7811 - }
7812 - $code = (int) wp_remote_retrieve_response_code($response);
7813 - $data = json_decode(wp_remote_retrieve_body($response), true);
7814 - return array('code' => $code, 'data' => $data, 'error' => null);
7815 -}
7816 -
7817 -/* ---------------- OpenAI-compatible loop (OpenAI/xAI/DeepSeek/OpenRouter/Custom) -------------- */
7818 -private function mxchat_fc_loop_openai($prov, $system, $relevant_content, $conversation_history, $tools, $orig_message, $user_id, $session_id) {
7819 - $messages = array();
7820 - $messages[] = array('role' => 'system', 'content' => $system . ' ' . $relevant_content);
7821 - foreach ($this->mxchat_fc_normalize_history($conversation_history) as $m) {
7822 - $messages[] = $m;
7823 - }
7824 -
7825 - $depth = MxChat_Tool_Registry::max_depth();
7826 - $budget = MxChat_Tool_Registry::max_tool_calls_per_turn();
7827 - $tool_schema = MxChat_Tool_Registry::to_openai_tools($tools);
7828 - $used_tool = false;
7829 - $calls_made = 0;
7830 -
7831 - for ($step = 0; $step <= $depth; $step++) {
7832 - $offer_tools = ($step < $depth) && !empty($tool_schema);
7833 - $body = array('model' => $prov['model'], 'messages' => $messages, 'temperature' => 1, 'stream' => false);
7834 - if ($offer_tools) {
7835 - $body['tools'] = $tool_schema;
7836 - $body['tool_choice'] = 'auto';
7837 - }
7838 - $r = $this->mxchat_fc_post($prov['url'], $body, $prov['headers'], $prov['tag']);
7839 - if ($r['code'] !== 200 || !is_array($r['data'])) {
7840 - $this->mxchat_fc_log('openai call failed: code=' . $r['code'] . ' err=' . ($r['error'] ?? ''));
7841 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
7842 - }
7843 - $msg = isset($r['data']['choices'][0]['message']) ? $r['data']['choices'][0]['message'] : null;
7844 - if (!$msg) {
7845 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
7846 - }
7847 - $tool_calls = isset($msg['tool_calls']) && is_array($msg['tool_calls']) ? $msg['tool_calls'] : array();
7848 - if (empty($tool_calls)) {
7849 - $text = isset($msg['content']) ? trim((string) $msg['content']) : '';
7850 - if (!$used_tool) return array('handled' => false); // model never used a tool → normal path
7851 - return array('handled' => true, 'text' => ($text !== '' ? $text : $this->mxchat_fc_giveup_text()));
7852 - }
7853 - // Append the assistant tool-call turn verbatim, then a tool result per call.
7854 - $used_tool = true;
7855 - $messages[] = $msg;
7856 - foreach ($tool_calls as $tc) {
7857 - if ($calls_made >= $budget) break;
7858 - $calls_made++;
7859 - $name = isset($tc['function']['name']) ? $tc['function']['name'] : '';
7860 - $args = array();
7861 - if (isset($tc['function']['arguments'])) {
7862 - $decoded = json_decode($tc['function']['arguments'], true);
7863 - if (is_array($decoded)) $args = $decoded;
7864 - }
7865 - $exec = $this->mxchat_fc_execute_tool($name, $args, $orig_message, $user_id, $session_id);
7866 - $messages[] = array(
7867 - 'role' => 'tool',
7868 - 'tool_call_id' => isset($tc['id']) ? $tc['id'] : '',
7869 - 'content' => $exec['content'],
7870 - );
7871 - }
7872 - }
7873 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
7874 -}
7875 -
7876 -/* ---------------- Anthropic Claude loop ---------------- */
7877 -private function mxchat_fc_loop_anthropic($prov, $system, $relevant_content, $conversation_history, $tools, $orig_message, $user_id, $session_id) {
7878 - $messages = $this->mxchat_fc_normalize_history($conversation_history);
7879 - $messages[] = array('role' => 'user', 'content' => $relevant_content);
7880 -
7881 - $depth = MxChat_Tool_Registry::max_depth();
7882 - $budget = MxChat_Tool_Registry::max_tool_calls_per_turn();
7883 - $tool_schema = MxChat_Tool_Registry::to_anthropic_tools($tools);
7884 - $omit_temp = $this->mxchat_claude_omits_temperature($prov['model']);
7885 - $used_tool = false;
7886 - $calls_made = 0;
7887 -
7888 - for ($step = 0; $step <= $depth; $step++) {
7889 - $offer_tools = ($step < $depth) && !empty($tool_schema);
7890 - $body = array('model' => $prov['model'], 'max_tokens' => 1024, 'temperature' => 0.8,
7891 - 'messages' => $messages, 'system' => $system);
7892 - if ($omit_temp) unset($body['temperature']);
7893 - if ($offer_tools) {
7894 - $body['tools'] = $tool_schema;
7895 - $body['tool_choice'] = array('type' => 'auto');
7896 - }
7897 - $r = $this->mxchat_fc_post($prov['url'], $body, $prov['headers'], $prov['tag']);
7898 - if ($r['code'] !== 200 || !is_array($r['data'])) {
7899 - $this->mxchat_fc_log('anthropic call failed: code=' . $r['code'] . ' err=' . ($r['error'] ?? ''));
7900 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
7901 - }
7902 - $content = isset($r['data']['content']) && is_array($r['data']['content']) ? $r['data']['content'] : array();
7903 - $tool_uses = array();
7904 - $text_out = '';
7905 - foreach ($content as $block) {
7906 - if (!isset($block['type'])) continue;
7907 - if ($block['type'] === 'tool_use') {
7908 - $tool_uses[] = $block;
7909 - } elseif ($block['type'] === 'text' && isset($block['text'])) {
7910 - $text_out .= $block['text'];
7911 - }
7912 - }
7913 - if (empty($tool_uses)) {
7914 - if (!$used_tool) return array('handled' => false);
7915 - $text_out = trim($text_out);
7916 - return array('handled' => true, 'text' => ($text_out !== '' ? $text_out : $this->mxchat_fc_giveup_text()));
7917 - }
7918 - // Append the assistant turn (the full content array), then a user turn of tool_result blocks.
7919 - $used_tool = true;
7920 - $messages[] = array('role' => 'assistant', 'content' => $content);
7921 - $results = array();
7922 - foreach ($tool_uses as $tu) {
7923 - if ($calls_made >= $budget) break;
7924 - $calls_made++;
7925 - $name = isset($tu['name']) ? $tu['name'] : '';
7926 - $args = isset($tu['input']) && is_array($tu['input']) ? $tu['input'] : array();
7927 - $exec = $this->mxchat_fc_execute_tool($name, $args, $orig_message, $user_id, $session_id);
7928 - $results[] = array(
7929 - 'type' => 'tool_result',
7930 - 'tool_use_id' => isset($tu['id']) ? $tu['id'] : '',
7931 - 'content' => $exec['content'],
7932 - );
7933 - }
7934 - $messages[] = array('role' => 'user', 'content' => $results);
7935 - }
7936 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
7937 -}
7938 -
7939 -/* ---------------- Google Gemini loop ---------------- */
7940 -private function mxchat_fc_loop_gemini($prov, $system, $relevant_content, $conversation_history, $tools, $orig_message, $user_id, $session_id) {
7941 - $contents = array();
7942 - $contents[] = array('role' => 'user', 'parts' => array(array('text' => '[System Instructions] ' . $system . ' ' . $relevant_content)));
7943 - $contents[] = array('role' => 'model', 'parts' => array(array('text' => 'I understand and will follow these instructions.')));
7944 - foreach ($this->mxchat_fc_normalize_history($conversation_history) as $m) {
7945 - $contents[] = array('role' => ($m['role'] === 'assistant' ? 'model' : 'user'),
7946 - 'parts' => array(array('text' => $m['content'])));
7947 - }
7948 -
7949 - $depth = MxChat_Tool_Registry::max_depth();
7950 - $budget = MxChat_Tool_Registry::max_tool_calls_per_turn();
7951 - $tool_schema = MxChat_Tool_Registry::to_gemini_tools($tools);
7952 - // Function calling (tools + functionDeclarations + toolConfig) is a v1beta feature on the
7953 - // Generative Language REST API. The v1 endpoint silently ignores the tools array, so a
7954 - // non-preview model (e.g. gemini-2.5-pro, gemini-3.5-flash, gemini-3.1-flash-lite) would
7955 - // just answer in text and never emit a tool call. Always use v1beta for the FC loop —
7956 - // confirmed against Google's function-calling docs (their REST example targets
7957 - // v1beta/models/gemini-3.5-flash:generateContent). v1beta is a superset, so every model
7958 - // reachable on v1 is also reachable here.
7959 - $api_version = 'v1beta';
7960 - $url = 'https://generativelanguage.googleapis.com/' . $api_version . '/models/' . $prov['model'] . ':generateContent?key=' . $prov['key'];
7961 - $headers = array('Content-Type' => 'application/json');
7962 - $used_tool = false;
7963 - $calls_made = 0;
7964 -
7965 - for ($step = 0; $step <= $depth; $step++) {
7966 - $offer_tools = ($step < $depth) && !empty($tool_schema);
7967 - $body = array(
7968 - 'contents' => $contents,
7969 - 'generationConfig' => array('temperature' => 0.7, 'topP' => 0.95, 'topK' => 40, 'maxOutputTokens' => 8192),
7970 - );
7971 - if ($offer_tools) {
7972 - $body['tools'] = $tool_schema;
7973 - $body['toolConfig'] = array('functionCallingConfig' => array('mode' => 'AUTO'));
7974 - }
7975 - $r = $this->mxchat_fc_post($url, $body, $headers, 'gemini');
7976 - if ($r['code'] !== 200 || !is_array($r['data']) || isset($r['data']['error'])) {
7977 - $this->mxchat_fc_log('gemini call failed: code=' . $r['code'] . ' err=' . ($r['error'] ?? ''));
7978 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
7979 - }
7980 - $parts = isset($r['data']['candidates'][0]['content']['parts']) && is_array($r['data']['candidates'][0]['content']['parts'])
7981 - ? $r['data']['candidates'][0]['content']['parts'] : array();
7982 - $fn_calls = array();
7983 - $text_out = '';
7984 - foreach ($parts as $p) {
7985 - if (isset($p['functionCall'])) {
7986 - $fn_calls[] = $p['functionCall'];
7987 - } elseif (isset($p['text'])) {
7988 - $text_out .= $p['text'];
7989 - }
7990 - }
7991 - if (empty($fn_calls)) {
7992 - if (!$used_tool) return array('handled' => false);
7993 - $text_out = trim($text_out);
7994 - return array('handled' => true, 'text' => ($text_out !== '' ? $text_out : $this->mxchat_fc_giveup_text()));
7995 - }
7996 - // Append the model turn (its parts) then a user turn of functionResponse parts.
7997 - $used_tool = true;
7998 - $contents[] = array('role' => 'model', 'parts' => $parts);
7999 - $resp_parts = array();
8000 - foreach ($fn_calls as $fcall) {
8001 - if ($calls_made >= $budget) break;
8002 - $calls_made++;
8003 - $name = isset($fcall['name']) ? $fcall['name'] : '';
8004 - $args = isset($fcall['args']) && is_array($fcall['args']) ? $fcall['args'] : array();
8005 - $exec = $this->mxchat_fc_execute_tool($name, $args, $orig_message, $user_id, $session_id);
8006 - $fr = array('name' => $name, 'response' => array('result' => $exec['content']));
8007 - // Gemini 3 function calls carry a unique id; echo the matching id back in the
8008 - // functionResponse so the model maps the result to the right call (Google REST
8009 - // guidance). Older models omit the id — then we send none, exactly as before.
8010 - if (isset($fcall['id']) && $fcall['id'] !== '') { $fr['id'] = $fcall['id']; }
8011 - $resp_parts[] = array('functionResponse' => $fr);
8012 - }
8013 - $contents[] = array('role' => 'user', 'parts' => $resp_parts);
8014 - }
8015 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
8016 -}
8017 -
8018 -private function mxchat_fc_giveup_text() {
8019 - return esc_html__('I looked into that but could not put together a final answer. Please try rephrasing your request.', 'mxchat');
8020 -}
8021 -
8022 -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-5.1-chat-latest') {
8023 - try {
8024 - if (!$relevant_content) {
8025 - $error_response = [
8026 - 'error' => esc_html__("I couldn't find relevant information on that topic.", 'mxchat'),
8027 - 'error_code' => 'no_relevant_content'
8028 - ];
8029 -
8030 - if ($testing_data !== null) {
8031 - $error_response['testing_data'] = $testing_data;
8032 - }
8033 -
8034 - return $error_response;
8035 - }
8036 -
8037 - if (!is_array($conversation_history)) {
8038 - $conversation_history = array();
8039 - }
8040 -
8041 - // Check if this is an OpenRouter model
8042 - if ($selected_model === 'openrouter') {
8043 - // Get the actual OpenRouter model from options
8044 - $openrouter_selected_model = $this->options['openrouter_selected_model'] ?? '';
8045 -
8046 - if (empty($openrouter_selected_model)) {
8047 - $error_response = [
8048 - 'error' => esc_html__('No OpenRouter model selected. Please select a model in settings.', 'mxchat'),
8049 - 'error_code' => 'no_openrouter_model_selected'
8050 - ];
8051 - if ($testing_data !== null) {
8052 - $error_response['testing_data'] = $testing_data;
8053 - }
8054 - return $error_response;
8055 - }
8056 -
8057 - if (empty($openrouter_api_key)) {
8058 - $error_response = [
8059 - 'error' => esc_html__('OpenRouter API key is not configured', 'mxchat'),
8060 - 'error_code' => 'missing_openrouter_api_key'
8061 - ];
8062 - if ($testing_data !== null) {
8063 - $error_response['testing_data'] = $testing_data;
8064 - }
8065 - return $error_response;
8066 - }
8067 -
8068 - if ($streaming) {
8069 - return $this->mxchat_generate_response_openrouter_stream(
8070 - $openrouter_selected_model,
8071 - $openrouter_api_key,
8072 - $conversation_history,
8073 - $relevant_content,
8074 - $session_id,
8075 - $testing_data
8076 - );
8077 - } else {
8078 - $response = $this->mxchat_generate_response_openrouter(
8079 - $openrouter_selected_model,
8080 - $openrouter_api_key,
8081 - $conversation_history,
8082 - $relevant_content,
8083 - $session_id
8084 - );
8085 - }
8086 -
8087 - if (is_array($response) && isset($response['error'])) {
8088 - if ($testing_data !== null) {
8089 - $response['testing_data'] = $testing_data;
8090 - }
8091 - return $response;
8092 - }
8093 -
8094 - return $response;
8095 - }
8096 -
8097 - // Extract model prefix to determine the provider
8098 - $model_parts = explode('-', $selected_model);
8099 - $provider = strtolower($model_parts[0]);
8100 -
8101 - // Handle model selection based on provider prefix
8102 - switch ($provider) {
8103 - case 'gemini':
8104 - if (empty($gemini_api_key)) {
8105 - $error_response = [
8106 - 'error' => esc_html__('Google Gemini API key is not configured', 'mxchat'),
8107 - 'error_code' => 'missing_gemini_api_key'
8108 - ];
8109 - if ($testing_data !== null) {
8110 - $error_response['testing_data'] = $testing_data;
8111 - }
8112 - return $error_response;
8113 - }
8114 - $response = $this->mxchat_generate_response_gemini(
8115 - $selected_model,
8116 - $gemini_api_key,
8117 - $conversation_history,
8118 - $relevant_content,
8119 - $session_id
8120 - );
8121 - break;
8122 -
8123 - case 'claude':
8124 - if (empty($claude_api_key)) {
8125 - $error_response = [
8126 - 'error' => esc_html__('Claude API key is not configured', 'mxchat'),
8127 - 'error_code' => 'missing_claude_api_key'
8128 - ];
8129 - if ($testing_data !== null) {
8130 - $error_response['testing_data'] = $testing_data;
8131 - }
8132 - return $error_response;
8133 - }
8134 - if ($streaming) {
8135 - return $this->mxchat_generate_response_claude_stream(
8136 - $selected_model,
8137 - $claude_api_key,
8138 - $conversation_history,
8139 - $relevant_content,
8140 - $session_id,
8141 - $testing_data
8142 - );
8143 - } else {
8144 - $response = $this->mxchat_generate_response_claude(
8145 - $selected_model,
8146 - $claude_api_key,
8147 - $conversation_history,
8148 - $relevant_content,
8149 - $session_id
8150 - );
8151 - }
8152 - break;
8153 -
8154 - case 'grok':
8155 - if (empty($xai_api_key)) {
8156 - $error_response = [
8157 - 'error' => esc_html__('X.AI API key is not configured', 'mxchat'),
8158 - 'error_code' => 'missing_xai_api_key'
8159 - ];
8160 - if ($testing_data !== null) {
8161 - $error_response['testing_data'] = $testing_data;
8162 - }
8163 - return $error_response;
8164 - }
8165 - if ($streaming) {
8166 - return $this->mxchat_generate_response_xai_stream(
8167 - $selected_model,
8168 - $xai_api_key,
8169 - $conversation_history,
8170 - $relevant_content,
8171 - $session_id,
8172 - $testing_data
8173 - );
8174 - } else {
8175 - $response = $this->mxchat_generate_response_xai(
8176 - $selected_model,
8177 - $xai_api_key,
8178 - $conversation_history,
8179 - $relevant_content,
8180 - $session_id
8181 - );
8182 - }
8183 - break;
8184 -
8185 - case 'deepseek':
8186 - if (empty($deepseek_api_key)) {
8187 - $error_response = [
8188 - 'error' => esc_html__('DeepSeek API key is not configured', 'mxchat'),
8189 - 'error_code' => 'missing_deepseek_api_key'
8190 - ];
8191 - if ($testing_data !== null) {
8192 - $error_response['testing_data'] = $testing_data;
8193 - }
8194 - return $error_response;
8195 - }
8196 - if ($streaming) {
8197 - return $this->mxchat_generate_response_deepseek_stream(
8198 - $selected_model,
8199 - $deepseek_api_key,
8200 - $conversation_history,
8201 - $relevant_content,
8202 - $session_id,
8203 - $testing_data
8204 - );
8205 - } else {
8206 - $response = $this->mxchat_generate_response_deepseek(
8207 - $selected_model,
8208 - $deepseek_api_key,
8209 - $conversation_history,
8210 - $relevant_content,
8211 - $session_id
8212 - );
8213 - }
8214 - break;
8215 -
8216 - case 'custom':
8217 - // Custom (OpenAI-compatible) provider — Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI
8218 - $cp_base_url = isset($this->options['custom_provider_base_url']) ? trim((string) $this->options['custom_provider_base_url']) : '';
8219 - if (empty($cp_base_url)) {
8220 - $error_response = [
8221 - 'error' => esc_html__('Custom provider is not configured. Set Base URL in MxChat → API Keys → Custom Provider.', 'mxchat'),
8222 - 'error_code' => 'missing_custom_provider_base_url'
8223 - ];
8224 - if ($testing_data !== null) {
8225 - $error_response['testing_data'] = $testing_data;
8226 - }
8227 - return $error_response;
8228 - }
8229 - if ($streaming) {
8230 - return $this->mxchat_generate_response_custom_stream(
8231 - $selected_model,
8232 - $conversation_history,
8233 - $relevant_content,
8234 - $session_id,
8235 - $testing_data
8236 - );
8237 - } else {
8238 - $response = $this->mxchat_generate_response_custom(
8239 - $selected_model,
8240 - $conversation_history,
8241 - $relevant_content
8242 - );
8243 - }
8244 - break;
8245 -
8246 - case 'gpt':
8247 - case 'o1':
8248 - if (empty($api_key)) {
8249 - $error_response = [
8250 - 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
8251 - 'error_code' => 'missing_openai_api_key'
8252 - ];
8253 - if ($testing_data !== null) {
8254 - $error_response['testing_data'] = $testing_data;
8255 - }
8256 - return $error_response;
8257 - }
8258 -
8259 - // Check if web search is enabled for this OpenAI model
8260 - $web_search_enabled = isset($this->options['enable_web_search']) && $this->options['enable_web_search'] === 'on';
8261 - // Models that don't support web search
8262 - $unsupported_web_search_models = array('gpt-4.1-nano');
8263 - $model_supports_web_search = !in_array($selected_model, $unsupported_web_search_models);
8264 -
8265 - if ($web_search_enabled && $model_supports_web_search) {
8266 - // Use Responses API (required for some models, or when web search is enabled)
8267 - return $this->mxchat_generate_response_openai_web_search(
8268 - $selected_model,
8269 - $api_key,
8270 - $conversation_history,
8271 - $relevant_content,
8272 - $session_id,
8273 - $testing_data,
8274 - $streaming
8275 - );
8276 - } elseif ($streaming) {
8277 - return $this->mxchat_generate_response_openai_stream(
8278 - $selected_model,
8279 - $api_key,
8280 - $conversation_history,
8281 - $relevant_content,
8282 - $session_id,
8283 - $testing_data
8284 - );
8285 - } else {
8286 - $response = $this->mxchat_generate_response_openai(
8287 - $selected_model,
8288 - $api_key,
8289 - $conversation_history,
8290 - $relevant_content,
8291 - $session_id
8292 - );
8293 - }
8294 - break;
8295 -
8296 - default:
8297 - if (empty($api_key)) {
8298 - $error_response = [
8299 - 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
8300 - 'error_code' => 'missing_openai_api_key'
8301 - ];
8302 - if ($testing_data !== null) {
8303 - $error_response['testing_data'] = $testing_data;
8304 - }
8305 - return $error_response;
8306 - }
8307 -
8308 - // Check if web search is enabled (default case also handles OpenAI models)
8309 - $web_search_enabled = isset($this->options['enable_web_search']) && $this->options['enable_web_search'] === 'on';
8310 - $unsupported_web_search_models = array('gpt-4.1-nano');
8311 - $model_supports_web_search = !in_array($selected_model, $unsupported_web_search_models);
8312 -
8313 - if ($web_search_enabled && $model_supports_web_search) {
8314 - return $this->mxchat_generate_response_openai_web_search(
8315 - $selected_model,
8316 - $api_key,
8317 - $conversation_history,
8318 - $relevant_content,
8319 - $session_id,
8320 - $testing_data,
8321 - $streaming
8322 - );
8323 - } elseif ($streaming) {
8324 - return $this->mxchat_generate_response_openai_stream(
8325 - $selected_model,
8326 - $api_key,
8327 - $conversation_history,
8328 - $relevant_content,
8329 - $session_id,
8330 - $testing_data
8331 - );
8332 - } else {
8333 - $response = $this->mxchat_generate_response_openai(
8334 - $selected_model,
8335 - $api_key,
8336 - $conversation_history,
8337 - $relevant_content,
8338 - $session_id
8339 - );
8340 - }
8341 - break;
8342 - }
8343 -
8344 - if (is_array($response) && isset($response['error'])) {
8345 - if ($testing_data !== null) {
8346 - $response['testing_data'] = $testing_data;
8347 - }
8348 - return $response;
8349 - }
8350 -
8351 - return $response;
8352 -
8353 - } catch (Exception $e) {
8354 - $error_response = [
8355 - 'error' => sprintf(esc_html__('An error occurred: %s', 'mxchat'), esc_html($e->getMessage())),
8356 - 'error_code' => 'system_exception',
8357 - 'exception_details' => $e->getMessage()
8358 - ];
8359 -
8360 - if ($testing_data !== null) {
8361 - $error_response['testing_data'] = $testing_data;
8362 - }
8363 -
8364 - return $error_response;
8365 - }
8366 -}
8367 -private function mxchat_generate_response_openrouter_stream($selected_model, $openrouter_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
8368 - try {
8369 - $bot_id = $this->get_current_bot_id($session_id);
8370 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
8371 -
8372 - if (!is_array($conversation_history)) {
8373 - $conversation_history = array();
8374 - }
8375 -
8376 - $formatted_conversation = array();
8377 -
8378 - $formatted_conversation[] = array(
8379 - 'role' => 'system',
8380 - 'content' => $system_prompt_instructions . " " . $relevant_content
8381 - );
8382 -
8383 - foreach ($conversation_history as $message) {
8384 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
8385 - $role = $message['role'];
8386 - if ($role === 'bot' || $role === 'agent') {
8387 - $role = 'assistant';
8388 - }
8389 - if (!in_array($role, ['system', 'assistant', 'user'])) {
8390 - $role = 'user';
8391 - }
8392 - $formatted_conversation[] = array(
8393 - 'role' => $role,
8394 - 'content' => $message['content']
8395 - );
8396 - }
8397 - }
8398 -
8399 - if (headers_sent() || !function_exists('curl_init')) {
8400 - $regular_response = $this->mxchat_generate_response_openrouter(
8401 - $selected_model,
8402 - $openrouter_api_key,
8403 - $conversation_history,
8404 - $relevant_content,
8405 - $session_id
8406 - );
8407 -
8408 - // Save bot response to transcript
8409 - if (!empty($regular_response) && !empty($session_id)) {
8410 - $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
8411 - }
8412 -
8413 - $response_data = [
8414 - 'text' => $regular_response,
8415 - 'html' => '',
8416 - 'session_id' => $session_id
8417 - ];
8418 -
8419 - if ($testing_data !== null) {
8420 - $response_data['testing_data'] = $testing_data;
8421 - }
8422 -
8423 - header('Content-Type: application/json');
8424 - echo json_encode($response_data);
8425 - return true;
8426 - }
8427 -
8428 - $body = json_encode([
8429 - 'model' => $selected_model,
8430 - 'messages' => $formatted_conversation,
8431 - 'temperature' => 1,
8432 - 'stream' => true
8433 - ]);
8434 -
8435 - // V2 retry-on-initial-connect: setup_streaming_headers is now lazy-fired
8436 - // inside WRITEFUNCTION on first byte of a successful upstream.
8437 -
8438 - $captured_status_code = 0;
8439 - $captured_body_pre_stream = '';
8440 - $full_response = '';
8441 - $stream_started = false;
8442 - $buffer = '';
8443 - $errno = 0;
8444 - $last_curl_error = '';
8445 - $http_code = 0;
8446 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
8447 - $backoff_ms = array(0, 750, 2000);
8448 -
8449 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
8450 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
8451 - usleep($backoff_ms[$attempt] * 1000);
8452 - }
8453 -
8454 - $captured_status_code = 0;
8455 - $captured_body_pre_stream = '';
8456 - $full_response = '';
8457 - $stream_started = false;
8458 - $buffer = '';
8459 -
8460 - $ch = curl_init();
8461 - curl_setopt($ch, CURLOPT_URL, 'https://openrouter.ai/api/v1/chat/completions');
8462 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
8463 - curl_setopt($ch, CURLOPT_POST, true);
8464 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
8465 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
8466 - 'Content-Type: application/json',
8467 - 'Authorization: Bearer ' . $openrouter_api_key,
8468 - 'HTTP-Referer: ' . home_url(),
8469 - 'X-Title: ' . get_bloginfo('name')
8470 - ));
8471 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
8472 - curl_setopt($ch, CURLOPT_TIMEOUT, 60);
8473 -
8474 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
8475 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
8476 - $captured_status_code = (int) $m[1];
8477 - }
8478 - return strlen($header);
8479 - });
8480 -
8481 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
8482 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
8483 - $captured_body_pre_stream .= $data;
8484 - return strlen($data);
8485 - }
8486 -
8487 - if (!$this->streaming_headers_sent) {
8488 - $this->setup_streaming_headers();
8489 - }
8490 -
8491 - if (!$stream_started && $testing_data !== null) {
8492 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
8493 - flush();
8494 - $stream_started = true;
8495 - }
8496 -
8497 - $buffer .= $data;
8498 - $lines = explode("\n", $buffer);
8499 - $buffer = array_pop($lines);
8500 -
8501 - foreach ($lines as $line) {
8502 - if (trim($line) === '') {
8503 - continue;
8504 - }
8505 - if (strpos($line, 'data: ') !== 0) {
8506 - continue;
8507 - }
8508 -
8509 - $json_str = substr($line, 6);
8510 -
8511 - if (trim($json_str) === '[DONE]') {
8512 - echo "data: [DONE]\n\n";
8513 - flush();
8514 - continue;
8515 - }
8516 -
8517 - $json = json_decode(trim($json_str), true);
8518 - if ($json && isset($json['choices'][0]['delta']['content'])) {
8519 - $content = $json['choices'][0]['delta']['content'];
8520 - $full_response .= $content;
8521 -
8522 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
8523 - flush();
8524 - }
8525 - }
8526 -
8527 - return strlen($data);
8528 - });
8529 -
8530 - $response = curl_exec($ch);
8531 - $errno = curl_errno($ch);
8532 - $last_curl_error = curl_error($ch);
8533 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
8534 - curl_close($ch);
8535 -
8536 - if (!$errno && $http_code === 200) {
8537 - break;
8538 - }
8539 -
8540 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'openai', $errno);
8541 - $can_retry = !$this->streaming_headers_sent
8542 - && ($attempt + 1) < $max_attempts
8543 - && $is_transient;
8544 -
8545 - if (defined('WP_DEBUG') && WP_DEBUG) {
8546 - error_log(sprintf(
8547 - '[MxChat] openrouter_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
8548 - $attempt + 1, $max_attempts, $http_code, $errno,
8549 - $is_transient ? 'yes' : 'no',
8550 - $can_retry ? 'Retrying.' : 'Giving up.'
8551 - ));
8552 - }
8553 -
8554 - if (!$can_retry) {
8555 - break;
8556 - }
8557 - }
8558 -
8559 - if (!$errno && $http_code === 200) {
8560 - if (!empty($full_response) && !empty($session_id)) {
8561 - $rag_context_for_storage = null;
8562 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
8563 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
8564 -
8565 - if ($has_rag_data || $has_action_data) {
8566 - $rag_context_for_storage = [];
8567 -
8568 - if ($has_rag_data) {
8569 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
8570 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
8571 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
8572 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
8573 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
8574 - }
8575 -
8576 - if ($has_action_data) {
8577 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
8578 - }
8579 - }
8580 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
8581 - }
8582 - return true;
8583 - }
8584 -
8585 - return $this->mxchat_stream_emit_fallback(
8586 - 'openai',
8587 - $this->mxchat_generate_response_openrouter($selected_model, $openrouter_api_key, $conversation_history, $relevant_content, $session_id),
8588 - $session_id,
8589 - $testing_data
8590 - );
8591 -
8592 - } catch (Exception $e) {
8593 - return $this->mxchat_stream_emit_fallback(
8594 - 'openai',
8595 - $this->mxchat_generate_response_openrouter($selected_model, $openrouter_api_key, $conversation_history, $relevant_content, $session_id),
8596 - $session_id,
8597 - $testing_data
8598 - );
8599 - }
8600 -}
8601 -private function mxchat_generate_response_openai_stream($selected_model, $api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
8602 - try {
8603 - $bot_id = $this->get_current_bot_id($session_id);
8604 -
8605 - // Get system prompt instructions using centralized function
8606 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
8607 -
8608 - // Ensure conversation_history is an array
8609 - if (!is_array($conversation_history)) {
8610 - $conversation_history = array();
8611 - }
8612 -
8613 - // Format conversation history for OpenAI
8614 - $formatted_conversation = array();
8615 -
8616 - $formatted_conversation[] = array(
8617 - 'role' => 'system',
8618 - 'content' => $system_prompt_instructions . " " . $relevant_content
8619 - );
8620 -
8621 - foreach ($conversation_history as $message) {
8622 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
8623 - $role = $message['role'];
8624 - if ($role === 'bot' || $role === 'agent') {
8625 - $role = 'assistant';
8626 - }
8627 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
8628 - $role = 'user';
8629 - }
8630 - $formatted_conversation[] = array(
8631 - 'role' => $role,
8632 - 'content' => $message['content']
8633 - );
8634 - }
8635 - }
8636 -
8637 - // Check if we can actually stream
8638 - if (headers_sent() || !function_exists('curl_init')) {
8639 - // Fallback to regular response with testing data
8640 - $regular_response = $this->mxchat_generate_response_openai(
8641 - $selected_model,
8642 - $api_key,
8643 - $conversation_history,
8644 - $relevant_content,
8645 - $session_id
8646 - );
8647 -
8648 - // Save bot response to transcript
8649 - if (!empty($regular_response) && !empty($session_id)) {
8650 - $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
8651 - }
8652 -
8653 - $response_data = [
8654 - 'text' => $regular_response,
8655 - 'html' => '',
8656 - 'session_id' => $session_id
8657 - ];
8658 -
8659 - if ($testing_data !== null) {
8660 - $response_data['testing_data'] = $testing_data;
8661 - }
8662 -
8663 - header('Content-Type: application/json');
8664 - echo json_encode($response_data);
8665 - return true;
8666 - }
8667 -
8668 - // Build request body with optimal settings for fast streaming
8669 - $request_body = [
8670 - 'model' => $selected_model,
8671 - 'messages' => $formatted_conversation,
8672 - 'temperature' => 1,
8673 - 'stream' => true
8674 - ];
8675 -
8676 - // reasoning_effort — sourced from the core model catalog (plan-dcb71c);
8677 - // frozen inline ladder lives in mxchat_reasoning_effort_fallback().
8678 - $effort = $this->mxchat_reasoning_effort_for($selected_model, 'chat');
8679 - if ($effort !== null) {
8680 - $request_body['reasoning_effort'] = $effort;
8681 - }
8682 -
8683 - $body = json_encode($request_body);
8684 -
8685 - // V2 retry-on-initial-connect: do NOT call setup_streaming_headers() here.
8686 - // It is now lazy-fired inside the WRITEFUNCTION on the first byte of a
8687 - // SUCCESSFUL upstream response, gated by the captured HTTP status.
8688 -
8689 - $captured_status_code = 0;
8690 - $captured_body_pre_stream = '';
8691 - $full_response = '';
8692 - $stream_started = false;
8693 - $buffer = '';
8694 - $errno = 0;
8695 - $last_curl_error = '';
8696 - $http_code = 0;
8697 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
8698 - $backoff_ms = array(0, 750, 2000);
8699 -
8700 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
8701 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
8702 - usleep($backoff_ms[$attempt] * 1000);
8703 - }
8704 -
8705 - // Reset per-attempt capture state.
8706 - $captured_status_code = 0;
8707 - $captured_body_pre_stream = '';
8708 - $full_response = '';
8709 - $stream_started = false;
8710 - $buffer = '';
8711 -
8712 - $ch = curl_init();
8713 - curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
8714 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
8715 - curl_setopt($ch, CURLOPT_POST, true);
8716 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
8717 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
8718 - 'Content-Type: application/json',
8719 - 'Authorization: Bearer ' . $api_key
8720 - ));
8721 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
8722 - curl_setopt($ch, CURLOPT_TIMEOUT, 60);
8723 -
8724 - // Capture HTTP status as soon as response headers arrive — fires before WRITEFUNCTION.
8725 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
8726 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
8727 - $captured_status_code = (int) $m[1];
8728 - }
8729 - return strlen($header);
8730 - });
8731 -
8732 - // Buffer control for real-time streaming
8733 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
8734 - // V2 guard: if upstream returned non-200, buffer body for transient
8735 - // classification and DO NOT emit to client. Stream channel must NOT open.
8736 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
8737 - $captured_body_pre_stream .= $data;
8738 - return strlen($data);
8739 - }
8740 -
8741 - // Lazy-fire streaming headers on first byte of a SUCCESSFUL upstream.
8742 - // After this point streaming_headers_sent === true → retry is structurally blocked.
8743 - if (!$this->streaming_headers_sent) {
8744 - $this->setup_streaming_headers();
8745 - }
8746 -
8747 - // Send testing data as the first event if available
8748 - if (!$stream_started && $testing_data !== null) {
8749 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
8750 - flush();
8751 - $stream_started = true;
8752 - }
8753 -
8754 - // CRITICAL FIX: Append new data to buffer
8755 - $buffer .= $data;
8756 -
8757 - // Process complete lines only
8758 - $lines = explode("\n", $buffer);
8759 -
8760 - // CRITICAL FIX: Keep the last incomplete line in the buffer
8761 - $buffer = array_pop($lines);
8762 -
8763 - foreach ($lines as $line) {
8764 - if (trim($line) === '') {
8765 - continue;
8766 - }
8767 - if (strpos($line, 'data: ') !== 0) {
8768 - continue;
8769 - }
8770 -
8771 - $json_str = substr($line, 6);
8772 -
8773 - if (trim($json_str) === '[DONE]') {
8774 - echo "data: [DONE]\n\n";
8775 - flush();
8776 - continue;
8777 - }
8778 -
8779 - $json = json_decode(trim($json_str), true);
8780 - if ($json && isset($json['choices'][0]['delta']['content'])) {
8781 - $content = $json['choices'][0]['delta']['content'];
8782 - $full_response .= $content;
8783 -
8784 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
8785 - flush();
8786 - }
8787 - }
8788 -
8789 - return strlen($data);
8790 - });
8791 -
8792 - $response = curl_exec($ch);
8793 - $errno = curl_errno($ch);
8794 - $last_curl_error = curl_error($ch);
8795 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
8796 - curl_close($ch);
8797 -
8798 - if (!$errno && $http_code === 200) {
8799 - break; // Happy path — WRITEFUNCTION already streamed everything.
8800 - }
8801 -
8802 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'openai', $errno);
8803 - $can_retry = !$this->streaming_headers_sent
8804 - && ($attempt + 1) < $max_attempts
8805 - && $is_transient;
8806 -
8807 - if (defined('WP_DEBUG') && WP_DEBUG) {
8808 - error_log(sprintf(
8809 - '[MxChat] openai_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
8810 - $attempt + 1, $max_attempts, $http_code, $errno,
8811 - $is_transient ? 'yes' : 'no',
8812 - $can_retry ? 'Retrying.' : 'Giving up.'
8813 - ));
8814 - }
8815 -
8816 - if (!$can_retry) {
8817 - break;
8818 - }
8819 - }
8820 -
8821 - // Post-loop branch.
8822 - if (!$errno && $http_code === 200) {
8823 - // Happy path — save the complete response to maintain chat persistence.
8824 - if (!empty($full_response) && !empty($session_id)) {
8825 - $rag_context_for_storage = null;
8826 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
8827 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
8828 -
8829 - if ($has_rag_data || $has_action_data) {
8830 - $rag_context_for_storage = [];
8831 -
8832 - if ($has_rag_data) {
8833 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
8834 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
8835 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
8836 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
8837 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
8838 - }
8839 -
8840 - if ($has_action_data) {
8841 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
8842 - }
8843 - }
8844 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
8845 - }
8846 -
8847 - return true;
8848 - }
8849 -
8850 - // Failure path — branch on whether SSE channel was opened.
8851 - return $this->mxchat_stream_emit_fallback(
8852 - 'openai',
8853 - $this->mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content, $session_id),
8854 - $session_id,
8855 - $testing_data
8856 - );
8857 -
8858 - } catch (Exception $e) {
8859 - return $this->mxchat_stream_emit_fallback(
8860 - 'openai',
8861 - $this->mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content, $session_id),
8862 - $session_id,
8863 - $testing_data
8864 - );
8865 - }
8866 -}
8867 -
8868 -/**
8869 - * Shared fallback emitter for streaming chat functions. Two outcomes:
8870 - * - streaming_headers_sent === true: SSE channel is open. Emit fallback content
8871 - * as `data: {...}\n\n` + `data: [DONE]\n\n` so the widget renders it as a
8872 - * normal bot bubble. Transcript row is persisted.
8873 - * - streaming_headers_sent === false: SSE channel never opened (retries
8874 - * exhausted on initial connect). Emit a clean JSON response — the path
8875 - * the widget would normally hit if streaming wasn't even attempted.
8876 - *
8877 - * Used by all six *_stream functions after their per-attempt retry loop.
8878 - */
8879 -private function mxchat_stream_emit_fallback($provider_hint, $regular_response, $session_id, $testing_data = null) {
8880 - $is_error_array = is_array($regular_response) && isset($regular_response['error']);
8881 -
8882 - if ($this->streaming_headers_sent) {
8883 - if ($is_error_array) {
8884 - echo "data: " . json_encode([
8885 - 'error' => true,
8886 - 'error_message' => $regular_response['error'],
8887 - 'error_code' => $regular_response['error_code'] ?? 'api_error',
8888 - 'text' => $regular_response['error'],
8889 - 'message' => $regular_response['error']
8890 - ]) . "\n\n";
8891 - echo "data: [DONE]\n\n";
8892 - flush();
8893 - return true;
8894 - }
8895 - $fallback_message = (string) $regular_response;
8896 - if (!empty($fallback_message) && !empty($session_id)) {
8897 - $this->mxchat_save_chat_message($session_id, 'bot', $fallback_message);
8898 - }
8899 - echo "data: " . json_encode(['content' => $fallback_message]) . "\n\n";
8900 - echo "data: [DONE]\n\n";
8901 - flush();
8902 - return true;
8903 - }
8904 -
8905 - // SSE channel never opened — clean JSON fallback.
8906 - if ($is_error_array) {
8907 - header('Content-Type: application/json');
8908 - echo json_encode(array(
8909 - 'error' => true,
8910 - 'error_message' => $regular_response['error'],
8911 - 'error_code' => $regular_response['error_code'] ?? 'api_error',
8912 - 'text' => $regular_response['error'],
8913 - 'message' => $regular_response['error'],
8914 - ));
8915 - return true;
8916 - }
8917 -
8918 - $fallback_message = (string) $regular_response;
8919 - if (!empty($fallback_message) && !empty($session_id)) {
8920 - $this->mxchat_save_chat_message($session_id, 'bot', $fallback_message);
8921 - }
8922 - $response_data = array(
8923 - 'text' => $fallback_message,
8924 - 'html' => '',
8925 - 'session_id' => $session_id,
8926 - );
8927 - if ($testing_data !== null) {
8928 - $response_data['testing_data'] = $testing_data;
8929 - }
8930 - header('Content-Type: application/json');
8931 - echo json_encode($response_data);
8932 - return true;
8933 -}
8934 -
8935 -/**
8936 - * Resolve custom (OpenAI-compatible) provider config from settings.
8937 - * Returns ['base_url','api_key','model','auth_scheme','api_version','chat_url','headers'].
8938 - */
8939 -private function mxchat_resolve_custom_provider() {
8940 - $base_url = isset($this->options['custom_provider_base_url']) ? rtrim(trim((string) $this->options['custom_provider_base_url']), '/') : '';
8941 - $api_key = isset($this->options['custom_provider_api_key']) ? trim((string) $this->options['custom_provider_api_key']) : '';
8942 - $model = isset($this->options['custom_provider_model']) ? trim((string) $this->options['custom_provider_model']) : '';
8943 - $auth_scheme = isset($this->options['custom_provider_auth_scheme']) ? $this->options['custom_provider_auth_scheme'] : 'bearer';
8944 - $api_version = isset($this->options['custom_provider_api_version']) ? trim((string) $this->options['custom_provider_api_version']) : '';
8945 -
8946 - $chat_url = $base_url . '/chat/completions';
8947 - if (!empty($api_version)) {
8948 - $chat_url .= (strpos($chat_url, '?') === false ? '?' : '&') . 'api-version=' . rawurlencode($api_version);
8949 - }
8950 -
8951 - $headers = array('Content-Type: application/json');
8952 - if (!empty($api_key)) {
8953 - if ($auth_scheme === 'api-key') {
8954 - $headers[] = 'api-key: ' . $api_key;
8955 - } else {
8956 - $headers[] = 'Authorization: Bearer ' . $api_key;
8957 - }
8958 - }
8959 -
8960 - return array(
8961 - 'base_url' => $base_url,
8962 - 'api_key' => $api_key,
8963 - 'model' => $model !== '' ? $model : 'default',
8964 - 'auth_scheme' => $auth_scheme,
8965 - 'api_version' => $api_version,
8966 - 'chat_url' => $chat_url,
8967 - 'headers' => $headers,
8968 - );
8969 -}
8970 -
8971 -/**
8972 - * Streaming chat completion against an OpenAI-compatible custom provider
8973 - * (Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.).
8974 - * Mirrors mxchat_generate_response_openai_stream but with parameterized URL/auth/model.
8975 - */
8976 -private function mxchat_generate_response_custom_stream($selected_model, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
8977 - try {
8978 - $cfg = $this->mxchat_resolve_custom_provider();
8979 - if (empty($cfg['base_url'])) {
8980 - return array('error' => esc_html__('Custom provider Base URL is not configured.', 'mxchat'), 'error_code' => 'missing_custom_provider_base_url');
8981 - }
8982 -
8983 - $bot_id = $this->get_current_bot_id($session_id);
8984 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
8985 - if (!is_array($conversation_history)) {
8986 - $conversation_history = array();
8987 - }
8988 -
8989 - $formatted_conversation = array();
8990 - $formatted_conversation[] = array(
8991 - 'role' => 'system',
8992 - 'content' => $system_prompt_instructions . ' ' . $relevant_content,
8993 - );
8994 - foreach ($conversation_history as $message) {
8995 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
8996 - $role = $message['role'];
8997 - if ($role === 'bot' || $role === 'agent') { $role = 'assistant'; }
8998 - if (!in_array($role, array('system', 'assistant', 'user', 'function', 'tool'))) { $role = 'user'; }
8999 - $formatted_conversation[] = array('role' => $role, 'content' => $message['content']);
9000 - }
9001 - }
9002 -
9003 - if (headers_sent() || !function_exists('curl_init')) {
9004 - // No streaming capability — fall through to non-stream wrapper
9005 - $regular = $this->mxchat_generate_response_custom($selected_model, $conversation_history, $relevant_content);
9006 - if (!empty($regular) && !empty($session_id) && is_string($regular)) {
9007 - $this->mxchat_save_chat_message($session_id, 'bot', $regular);
9008 - }
9009 - $response_data = array('text' => is_string($regular) ? $regular : '', 'html' => '', 'session_id' => $session_id);
9010 - if ($testing_data !== null) { $response_data['testing_data'] = $testing_data; }
9011 - header('Content-Type: application/json');
9012 - echo json_encode($response_data);
9013 - return true;
9014 - }
9015 -
9016 - $request_body = array(
9017 - 'model' => $cfg['model'],
9018 - 'messages' => $formatted_conversation,
9019 - 'stream' => true,
9020 - );
9021 - $body = json_encode($request_body);
9022 -
9023 - // V2 retry-on-initial-connect: setup_streaming_headers is lazy-fired in WRITEFUNCTION.
9024 -
9025 - $captured_status_code = 0;
9026 - $captured_body_pre_stream = '';
9027 - $full_response = '';
9028 - $stream_started = false;
9029 - $buffer = '';
9030 - $errno = 0;
9031 - $http_code = 0;
9032 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
9033 - $backoff_ms = array(0, 750, 2000);
9034 -
9035 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
9036 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
9037 - usleep($backoff_ms[$attempt] * 1000);
9038 - }
9039 -
9040 - $captured_status_code = 0;
9041 - $captured_body_pre_stream = '';
9042 - $full_response = '';
9043 - $stream_started = false;
9044 - $buffer = '';
9045 -
9046 - $ch = curl_init();
9047 - curl_setopt($ch, CURLOPT_URL, $cfg['chat_url']);
9048 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
9049 - curl_setopt($ch, CURLOPT_POST, true);
9050 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
9051 - curl_setopt($ch, CURLOPT_HTTPHEADER, $cfg['headers']);
9052 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
9053 - curl_setopt($ch, CURLOPT_TIMEOUT, 120);
9054 -
9055 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
9056 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
9057 - $captured_status_code = (int) $m[1];
9058 - }
9059 - return strlen($header);
9060 - });
9061 -
9062 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
9063 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
9064 - $captured_body_pre_stream .= $data;
9065 - return strlen($data);
9066 - }
9067 -
9068 - if (!$this->streaming_headers_sent) {
9069 - $this->setup_streaming_headers();
9070 - }
9071 -
9072 - if (!$stream_started && $testing_data !== null) {
9073 - echo "data: " . json_encode(array('testing_data' => $testing_data)) . "\n\n";
9074 - flush();
9075 - $stream_started = true;
9076 - }
9077 - $buffer .= $data;
9078 - $lines = explode("\n", $buffer);
9079 - $buffer = array_pop($lines);
9080 - foreach ($lines as $line) {
9081 - if (trim($line) === '') { continue; }
9082 - if (strpos($line, 'data: ') !== 0) { continue; }
9083 - $json_str = substr($line, 6);
9084 - if (trim($json_str) === '[DONE]') {
9085 - echo "data: [DONE]\n\n";
9086 - flush();
9087 - continue;
9088 - }
9089 - $json = json_decode(trim($json_str), true);
9090 - if ($json && isset($json['choices'][0]['delta']['content'])) {
9091 - $content = $json['choices'][0]['delta']['content'];
9092 - $full_response .= $content;
9093 - echo "data: " . json_encode(array('content' => $content)) . "\n\n";
9094 - flush();
9095 - }
9096 - }
9097 - return strlen($data);
9098 - });
9099 -
9100 - $response = curl_exec($ch);
9101 - $errno = curl_errno($ch);
9102 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
9103 - curl_close($ch);
9104 -
9105 - if (!$errno && $http_code === 200) {
9106 - break;
9107 - }
9108 -
9109 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'openai', $errno);
9110 - $can_retry = !$this->streaming_headers_sent
9111 - && ($attempt + 1) < $max_attempts
9112 - && $is_transient;
9113 -
9114 - if (defined('WP_DEBUG') && WP_DEBUG) {
9115 - error_log(sprintf(
9116 - '[MxChat] custom_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
9117 - $attempt + 1, $max_attempts, $http_code, $errno,
9118 - $is_transient ? 'yes' : 'no',
9119 - $can_retry ? 'Retrying.' : 'Giving up.'
9120 - ));
9121 - }
9122 -
9123 - if (!$can_retry) {
9124 - break;
9125 - }
9126 - }
9127 -
9128 - if (!$errno && $http_code === 200) {
9129 - if (!empty($full_response) && !empty($session_id)) {
9130 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response);
9131 - }
9132 - return true;
9133 - }
9134 -
9135 - return $this->mxchat_stream_emit_fallback(
9136 - 'openai',
9137 - $this->mxchat_generate_response_custom($selected_model, $conversation_history, $relevant_content),
9138 - $session_id,
9139 - $testing_data
9140 - );
9141 -
9142 - } catch (Exception $e) {
9143 - return array('error' => sprintf(esc_html__('Custom provider error: %s', 'mxchat'), $e->getMessage()), 'error_code' => 'custom_provider_exception');
9144 - }
9145 -}
9146 -
9147 -/**
9148 - * Non-streaming chat completion against a custom OpenAI-compatible provider.
9149 - * Returns string content on success, array['error'=>...] on failure.
9150 - */
9151 -private function mxchat_generate_response_custom($selected_model, $conversation_history, $relevant_content) {
9152 - $cfg = $this->mxchat_resolve_custom_provider();
9153 - if (empty($cfg['base_url'])) {
9154 - return array('error' => esc_html__('Custom provider Base URL is not configured.', 'mxchat'), 'error_code' => 'missing_custom_provider_base_url');
9155 - }
9156 -
9157 - $bot_id = $this->get_current_bot_id(null);
9158 - $system_prompt_instructions = $this->get_system_instructions($bot_id, null);
9159 - if (!is_array($conversation_history)) {
9160 - $conversation_history = array();
9161 - }
9162 -
9163 - $messages = array(array(
9164 - 'role' => 'system',
9165 - 'content' => $system_prompt_instructions . ' ' . $relevant_content,
9166 - ));
9167 - foreach ($conversation_history as $message) {
9168 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
9169 - $role = $message['role'];
9170 - if ($role === 'bot' || $role === 'agent') { $role = 'assistant'; }
9171 - if (!in_array($role, array('system', 'assistant', 'user', 'function', 'tool'))) { $role = 'user'; }
9172 - $messages[] = array('role' => $role, 'content' => $message['content']);
9173 - }
9174 - }
9175 -
9176 - $headers_assoc = array('Content-Type' => 'application/json');
9177 - if (!empty($cfg['api_key'])) {
9178 - if ($cfg['auth_scheme'] === 'api-key') {
9179 - $headers_assoc['api-key'] = $cfg['api_key'];
9180 - } else {
9181 - $headers_assoc['Authorization'] = 'Bearer ' . $cfg['api_key'];
9182 - }
9183 - }
9184 -
9185 - $response = $this->mxchat_provider_call_with_retry($cfg['chat_url'], array(
9186 - 'headers' => $headers_assoc,
9187 - 'body' => wp_json_encode(array(
9188 - 'model' => $cfg['model'],
9189 - 'messages' => $messages,
9190 - )),
9191 - 'timeout' => 120,
9192 - ), 'openai');
9193 -
9194 - if (is_wp_error($response)) {
9195 - return array('error' => sprintf(esc_html__('Custom provider request failed: %s', 'mxchat'), $response->get_error_message()), 'error_code' => 'custom_provider_network_error');
9196 - }
9197 - $code = (int) wp_remote_retrieve_response_code($response);
9198 - if ($code < 200 || $code >= 300) {
9199 - return array('error' => sprintf(esc_html__('Custom provider returned HTTP %d.', 'mxchat'), $code), 'error_code' => 'custom_provider_http_error');
9200 - }
9201 - $body = json_decode(wp_remote_retrieve_body($response), true);
9202 - if (isset($body['choices'][0]['message']['content'])) {
9203 - return (string) $body['choices'][0]['message']['content'];
9204 - }
9205 - return array('error' => esc_html__('Custom provider returned an unexpected response shape.', 'mxchat'), 'error_code' => 'custom_provider_response_shape');
9206 -}
9207 -
9208 -/**
9209 - * Generate response using OpenAI Responses API with web search tool
9210 - * This uses the newer Responses API which supports web search functionality
9211 - */
9212 -private function mxchat_generate_response_openai_web_search($selected_model, $api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null, $streaming = false) {
9213 - try {
9214 - $bot_id = $this->get_current_bot_id($session_id);
9215 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
9216 -
9217 - if (!is_array($conversation_history)) {
9218 - $conversation_history = array();
9219 - }
9220 -
9221 - // Build the input for Responses API
9222 - // The Responses API uses a different format - we need to construct the input properly
9223 - $input_parts = [];
9224 -
9225 - // Add system instructions as context
9226 - $system_context = $system_prompt_instructions . "\n\n" . $relevant_content;
9227 -
9228 - // Build conversation as input items for Responses API
9229 - foreach ($conversation_history as $message) {
9230 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
9231 - $role = $message['role'];
9232 - if ($role === 'bot' || $role === 'agent') {
9233 - $role = 'assistant';
9234 - }
9235 - if (!in_array($role, ['assistant', 'user'])) {
9236 - $role = 'user';
9237 - }
9238 - $input_parts[] = [
9239 - 'type' => 'message',
9240 - 'role' => $role,
9241 - 'content' => $message['content']
9242 - ];
9243 - }
9244 - }
9245 -
9246 - // Build request body for Responses API
9247 - $request_body = [
9248 - 'model' => $selected_model,
9249 - 'input' => $input_parts,
9250 - 'instructions' => $system_context,
9251 - 'stream' => $streaming
9252 - ];
9253 -
9254 - // Only add web search tool if web search is enabled in settings
9255 - $web_search_enabled = isset($this->options['enable_web_search']) && $this->options['enable_web_search'] === 'on';
9256 - if ($web_search_enabled) {
9257 - $request_body['tools'] = [
9258 - ['type' => 'web_search']
9259 - ];
9260 - }
9261 -
9262 - // reasoning.effort — sourced from the core model catalog (plan-dcb71c),
9263 - // 'websearch' surface; frozen inline ladder in mxchat_reasoning_effort_fallback().
9264 - $effort = $this->mxchat_reasoning_effort_for($selected_model, 'websearch');
9265 - if ($effort !== null) {
9266 - $request_body['reasoning'] = ['effort' => $effort];
9267 - }
9268 -
9269 - //error_log("MXCHAT WEB SEARCH: Request body: " . json_encode($request_body));
9270 -
9271 - if ($streaming) {
9272 - return $this->mxchat_web_search_streaming_response($request_body, $api_key, $session_id, $testing_data);
9273 - } else {
9274 - return $this->mxchat_web_search_non_streaming_response($request_body, $api_key, $session_id, $testing_data);
9275 - }
9276 -
9277 - } catch (Exception $e) {
9278 - //error_log("MXCHAT WEB SEARCH ERROR: " . $e->getMessage());
9279 - return [
9280 - 'error' => sprintf(esc_html__('Web search error: %s', 'mxchat'), esc_html($e->getMessage())),
9281 - 'error_code' => 'web_search_exception'
9282 - ];
9283 - }
9284 -}
9285 -
9286 -/**
9287 - * Handle non-streaming web search response
9288 - */
9289 -private function mxchat_web_search_non_streaming_response($request_body, $api_key, $session_id, $testing_data) {
9290 - $request_body['stream'] = false;
9291 -
9292 - $response = $this->mxchat_provider_call_with_retry('https://api.openai.com/v1/responses', array(
9293 - 'headers' => array(
9294 - 'Authorization' => 'Bearer ' . $api_key,
9295 - 'Content-Type' => 'application/json'
9296 - ),
9297 - 'body' => json_encode($request_body),
9298 - 'timeout' => 90
9299 - ), 'openai');
9300 -
9301 - if (is_wp_error($response)) {
9302 - //error_log("MXCHAT WEB SEARCH ERROR: WP Error: " . $response->get_error_message());
9303 - return [
9304 - 'error' => esc_html__('Failed to connect to OpenAI web search API', 'mxchat'),
9305 - 'error_code' => 'web_search_connection_error'
9306 - ];
9307 - }
9308 -
9309 - $response_code = wp_remote_retrieve_response_code($response);
9310 - $response_body = wp_remote_retrieve_body($response);
9311 -
9312 - //error_log("MXCHAT WEB SEARCH: Response code: " . $response_code);
9313 - //error_log("MXCHAT WEB SEARCH: Response body (first 2000): " . substr($response_body, 0, 2000));
9314 -
9315 - if ($response_code !== 200) {
9316 - $error_data = json_decode($response_body, true);
9317 - $error_message = $error_data['error']['message'] ?? 'Unknown API error';
9318 - return [
9319 - 'error' => sprintf(esc_html__('OpenAI API error: %s', 'mxchat'), esc_html($error_message)),
9320 - 'error_code' => 'web_search_api_error'
9321 - ];
9322 - }
9323 -
9324 - $result = json_decode($response_body, true);
9325 -
9326 - if (json_last_error() !== JSON_ERROR_NONE) {
9327 - return [
9328 - 'error' => esc_html__('Invalid response from OpenAI', 'mxchat'),
9329 - 'error_code' => 'web_search_json_error'
9330 - ];
9331 - }
9332 -
9333 - // Extract the response text and citations from Responses API format
9334 - $output_text = '';
9335 - $citations = [];
9336 -
9337 - if (isset($result['output'])) {
9338 - foreach ($result['output'] as $output_item) {
9339 - if ($output_item['type'] === 'message' && isset($output_item['content'])) {
9340 - foreach ($output_item['content'] as $content_item) {
9341 - if ($content_item['type'] === 'output_text') {
9342 - $output_text .= $content_item['text'];
9343 -
9344 - // Extract citations/annotations
9345 - if (isset($content_item['annotations'])) {
9346 - foreach ($content_item['annotations'] as $annotation) {
9347 - if ($annotation['type'] === 'url_citation') {
9348 - $citations[] = [
9349 - 'url' => $annotation['url'],
9350 - 'title' => $annotation['title'] ?? ''
9351 - ];
9352 - }
9353 - }
9354 - }
9355 - }
9356 - }
9357 - }
9358 - }
9359 - }
9360 -
9361 - // If we have citations, append them to the response
9362 - if (!empty($citations)) {
9363 - $output_text .= "\n\n**Sources:**\n";
9364 - $seen_urls = [];
9365 - foreach ($citations as $citation) {
9366 - if (!in_array($citation['url'], $seen_urls)) {
9367 - $seen_urls[] = $citation['url'];
9368 - $title = !empty($citation['title']) ? $citation['title'] : $citation['url'];
9369 - $output_text .= "- [" . $title . "](" . $citation['url'] . ")\n";
9370 - }
9371 - }
9372 - }
9373 -
9374 - // Transcript save is handled by the main handler (mxchat_handle_chat_request)
9375 - // which includes rag_context for the "sources" link in transcripts.
9376 -
9377 - return $output_text;
9378 -}
9379 -
9380 -/**
9381 - * Handle streaming web search response using Responses API
9382 - */
9383 -private function mxchat_web_search_streaming_response($request_body, $api_key, $session_id, $testing_data) {
9384 - $request_body['stream'] = true;
9385 -
9386 - // Check if we can stream
9387 - if (headers_sent() || !function_exists('curl_init')) {
9388 - // Fallback to non-streaming
9389 - return $this->mxchat_web_search_non_streaming_response($request_body, $api_key, $session_id, $testing_data);
9390 - }
9391 -
9392 - // Setup streaming headers
9393 - $this->setup_streaming_headers();
9394 -
9395 - $ch = curl_init();
9396 - curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/responses');
9397 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
9398 - curl_setopt($ch, CURLOPT_POST, true);
9399 - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request_body));
9400 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
9401 - 'Content-Type: application/json',
9402 - 'Authorization: Bearer ' . $api_key
9403 - ));
9404 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
9405 - curl_setopt($ch, CURLOPT_TIMEOUT, 120);
9406 -
9407 - $full_response = '';
9408 - $stream_started = false;
9409 - $buffer = '';
9410 - $citations = [];
9411 -
9412 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$citations, $testing_data) {
9413 - // Send testing data as first event if available
9414 - if (!$stream_started && $testing_data !== null) {
9415 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
9416 - flush();
9417 - $stream_started = true;
9418 - }
9419 -
9420 - $buffer .= $data;
9421 - $lines = explode("\n", $buffer);
9422 - $buffer = array_pop($lines);
9423 -
9424 - foreach ($lines as $line) {
9425 - if (trim($line) === '') continue;
9426 - if (strpos($line, 'data: ') !== 0) continue;
9427 -
9428 - $json_str = substr($line, 6);
9429 -
9430 - if (trim($json_str) === '[DONE]') {
9431 - // Append citations if we have any
9432 - if (!empty($citations)) {
9433 - $citation_text = "\n\n**Sources:**\n";
9434 - $seen_urls = [];
9435 - foreach ($citations as $citation) {
9436 - if (!in_array($citation['url'], $seen_urls)) {
9437 - $seen_urls[] = $citation['url'];
9438 - $title = !empty($citation['title']) ? $citation['title'] : $citation['url'];
9439 - $citation_text .= "- [" . $title . "](" . $citation['url'] . ")\n";
9440 - }
9441 - }
9442 - echo "data: " . json_encode(['content' => $citation_text]) . "\n\n";
9443 - $full_response .= $citation_text;
9444 - flush();
9445 - }
9446 - echo "data: [DONE]\n\n";
9447 - flush();
9448 - continue;
9449 - }
9450 -
9451 - $json = json_decode(trim($json_str), true);
9452 - if (!$json) continue;
9453 -
9454 - // Handle Responses API streaming events
9455 - // The format is different from Chat Completions
9456 - if (isset($json['type'])) {
9457 - switch ($json['type']) {
9458 - case 'response.output_text.delta':
9459 - // Text content delta
9460 - if (isset($json['delta'])) {
9461 - $content = $json['delta'];
9462 - $full_response .= $content;
9463 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
9464 - flush();
9465 - }
9466 - break;
9467 -
9468 - case 'response.output_item.done':
9469 - // Check for citations in completed items
9470 - if (isset($json['item']['content'])) {
9471 - foreach ($json['item']['content'] as $content_item) {
9472 - if (isset($content_item['annotations'])) {
9473 - foreach ($content_item['annotations'] as $annotation) {
9474 - if ($annotation['type'] === 'url_citation') {
9475 - $citations[] = [
9476 - 'url' => $annotation['url'],
9477 - 'title' => $annotation['title'] ?? ''
9478 - ];
9479 - }
9480 - }
9481 - }
9482 - }
9483 - }
9484 - break;
9485 - }
9486 - }
9487 - }
9488 -
9489 - return strlen($data);
9490 - });
9491 -
9492 - $response = curl_exec($ch);
9493 - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
9494 -
9495 - if (curl_errno($ch) || $http_code !== 200) {
9496 - $curl_error = curl_error($ch);
9497 - curl_close($ch);
9498 -
9499 - //error_log("MXCHAT WEB SEARCH STREAM ERROR: HTTP $http_code, cURL error: $curl_error");
9500 -
9501 - return $this->mxchat_stream_emit_fallback(
9502 - 'web_search',
9503 - $this->mxchat_web_search_non_streaming_response($request_body, $api_key, $session_id, $testing_data),
9504 - $session_id,
9505 - $testing_data
9506 - );
9507 - }
9508 -
9509 - curl_close($ch);
9510 -
9511 - // Save the complete response with RAG context so the "sources" link
9512 - // appears in transcripts — mirrors the pattern used by Claude/OpenAI streaming.
9513 - if (!empty($full_response) && !empty($session_id)) {
9514 - $rag_context_for_storage = null;
9515 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
9516 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
9517 -
9518 - if ($has_rag_data || $has_action_data) {
9519 - $rag_context_for_storage = [];
9520 -
9521 - if ($has_rag_data) {
9522 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
9523 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
9524 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
9525 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
9526 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
9527 - }
9528 -
9529 - if ($has_action_data) {
9530 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
9531 - }
9532 - }
9533 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
9534 - }
9535 -
9536 - return true;
9537 -}
9538 -
9539 -private function mxchat_generate_response_claude_stream($selected_model, $claude_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
9540 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
9541 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
9542 - if ($selected_model === 'claude-opus-4-20250514') { $selected_model = 'claude-opus-4-8'; }
9543 - elseif ($selected_model === 'claude-sonnet-4-20250514') { $selected_model = 'claude-sonnet-4-6'; }
9544 - try {
9545 - // Get bot ID from session or request
9546 - $bot_id = $this->get_current_bot_id($session_id);
9547 -
9548 - // Get system prompt instructions using centralized function
9549 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
9550 - // Ensure conversation_history is an array
9551 - if (!is_array($conversation_history)) {
9552 - $conversation_history = array();
9553 - }
9554 -
9555 - // Clean and validate conversation history
9556 - foreach ($conversation_history as &$message) {
9557 - // Convert bot and agent roles to assistant
9558 - if ($message['role'] === 'bot' || $message['role'] === 'agent') {
9559 - $message['role'] = 'assistant';
9560 - }
9561 -
9562 - // Remove unsupported roles - Claude only supports 'assistant' and 'user'
9563 - if (!in_array($message['role'], ['assistant', 'user'])) {
9564 - $message['role'] = 'user';
9565 - }
9566 -
9567 - // Ensure content field exists
9568 - if (!isset($message['content']) || empty($message['content'])) {
9569 - $message['content'] = '';
9570 - }
9571 -
9572 - // Remove any unsupported fields
9573 - $message = array_intersect_key($message, array_flip(['role', 'content']));
9574 - }
9575 -
9576 - // Add relevant content as the latest user message
9577 - $conversation_history[] = [
9578 - 'role' => 'user',
9579 - 'content' => $relevant_content
9580 - ];
9581 -
9582 - // Prepare the request body with stream: true
9583 - $payload = [
9584 - 'model' => $selected_model,
9585 - 'messages' => $conversation_history,
9586 - 'max_tokens' => 1000,
9587 - 'temperature' => 0.8,
9588 - 'system' => $system_prompt_instructions,
9589 - 'stream' => true
9590 - ];
9591 - if ($this->mxchat_claude_omits_temperature($selected_model)) { unset($payload['temperature']); }
9592 - $body = json_encode($payload);
9593 -
9594 - // Check if we can actually stream (headers not sent, etc.)
9595 - if (headers_sent() || !function_exists('curl_init')) {
9596 - // Fallback to regular response with testing data
9597 - //error_log("MxChat: Streaming not possible, falling back to regular response");
9598 - $regular_response = $this->mxchat_generate_response_claude(
9599 - $selected_model,
9600 - $claude_api_key,
9601 - array_slice($conversation_history, 0, -1), // Remove the added content
9602 - $relevant_content,
9603 - $session_id
9604 - );
9605 -
9606 - // Save bot response to transcript
9607 - if (!empty($regular_response) && !empty($session_id)) {
9608 - $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
9609 - }
9610 -
9611 - // Return as JSON with testing data
9612 - $response_data = [
9613 - 'text' => $regular_response,
9614 - 'html' => '',
9615 - 'session_id' => $session_id
9616 - ];
9617 -
9618 - if ($testing_data !== null) {
9619 - $response_data['testing_data'] = $testing_data;
9620 - //error_log("MxChat Testing: Added testing data to Claude fallback response");
9621 - }
9622 -
9623 - // Clear any streaming headers and send JSON
9624 - if (headers_sent() === false) {
9625 - header('Content-Type: application/json');
9626 - }
9627 - echo json_encode($response_data);
9628 - return true; // Indicate we handled the response
9629 - }
9630 -
9631 - // V2 retry-on-initial-connect: setup_streaming_headers is lazy-fired in WRITEFUNCTION.
9632 -
9633 - $captured_status_code = 0;
9634 - $captured_body_pre_stream = '';
9635 - $full_response = '';
9636 - $stream_started = false;
9637 - $buffer = '';
9638 - $errno = 0;
9639 - $http_code = 0;
9640 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
9641 - $backoff_ms = array(0, 750, 2000);
9642 -
9643 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
9644 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
9645 - usleep($backoff_ms[$attempt] * 1000);
9646 - }
9647 -
9648 - $captured_status_code = 0;
9649 - $captured_body_pre_stream = '';
9650 - $full_response = '';
9651 - $stream_started = false;
9652 - $buffer = '';
9653 -
9654 - $ch = curl_init();
9655 - curl_setopt($ch, CURLOPT_URL, 'https://api.anthropic.com/v1/messages');
9656 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
9657 - curl_setopt($ch, CURLOPT_POST, true);
9658 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
9659 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
9660 - 'Content-Type: application/json',
9661 - 'x-api-key: ' . $claude_api_key,
9662 - 'anthropic-version: 2023-06-01'
9663 - ));
9664 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
9665 - curl_setopt($ch, CURLOPT_TIMEOUT, 60);
9666 -
9667 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
9668 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
9669 - $captured_status_code = (int) $m[1];
9670 - }
9671 - return strlen($header);
9672 - });
9673 -
9674 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
9675 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
9676 - $captured_body_pre_stream .= $data;
9677 - return strlen($data);
9678 - }
9679 -
9680 - if (!$this->streaming_headers_sent) {
9681 - $this->setup_streaming_headers();
9682 - }
9683 -
9684 - if (!$stream_started && $testing_data !== null) {
9685 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
9686 - flush();
9687 - $stream_started = true;
9688 - }
9689 -
9690 - $buffer .= $data;
9691 - $lines = explode("\n", $buffer);
9692 - $buffer = array_pop($lines);
9693 -
9694 - foreach ($lines as $line) {
9695 - if (trim($line) === '') {
9696 - continue;
9697 - }
9698 -
9699 - if (strpos($line, 'event: ') === 0) {
9700 - continue;
9701 - }
9702 -
9703 - if (strpos($line, 'data: ') === 0) {
9704 - $json_str = substr($line, 6);
9705 -
9706 - $json = json_decode(trim($json_str), true);
9707 - if (json_last_error() !== JSON_ERROR_NONE) {
9708 - continue;
9709 - }
9710 -
9711 - if (isset($json['type'])) {
9712 - switch ($json['type']) {
9713 - case 'content_block_delta':
9714 - if (isset($json['delta']['text'])) {
9715 - $content = $json['delta']['text'];
9716 - $full_response .= $content;
9717 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
9718 - flush();
9719 - }
9720 - break;
9721 -
9722 - case 'message_stop':
9723 - echo "data: [DONE]\n\n";
9724 - flush();
9725 - break;
9726 -
9727 - case 'error':
9728 - echo "data: " . json_encode(['error' => $json['error']['message'] ?? 'Unknown error']) . "\n\n";
9729 - flush();
9730 - break;
9731 - }
9732 - }
9733 - }
9734 - }
9735 -
9736 - return strlen($data);
9737 - });
9738 -
9739 - $response = curl_exec($ch);
9740 - $errno = curl_errno($ch);
9741 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
9742 - curl_close($ch);
9743 -
9744 - if (!$errno && $http_code === 200) {
9745 - break;
9746 - }
9747 -
9748 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'anthropic', $errno);
9749 - $can_retry = !$this->streaming_headers_sent
9750 - && ($attempt + 1) < $max_attempts
9751 - && $is_transient;
9752 -
9753 - if (defined('WP_DEBUG') && WP_DEBUG) {
9754 - error_log(sprintf(
9755 - '[MxChat] claude_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
9756 - $attempt + 1, $max_attempts, $http_code, $errno,
9757 - $is_transient ? 'yes' : 'no',
9758 - $can_retry ? 'Retrying.' : 'Giving up.'
9759 - ));
9760 - }
9761 -
9762 - if (!$can_retry) {
9763 - break;
9764 - }
9765 - }
9766 -
9767 - if ($errno || $http_code !== 200) {
9768 - return $this->mxchat_stream_emit_fallback(
9769 - 'anthropic',
9770 - $this->mxchat_generate_response_claude($selected_model, $claude_api_key, array_slice($conversation_history, 0, -1), $relevant_content, $session_id),
9771 - $session_id,
9772 - $testing_data
9773 - );
9774 - }
9775 -
9776 - // Save the complete response to maintain chat persistence
9777 - if (!empty($full_response) && !empty($session_id)) {
9778 - // Prepare RAG context for streaming response
9779 - $rag_context_for_storage = null;
9780 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
9781 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
9782 -
9783 - if ($has_rag_data || $has_action_data) {
9784 - $rag_context_for_storage = [];
9785 -
9786 - if ($has_rag_data) {
9787 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
9788 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
9789 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
9790 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
9791 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
9792 - }
9793 -
9794 - if ($has_action_data) {
9795 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
9796 - }
9797 - }
9798 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
9799 - }
9800 -
9801 - return true; // Indicate streaming completed successfully
9802 -
9803 - } catch (Exception $e) {
9804 - return $this->mxchat_stream_emit_fallback(
9805 - 'anthropic',
9806 - $this->mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content, $session_id),
9807 - $session_id,
9808 - $testing_data
9809 - );
9810 - }
9811 -}
9812 -private function mxchat_generate_response_xai_stream($selected_model, $xai_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
9813 - try {
9814 - // Get bot ID from session or request
9815 - $bot_id = $this->get_current_bot_id($session_id);
9816 -
9817 - // Get system prompt instructions using centralized function
9818 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
9819 -
9820 - // Ensure conversation_history is an array
9821 - if (!is_array($conversation_history)) {
9822 - $conversation_history = array();
9823 - }
9824 -
9825 - // Format conversation history for X.AI (same as OpenAI format)
9826 - $formatted_conversation = array();
9827 -
9828 - $formatted_conversation[] = array(
9829 - 'role' => 'system',
9830 - 'content' => $system_prompt_instructions . " " . $relevant_content
9831 - );
9832 -
9833 - foreach ($conversation_history as $message) {
9834 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
9835 - $role = $message['role'];
9836 - if ($role === 'bot' || $role === 'agent') {
9837 - $role = 'assistant';
9838 - }
9839 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
9840 - $role = 'user';
9841 - }
9842 - $formatted_conversation[] = array(
9843 - 'role' => $role,
9844 - 'content' => $message['content']
9845 - );
9846 - }
9847 - }
9848 -
9849 - // Check if we can actually stream
9850 - if (headers_sent() || !function_exists('curl_init')) {
9851 - // Fallback to regular response with testing data
9852 - //error_log("MxChat: X.AI streaming not possible, falling back to regular response");
9853 - $regular_response = $this->mxchat_generate_response_xai(
9854 - $selected_model,
9855 - $xai_api_key,
9856 - $conversation_history,
9857 - $relevant_content,
9858 - $session_id
9859 - );
9860 -
9861 - // Save bot response to transcript
9862 - if (!empty($regular_response) && !empty($session_id)) {
9863 - $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
9864 - }
9865 -
9866 - $response_data = [
9867 - 'text' => $regular_response,
9868 - 'html' => '',
9869 - 'session_id' => $session_id
9870 - ];
9871 -
9872 - if ($testing_data !== null) {
9873 - $response_data['testing_data'] = $testing_data;
9874 - //error_log("MxChat Testing: Added testing data to X.AI fallback response");
9875 - }
9876 -
9877 - header('Content-Type: application/json');
9878 - echo json_encode($response_data);
9879 - return true;
9880 - }
9881 -
9882 - // Prepare the request body with stream: true
9883 - $body = json_encode([
9884 - 'model' => $selected_model,
9885 - 'messages' => $formatted_conversation,
9886 - 'temperature' => 0.8,
9887 - 'stream' => true
9888 - ]);
9889 -
9890 - // V2 retry-on-initial-connect: setup_streaming_headers is lazy-fired in WRITEFUNCTION.
9891 -
9892 - $captured_status_code = 0;
9893 - $captured_body_pre_stream = '';
9894 - $full_response = '';
9895 - $stream_started = false;
9896 - $buffer = '';
9897 - $errno = 0;
9898 - $http_code = 0;
9899 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
9900 - $backoff_ms = array(0, 750, 2000);
9901 -
9902 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
9903 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
9904 - usleep($backoff_ms[$attempt] * 1000);
9905 - }
9906 -
9907 - $captured_status_code = 0;
9908 - $captured_body_pre_stream = '';
9909 - $full_response = '';
9910 - $stream_started = false;
9911 - $buffer = '';
9912 -
9913 - $ch = curl_init();
9914 - curl_setopt($ch, CURLOPT_URL, 'https://api.x.ai/v1/chat/completions');
9915 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
9916 - curl_setopt($ch, CURLOPT_POST, true);
9917 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
9918 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
9919 - 'Content-Type: application/json',
9920 - 'Authorization: Bearer ' . $xai_api_key
9921 - ));
9922 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
9923 - curl_setopt($ch, CURLOPT_TIMEOUT, 60);
9924 -
9925 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
9926 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
9927 - $captured_status_code = (int) $m[1];
9928 - }
9929 - return strlen($header);
9930 - });
9931 -
9932 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
9933 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
9934 - $captured_body_pre_stream .= $data;
9935 - return strlen($data);
9936 - }
9937 -
9938 - if (!$this->streaming_headers_sent) {
9939 - $this->setup_streaming_headers();
9940 - }
9941 -
9942 - if (!$stream_started && $testing_data !== null) {
9943 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
9944 - flush();
9945 - $stream_started = true;
9946 - }
9947 -
9948 - $buffer .= $data;
9949 - $lines = explode("\n", $buffer);
9950 - $buffer = array_pop($lines);
9951 -
9952 - foreach ($lines as $line) {
9953 - if (trim($line) === '') {
9954 - continue;
9955 - }
9956 - if (strpos($line, 'data: ') !== 0) {
9957 - continue;
9958 - }
9959 -
9960 - $json_str = substr($line, 6);
9961 -
9962 - if (trim($json_str) === '[DONE]') {
9963 - echo "data: [DONE]\n\n";
9964 - flush();
9965 - continue;
9966 - }
9967 -
9968 - $json = json_decode(trim($json_str), true);
9969 - if ($json && isset($json['choices'][0]['delta']['content'])) {
9970 - $content = $json['choices'][0]['delta']['content'];
9971 - $full_response .= $content;
9972 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
9973 - flush();
9974 - }
9975 - }
9976 -
9977 - return strlen($data);
9978 - });
9979 -
9980 - $response = curl_exec($ch);
9981 - $errno = curl_errno($ch);
9982 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
9983 - curl_close($ch);
9984 -
9985 - if (!$errno && $http_code === 200) {
9986 - break;
9987 - }
9988 -
9989 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'xai', $errno);
9990 - $can_retry = !$this->streaming_headers_sent
9991 - && ($attempt + 1) < $max_attempts
9992 - && $is_transient;
9993 -
9994 - if (defined('WP_DEBUG') && WP_DEBUG) {
9995 - error_log(sprintf(
9996 - '[MxChat] xai_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
9997 - $attempt + 1, $max_attempts, $http_code, $errno,
9998 - $is_transient ? 'yes' : 'no',
9999 - $can_retry ? 'Retrying.' : 'Giving up.'
10000 - ));
10001 - }
10002 -
10003 - if (!$can_retry) {
10004 - break;
10005 - }
10006 - }
10007 -
10008 - if ($errno || $http_code !== 200) {
10009 - return $this->mxchat_stream_emit_fallback(
10010 - 'xai',
10011 - $this->mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content, $session_id),
10012 - $session_id,
10013 - $testing_data
10014 - );
10015 - }
10016 -
10017 - // Save the complete response to maintain chat persistence
10018 - if (!empty($full_response) && !empty($session_id)) {
10019 - // Prepare RAG context for streaming response
10020 - $rag_context_for_storage = null;
10021 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
10022 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
10023 -
10024 - if ($has_rag_data || $has_action_data) {
10025 - $rag_context_for_storage = [];
10026 -
10027 - if ($has_rag_data) {
10028 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
10029 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
10030 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
10031 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
10032 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
10033 - }
10034 -
10035 - if ($has_action_data) {
10036 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
10037 - }
10038 - }
10039 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
10040 - }
10041 -
10042 - return true; // Indicate streaming completed successfully
10043 -
10044 - } catch (Exception $e) {
10045 - return $this->mxchat_stream_emit_fallback(
10046 - 'xai',
10047 - $this->mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content),
10048 - $session_id,
10049 - $testing_data
10050 - );
10051 - }
10052 -}
10053 -private function mxchat_generate_response_deepseek_stream($selected_model, $deepseek_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
10054 - try {
10055 - // Get bot ID from session or request
10056 - $bot_id = $this->get_current_bot_id($session_id);
10057 -
10058 - // Get system prompt instructions using centralized function
10059 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
10060 -
10061 - // Ensure conversation_history is an array
10062 - if (!is_array($conversation_history)) {
10063 - $conversation_history = array();
10064 - }
10065 -
10066 - // Format conversation history for DeepSeek
10067 - $formatted_conversation = array();
10068 -
10069 - $formatted_conversation[] = array(
10070 - 'role' => 'system',
10071 - 'content' => $system_prompt_instructions . " " . $relevant_content
10072 - );
10073 -
10074 - foreach ($conversation_history as $message) {
10075 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
10076 - $role = $message['role'];
10077 - if ($role === 'bot' || $role === 'agent') {
10078 - $role = 'assistant';
10079 - }
10080 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
10081 - $role = 'user';
10082 - }
10083 - $formatted_conversation[] = array(
10084 - 'role' => $role,
10085 - 'content' => $message['content']
10086 - );
10087 - }
10088 - }
10089 -
10090 - // Check if we can actually stream
10091 - if (headers_sent() || !function_exists('curl_init')) {
10092 - // Fallback to regular response with testing data
10093 - //error_log("MxChat: DeepSeek streaming not possible, falling back to regular response");
10094 - $regular_response = $this->mxchat_generate_response_deepseek(
10095 - $selected_model,
10096 - $deepseek_api_key,
10097 - $conversation_history,
10098 - $relevant_content,
10099 - $session_id
10100 - );
10101 -
10102 - // Save bot response to transcript
10103 - if (!empty($regular_response) && !empty($session_id)) {
10104 - $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
10105 - }
10106 -
10107 - $response_data = [
10108 - 'text' => $regular_response,
10109 - 'html' => '',
10110 - 'session_id' => $session_id
10111 - ];
10112 -
10113 - if ($testing_data !== null) {
10114 - $response_data['testing_data'] = $testing_data;
10115 - //error_log("MxChat Testing: Added testing data to DeepSeek fallback response");
10116 - }
10117 -
10118 - header('Content-Type: application/json');
10119 - echo json_encode($response_data);
10120 - return true;
10121 - }
10122 -
10123 - // Prepare the request body with stream: true
10124 - $body = json_encode([
10125 - 'model' => $selected_model,
10126 - 'messages' => $formatted_conversation,
10127 - 'temperature' => 0.8,
10128 - 'stream' => true
10129 - ]);
10130 -
10131 - // V2 retry-on-initial-connect: setup_streaming_headers is lazy-fired in WRITEFUNCTION.
10132 -
10133 - $captured_status_code = 0;
10134 - $captured_body_pre_stream = '';
10135 - $full_response = '';
10136 - $stream_started = false;
10137 - $buffer = '';
10138 - $errno = 0;
10139 - $http_code = 0;
10140 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
10141 - $backoff_ms = array(0, 750, 2000);
10142 -
10143 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
10144 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
10145 - usleep($backoff_ms[$attempt] * 1000);
10146 - }
10147 -
10148 - $captured_status_code = 0;
10149 - $captured_body_pre_stream = '';
10150 - $full_response = '';
10151 - $stream_started = false;
10152 - $buffer = '';
10153 -
10154 - $ch = curl_init();
10155 - curl_setopt($ch, CURLOPT_URL, 'https://api.deepseek.com/v1/chat/completions');
10156 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
10157 - curl_setopt($ch, CURLOPT_POST, true);
10158 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
10159 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
10160 - 'Content-Type: application/json',
10161 - 'Authorization: Bearer ' . $deepseek_api_key
10162 - ));
10163 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
10164 - curl_setopt($ch, CURLOPT_TIMEOUT, 60);
10165 -
10166 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
10167 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
10168 - $captured_status_code = (int) $m[1];
10169 - }
10170 - return strlen($header);
10171 - });
10172 -
10173 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
10174 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
10175 - $captured_body_pre_stream .= $data;
10176 - return strlen($data);
10177 - }
10178 -
10179 - if (!$this->streaming_headers_sent) {
10180 - $this->setup_streaming_headers();
10181 - }
10182 -
10183 - if (!$stream_started && $testing_data !== null) {
10184 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
10185 - flush();
10186 - $stream_started = true;
10187 - }
10188 -
10189 - $buffer .= $data;
10190 - $lines = explode("\n", $buffer);
10191 - $buffer = array_pop($lines);
10192 -
10193 - foreach ($lines as $line) {
10194 - if (trim($line) === '') {
10195 - continue;
10196 - }
10197 - if (strpos($line, 'data: ') !== 0) {
10198 - continue;
10199 - }
10200 -
10201 - $json_str = substr($line, 6);
10202 -
10203 - if (trim($json_str) === '[DONE]') {
10204 - echo "data: [DONE]\n\n";
10205 - flush();
10206 - continue;
10207 - }
10208 -
10209 - $json = json_decode(trim($json_str), true);
10210 - if ($json && isset($json['choices'][0]['delta']['content'])) {
10211 - $content = $json['choices'][0]['delta']['content'];
10212 - $full_response .= $content;
10213 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
10214 - flush();
10215 - }
10216 - }
10217 -
10218 - return strlen($data);
10219 - });
10220 -
10221 - $response = curl_exec($ch);
10222 - $errno = curl_errno($ch);
10223 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
10224 - curl_close($ch);
10225 -
10226 - if (!$errno && $http_code === 200) {
10227 - break;
10228 - }
10229 -
10230 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'openai', $errno);
10231 - $can_retry = !$this->streaming_headers_sent
10232 - && ($attempt + 1) < $max_attempts
10233 - && $is_transient;
10234 -
10235 - if (defined('WP_DEBUG') && WP_DEBUG) {
10236 - error_log(sprintf(
10237 - '[MxChat] deepseek_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
10238 - $attempt + 1, $max_attempts, $http_code, $errno,
10239 - $is_transient ? 'yes' : 'no',
10240 - $can_retry ? 'Retrying.' : 'Giving up.'
10241 - ));
10242 - }
10243 -
10244 - if (!$can_retry) {
10245 - break;
10246 - }
10247 - }
10248 -
10249 - if ($errno || $http_code !== 200) {
10250 - return $this->mxchat_stream_emit_fallback(
10251 - 'openai',
10252 - $this->mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content, $session_id),
10253 - $session_id,
10254 - $testing_data
10255 - );
10256 - }
10257 -
10258 - // Save the complete response to maintain chat persistence
10259 - if (!empty($full_response) && !empty($session_id)) {
10260 - // Prepare RAG context for streaming response
10261 - $rag_context_for_storage = null;
10262 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
10263 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
10264 -
10265 - if ($has_rag_data || $has_action_data) {
10266 - $rag_context_for_storage = [];
10267 -
10268 - if ($has_rag_data) {
10269 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
10270 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
10271 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
10272 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
10273 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
10274 - }
10275 -
10276 - if ($has_action_data) {
10277 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
10278 - }
10279 - }
10280 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $rag_context_for_storage);
10281 - }
10282 -
10283 - return true; // Indicate streaming completed successfully
10284 -
10285 - } catch (Exception $e) {
10286 - return $this->mxchat_stream_emit_fallback(
10287 - 'openai',
10288 - $this->mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content),
10289 - $session_id,
10290 - $testing_data
10291 - );
10292 - }
10293 -}
10294 -
10295 -
10296 -private function mxchat_generate_response_openrouter($selected_model, $openrouter_api_key, $conversation_history, $relevant_content, $session_id = '') {
10297 - try {
10298 - if (!is_array($conversation_history)) {
10299 - $conversation_history = array();
10300 - }
10301 -
10302 - $bot_id = $this->get_current_bot_id($session_id);
10303 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
10304 -
10305 - $formatted_conversation = array();
10306 -
10307 - $formatted_conversation[] = array(
10308 - 'role' => 'system',
10309 - 'content' => $system_prompt_instructions . " " . $relevant_content
10310 - );
10311 -
10312 - foreach ($conversation_history as $message) {
10313 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
10314 - $role = $message['role'];
10315 -
10316 - if ($role === 'bot' || $role === 'agent') {
10317 - $role = 'assistant';
10318 - }
10319 - if (!in_array($role, ['system', 'assistant', 'user'])) {
10320 - $role = 'user';
10321 - }
10322 -
10323 - $formatted_conversation[] = array(
10324 - 'role' => $role,
10325 - 'content' => $message['content']
10326 - );
10327 - }
10328 - }
10329 -
10330 - $body = json_encode([
10331 - 'model' => $selected_model,
10332 - 'messages' => $formatted_conversation,
10333 - 'temperature' => 1,
10334 - ]);
10335 -
10336 - $args = [
10337 - 'body' => $body,
10338 - 'headers' => [
10339 - 'Content-Type' => 'application/json',
10340 - 'Authorization' => 'Bearer ' . $openrouter_api_key,
10341 - 'HTTP-Referer' => home_url(),
10342 - 'X-Title' => get_bloginfo('name'),
10343 - ],
10344 - 'timeout' => 60,
10345 - 'redirection' => 5,
10346 - 'blocking' => true,
10347 - 'httpversion' => '1.0',
10348 - 'sslverify' => true,
10349 - ];
10350 -
10351 - $response = $this->mxchat_provider_call_with_retry('https://openrouter.ai/api/v1/chat/completions', $args, 'openai');
10352 -
10353 - if (is_wp_error($response)) {
10354 - $error_message = $response->get_error_message();
10355 - return [
10356 - 'error' => $this->mxchat_friendly_chat_error(0, $error_message, 'OpenRouter'),
10357 - 'error_code' => 'openrouter_connection_error',
10358 - 'provider' => 'openrouter'
10359 - ];
10360 - }
10361 -
10362 - $status_code = wp_remote_retrieve_response_code($response);
10363 - if ($status_code !== 200) {
10364 - $response_body = wp_remote_retrieve_body($response);
10365 - $decoded_response = json_decode($response_body, true);
10366 -
10367 - $error_message = isset($decoded_response['error']['message'])
10368 - ? $decoded_response['error']['message']
10369 - : 'HTTP Error ' . $status_code;
10370 -
10371 - return [
10372 - 'error' => esc_html__('OpenRouter API error: ', 'mxchat') . esc_html($error_message),
10373 - 'error_code' => 'openrouter_api_error',
10374 - 'provider' => 'openrouter',
10375 - 'status_code' => $status_code
10376 - ];
10377 - }
10378 -
10379 - $response_body = wp_remote_retrieve_body($response);
10380 - $decoded_response = json_decode($response_body, true);
10381 -
10382 - if (isset($decoded_response['choices'][0]['message']['content'])) {
10383 - return trim($decoded_response['choices'][0]['message']['content']);
10384 - } else {
10385 - return [
10386 - 'error' => esc_html__('Unexpected response format from OpenRouter.', 'mxchat'),
10387 - 'error_code' => 'openrouter_response_format_error',
10388 - 'provider' => 'openrouter'
10389 - ];
10390 - }
10391 - } catch (Exception $e) {
10392 - return [
10393 - 'error' => esc_html__('System error when processing OpenRouter request: ', 'mxchat') . esc_html($e->getMessage()),
10394 - 'error_code' => 'openrouter_exception',
10395 - 'provider' => 'openrouter'
10396 - ];
10397 - }
10398 -}
10399 -
10400 -/**
10401 - * Build a chat-bubble-safe message for a non-200 provider (chat) error.
10402 - *
10403 - * Visitors must NEVER see raw API internals (model names, key/billing/quota
10404 - * text). Admins (manage_options) get an actionable hint — and, for the common
10405 - * "model not available on this key" case, a direct pointer to change the model
10406 - * (the site owner can fix it in one click). Anthropic returns model-access as a
10407 - * 4xx with a message like "Claude Fable 5 is not available. Please use Opus 4.8."
10408 - *
10409 - * Provider-agnostic by design (reusable for the xai/gemini/deepseek branches),
10410 - * but Anthropic is the confirmed, reproduced case wired up here (plan 1d3b0f).
10411 - *
10412 - * @param int $http_code HTTP status from the provider.
10413 - * @param string $error_message Raw provider error.message (may be empty).
10414 - * @param string $provider_label Human provider name, e.g. 'Anthropic'.
10415 - * @return string Message safe to render as a chat bubble.
10416 - */
10417 -private function mxchat_friendly_chat_error($http_code, $error_message, $provider_label = '') {
10418 - $raw = trim((string) $error_message);
10419 -
10420 - // Detect a model-access / availability problem the site owner can fix by
10421 - // choosing a different model. (Anthropic phrasing + the common API shapes.)
10422 - $low = strtolower($raw);
10423 - $is_model_access = (strpos($low, 'not available') !== false)
10424 - || (strpos($low, 'does not have access') !== false)
10425 - || (strpos($low, 'do not have access') !== false)
10426 - || (strpos($low, 'does not exist') !== false) // OpenAI: "model `x` does not exist or you do not have access"
10427 - || (strpos($low, 'model_not_found') !== false)
10428 - || (strpos($low, 'not_found_error') !== false)
10429 - || (strpos($low, 'model not found') !== false) // xAI
10430 - || (strpos($low, 'not found') !== false) // Gemini: "models/x is not found for API version ..."
10431 - || (strpos($low, 'permission_denied') !== false) // Gemini gated model
10432 - || (strpos($low, 'permission denied') !== false);
10433 -
10434 - if (current_user_can('manage_options')) {
10435 - if ($is_model_access) {
10436 - return $raw !== ''
10437 - ? sprintf(
10438 - /* translators: %s: raw provider error detail */
10439 - esc_html__('The selected AI model isn\'t available on your API key. Choose another model in MxChat → Settings. (Details: %s)', 'mxchat'),
10440 - $raw
10441 - )
10442 - : esc_html__('The selected AI model isn\'t available on your API key. Choose another model in MxChat → Settings.', 'mxchat');
10443 - }
10444 - return $raw !== ''
10445 - ? sprintf(
10446 - /* translators: 1: provider label, 2: raw provider error detail */
10447 - esc_html__('The AI provider (%1$s) returned an error: %2$s. Check your model and API key in MxChat → Settings.', 'mxchat'),
10448 - $provider_label !== '' ? $provider_label : esc_html__('AI', 'mxchat'),
10449 - $raw
10450 - )
10451 - : esc_html__('The AI provider returned an error. Check your model and API key in MxChat → Settings.', 'mxchat');
10452 - }
10453 -
10454 - // Visitors: friendly, generic, no internals leaked.
10455 - return esc_html__('Sorry, I\'m having trouble responding right now. Please try again in a moment.', 'mxchat');
10456 -}
10457 -
10458 -private function mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content, $session_id = '') {
10459 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
10460 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
10461 - if ($selected_model === 'claude-opus-4-20250514') { $selected_model = 'claude-opus-4-8'; }
10462 - elseif ($selected_model === 'claude-sonnet-4-20250514') { $selected_model = 'claude-sonnet-4-6'; }
10463 -
10464 - // Get bot ID from session or request
10465 - $bot_id = $this->get_current_bot_id($session_id);
10466 -
10467 - // Get system prompt instructions using centralized function
10468 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
10469 -
10470 - // Clean and validate conversation history
10471 - foreach ($conversation_history as &$message) {
10472 - // Convert bot and agent roles to assistant
10473 - if ($message['role'] === 'bot' || $message['role'] === 'agent') {
10474 - $message['role'] = 'assistant';
10475 - }
10476 -
10477 - // Remove unsupported roles - Claude only supports 'assistant' and 'user'
10478 - if (!in_array($message['role'], ['assistant', 'user'])) {
10479 - $message['role'] = 'user';
10480 - }
10481 -
10482 - // Ensure content field exists
10483 - if (!isset($message['content']) || empty($message['content'])) {
10484 - $message['content'] = '';
10485 - }
10486 -
10487 - // Remove any unsupported fields
10488 - $message = array_intersect_key($message, array_flip(['role', 'content']));
10489 - }
10490 -
10491 - // Add relevant content as the latest user message
10492 - $conversation_history[] = [
10493 - 'role' => 'user',
10494 - 'content' => $relevant_content
10495 - ];
10496 -
10497 - // Build request body
10498 - $payload = [
10499 - 'model' => $selected_model,
10500 - 'max_tokens' => 1000,
10501 - 'temperature' => 0.8,
10502 - 'messages' => $conversation_history,
10503 - 'system' => $system_prompt_instructions
10504 - ];
10505 - if ($this->mxchat_claude_omits_temperature($selected_model)) { unset($payload['temperature']); }
10506 - $body = json_encode($payload);
10507 -
10508 - // Set up API request
10509 - $args = [
10510 - 'body' => $body,
10511 - 'headers' => [
10512 - 'Content-Type' => 'application/json',
10513 - 'x-api-key' => $claude_api_key,
10514 - 'anthropic-version' => '2023-06-01'
10515 - ],
10516 - 'timeout' => 60,
10517 - 'redirection' => 5,
10518 - 'blocking' => true,
10519 - 'httpversion' => '1.0',
10520 - 'sslverify' => true,
10521 - ];
10522 -
10523 - // Make API request
10524 - $response = $this->mxchat_provider_call_with_retry('https://api.anthropic.com/v1/messages', $args, 'anthropic');
10525 -
10526 - // Check for WordPress errors
10527 - if (is_wp_error($response)) {
10528 - //error_log("Claude API request error: " . $response->get_error_message());
10529 - return "Sorry, there was an error connecting to the API.";
10530 - }
10531 -
10532 - // Check HTTP response code
10533 - $http_code = wp_remote_retrieve_response_code($response);
10534 - if ($http_code !== 200) {
10535 - $error_body = wp_remote_retrieve_body($response);
10536 - //error_log("Claude API HTTP error: " . $http_code . " - " . $error_body);
10537 -
10538 - // Try to extract error message from response
10539 - $error_data = json_decode($error_body, true);
10540 - $error_message = isset($error_data['error']['message']) ?
10541 - $error_data['error']['message'] :
10542 - "HTTP error " . $http_code;
10543 -
10544 - // Surface an admin-actionable message (and a model-change pointer for the
10545 - // model-access case) without leaking raw API internals to visitors. This
10546 - // is the single chokepoint for BOTH the non-streaming and streaming Claude
10547 - // paths (the stream's non-200 fallback re-enters this method). plan 1d3b0f.
10548 - return $this->mxchat_friendly_chat_error($http_code, $error_message, 'Anthropic');
10549 - }
10550 -
10551 - // Parse response
10552 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
10553 -
10554 - // Check for JSON decode errors
10555 - if (json_last_error() !== JSON_ERROR_NONE) {
10556 - //error_log("Claude API JSON decode error: " . json_last_error_msg());
10557 - return "Sorry, there was an error processing the API response.";
10558 - }
10559 -
10560 - // Extract and validate response content. claude-fable-5 prepends a
10561 - // thinking block to content even with no thinking param — take the first
10562 - // TEXT block rather than content[0].
10563 - if (isset($response_body['content']) && is_array($response_body['content'])) {
10564 - foreach ($response_body['content'] as $block) {
10565 - if (isset($block['type'], $block['text']) && $block['type'] === 'text') {
10566 - return trim($block['text']);
10567 - }
10568 - }
10569 - }
10570 -
10571 - // Log unexpected response format
10572 - //error_log("Claude API unexpected response format: " . print_r($response_body, true));
10573 - return "Sorry, I received an unexpected response format from the API.";
10574 -}
10575 -private function mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content, $session_id = '') {
10576 - try {
10577 - // Ensure conversation_history is an array
10578 - if (!is_array($conversation_history)) {
10579 - $conversation_history = array();
10580 - }
10581 -
10582 - // Get bot ID from session or request. plan eb9c38: resolve the real bot
10583 - // from the session (was hardcoded '' → always default bot on multi-bot
10584 - // installs) and fix the undefined $session_id that fed get_system_instructions.
10585 - $bot_id = $this->get_current_bot_id($session_id);
10586 -
10587 - // Get system prompt instructions using centralized function
10588 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
10589 -
10590 - // Create a new array for the formatted conversation
10591 - $formatted_conversation = array();
10592 -
10593 - // Add system message first
10594 - $formatted_conversation[] = array(
10595 - 'role' => 'system',
10596 - 'content' => $system_prompt_instructions . " " . $relevant_content
10597 - );
10598 -
10599 - // Add the rest of the conversation history
10600 - foreach ($conversation_history as $message) {
10601 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
10602 - $role = $message['role'];
10603 -
10604 - // Convert roles to supported format
10605 - if ($role === 'bot' || $role === 'agent') {
10606 - $role = 'assistant';
10607 - }
10608 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
10609 - $role = 'user';
10610 - }
10611 -
10612 - $formatted_conversation[] = array(
10613 - 'role' => $role,
10614 - 'content' => $message['content']
10615 - );
10616 - }
10617 - }
10618 -
10619 - // Build request body with optimal settings for fast responses
10620 - $request_body = [
10621 - 'model' => $selected_model,
10622 - 'messages' => $formatted_conversation,
10623 - 'temperature' => 1,
10624 - 'stream' => false
10625 - ];
10626 -
10627 - // reasoning_effort — sourced from the core model catalog (plan-dcb71c);
10628 - // frozen inline ladder lives in mxchat_reasoning_effort_fallback().
10629 - $effort = $this->mxchat_reasoning_effort_for($selected_model, 'chat');
10630 - if ($effort !== null) {
10631 - $request_body['reasoning_effort'] = $effort;
10632 - }
10633 -
10634 - $body = json_encode($request_body);
10635 -
10636 - $args = [
10637 - 'body' => $body,
10638 - 'headers' => [
10639 - 'Content-Type' => 'application/json',
10640 - 'Authorization' => 'Bearer ' . $api_key,
10641 - ],
10642 - 'timeout' => 60,
10643 - 'redirection' => 5,
10644 - 'blocking' => true,
10645 - 'httpversion' => '1.0',
10646 - 'sslverify' => true,
10647 - ];
10648 -
10649 - $response = $this->mxchat_provider_call_with_retry('https://api.openai.com/v1/chat/completions', $args, 'openai');
10650 -
10651 - if (is_wp_error($response)) {
10652 - $error_message = $response->get_error_message();
10653 - return [
10654 - 'error' => $this->mxchat_friendly_chat_error(0, $error_message, 'OpenAI'),
10655 - 'error_code' => 'openai_connection_error',
10656 - 'provider' => 'openai'
10657 - ];
10658 - }
10659 -
10660 - $status_code = wp_remote_retrieve_response_code($response);
10661 - if ($status_code !== 200) {
10662 - $response_body = wp_remote_retrieve_body($response);
10663 - $decoded_response = json_decode($response_body, true);
10664 -
10665 - $error_message = isset($decoded_response['error']['message'])
10666 - ? $decoded_response['error']['message']
10667 - : 'HTTP Error ' . $status_code;
10668 -
10669 - $error_type = isset($decoded_response['error']['type'])
10670 - ? $decoded_response['error']['type']
10671 - : 'unknown';
10672 -
10673 - // Handle specific error types
10674 - switch ($error_type) {
10675 - case 'invalid_request_error':
10676 - if (strpos($error_message, 'API key') !== false) {
10677 - return [
10678 - 'error' => esc_html__('Invalid OpenAI API key. Please check your API key configuration.', 'mxchat'),
10679 - 'error_code' => 'openai_invalid_api_key',
10680 - 'provider' => 'openai'
10681 - ];
10682 - }
10683 - break;
10684 -
10685 - case 'authentication_error':
10686 - return [
10687 - 'error' => esc_html__('Authentication failed with OpenAI. Please check your API key.', 'mxchat'),
10688 - 'error_code' => 'openai_auth_error',
10689 - 'provider' => 'openai'
10690 - ];
10691 -
10692 - case 'rate_limit_exceeded':
10693 - return [
10694 - 'error' => esc_html__('OpenAI rate limit exceeded. Please try again later.', 'mxchat'),
10695 - 'error_code' => 'openai_rate_limit',
10696 - 'provider' => 'openai'
10697 - ];
10698 -
10699 - case 'quota_exceeded':
10700 - return [
10701 - 'error' => esc_html__('OpenAI API quota exceeded. Please check your billing details.', 'mxchat'),
10702 - 'error_code' => 'openai_quota_exceeded',
10703 - 'provider' => 'openai'
10704 - ];
10705 - }
10706 -
10707 - // Generic error fallback only — the typed cases above already produce
10708 - // clean messages. Route the raw-tail generic case through the leak-safe
10709 - // helper so visitors never see provider internals. plan 5da59a.
10710 - return [
10711 - 'error' => $this->mxchat_friendly_chat_error($status_code, $error_message, 'OpenAI'),
10712 - 'error_code' => 'openai_api_error',
10713 - 'provider' => 'openai',
10714 - 'status_code' => $status_code
10715 - ];
10716 - }
10717 -
10718 - $response_body = wp_remote_retrieve_body($response);
10719 - $decoded_response = json_decode($response_body, true);
10720 -
10721 - if (isset($decoded_response['choices'][0]['message']['content'])) {
10722 - return trim($decoded_response['choices'][0]['message']['content']);
10723 - } else {
10724 - return [
10725 - 'error' => esc_html__('Unexpected response format from OpenAI.', 'mxchat'),
10726 - 'error_code' => 'openai_response_format_error',
10727 - 'provider' => 'openai'
10728 - ];
10729 - }
10730 - } catch (Exception $e) {
10731 - return [
10732 - 'error' => esc_html__('System error when processing OpenAI request: ', 'mxchat') . esc_html($e->getMessage()),
10733 - 'error_code' => 'openai_exception',
10734 - 'provider' => 'openai'
10735 - ];
10736 - }
10737 -}
10738 -
10739 -private function mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content, $session_id = '') {
10740 - try {
10741 - // Get bot ID from session or request
10742 - $bot_id = $this->get_current_bot_id($session_id);
10743 -
10744 - // Get system prompt instructions using centralized function
10745 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
10746 -
10747 - // Add system prompt to relevant content
10748 - $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
10749 -
10750 - // Prepend system instructions to the conversation history
10751 - array_unshift($conversation_history, [
10752 - 'role' => 'system',
10753 - 'content' => "Here are your instructions: " . $content_with_instructions
10754 - ]);
10755 -
10756 - // Ensure consistency: Replace 'bot' and 'agent' roles with supported values
10757 - foreach ($conversation_history as &$message) {
10758 - if ($message['role'] === 'bot') {
10759 - $message['role'] = 'assistant';
10760 - } elseif ($message['role'] === 'agent') {
10761 - // Tag the message as coming from a live agent
10762 - $message['role'] = 'assistant';
10763 - if (!isset($message['metadata'])) {
10764 - $message['metadata'] = ['source' => 'live_agent'];
10765 - }
10766 - }
10767 -
10768 - // Ensure all roles are valid
10769 - if (!in_array($message['role'], ['system', 'assistant', 'user', 'function', 'tool'])) {
10770 - $message['role'] = 'user'; // Default to 'user'
10771 - }
10772 - }
10773 -
10774 - // Build the request body
10775 - $body = json_encode([
10776 - 'model' => $selected_model,
10777 - 'messages' => $conversation_history,
10778 - 'temperature' => 0.8,
10779 - 'stream' => false
10780 - ]);
10781 -
10782 - // Set up the API request
10783 - $args = [
10784 - 'body' => $body,
10785 - 'headers' => [
10786 - 'Content-Type' => 'application/json',
10787 - 'Authorization' => 'Bearer ' . $xai_api_key,
10788 - ],
10789 - 'timeout' => 60,
10790 - 'redirection' => 5,
10791 - 'blocking' => true,
10792 - 'httpversion' => '1.0',
10793 - 'sslverify' => true,
10794 - ];
10795 -
10796 - // Make the API request
10797 - $response = $this->mxchat_provider_call_with_retry('https://api.x.ai/v1/chat/completions', $args, 'xai');
10798 -
10799 - // Process the response
10800 - if (is_wp_error($response)) {
10801 - $error_message = $response->get_error_message();
10802 - //error_log('X.AI API Error: ' . $error_message);
10803 - return [
10804 - 'error' => $this->mxchat_friendly_chat_error(0, $error_message, 'X.AI'),
10805 - 'error_code' => 'xai_connection_error',
10806 - 'provider' => 'xai'
10807 - ];
10808 - }
10809 -
10810 - $status_code = wp_remote_retrieve_response_code($response);
10811 - if ($status_code !== 200) {
10812 - $response_body = wp_remote_retrieve_body($response);
10813 - $decoded_response = json_decode($response_body, true);
10814 -
10815 - // Log the full response for debugging
10816 - //error_log('X.AI Error Response: ' . print_r($decoded_response, true));
10817 -
10818 - // Extract error message from X.AI's specific format
10819 - $error_message = '';
10820 -
10821 - // Check for direct error string (as seen in your logs)
10822 - if (isset($decoded_response['error']) && is_string($decoded_response['error'])) {
10823 - $error_message = $decoded_response['error'];
10824 - }
10825 - // Check for nested error object (OpenAI style)
10826 - elseif (isset($decoded_response['error']['message'])) {
10827 - $error_message = $decoded_response['error']['message'];
10828 - }
10829 - // Check for top-level message
10830 - elseif (isset($decoded_response['message'])) {
10831 - $error_message = $decoded_response['message'];
10832 - }
10833 - // Fallback
10834 - else {
10835 - $error_message = 'HTTP Error ' . $status_code;
10836 - }
10837 -
10838 - //error_log('X.AI API HTTP Error: ' . $status_code . ' - ' . $error_message);
10839 -
10840 - // Check for API key errors using string matching
10841 - if (stripos($error_message, 'api key') !== false ||
10842 - stripos($error_message, 'incorrect api key') !== false ||
10843 - stripos($error_message, 'invalid api key') !== false) {
10844 - return [
10845 - 'error' => esc_html__('Invalid X.AI API key. Please check your API key configuration.', 'mxchat'),
10846 - 'error_code' => 'xai_invalid_api_key',
10847 - 'provider' => 'xai'
10848 - ];
10849 - }
10850 -
10851 - // Authentication errors
10852 - if ($status_code === 401 || $status_code === 403 ||
10853 - stripos($error_message, 'auth') !== false) {
10854 - return [
10855 - 'error' => esc_html__('Authentication failed with X.AI. Please check your API key.', 'mxchat'),
10856 - 'error_code' => 'xai_auth_error',
10857 - 'provider' => 'xai'
10858 - ];
10859 - }
10860 -
10861 - // Model errors
10862 - if (stripos($error_message, 'model') !== false) {
10863 - return [
10864 - 'error' => esc_html__('Invalid model specified for X.AI. Please check your model configuration.', 'mxchat'),
10865 - 'error_code' => 'xai_invalid_model',
10866 - 'provider' => 'xai'
10867 - ];
10868 - }
10869 -
10870 - // Rate limit errors
10871 - if ($status_code === 429 ||
10872 - stripos($error_message, 'rate') !== false ||
10873 - stripos($error_message, 'limit') !== false) {
10874 - return [
10875 - 'error' => esc_html__('X.AI rate limit exceeded. Please try again later.', 'mxchat'),
10876 - 'error_code' => 'xai_rate_limit',
10877 - 'provider' => 'xai'
10878 - ];
10879 - }
10880 -
10881 - // Quota errors
10882 - if (stripos($error_message, 'quota') !== false ||
10883 - stripos($error_message, 'billing') !== false) {
10884 - return [
10885 - 'error' => esc_html__('X.AI API quota exceeded. Please check your billing details.', 'mxchat'),
10886 - 'error_code' => 'xai_quota_exceeded',
10887 - 'provider' => 'xai'
10888 - ];
10889 - }
10890 -
10891 - // Server errors
10892 - if ($status_code >= 500) {
10893 - return [
10894 - 'error' => esc_html__('X.AI service is currently unavailable. Please try again later.', 'mxchat'),
10895 - 'error_code' => 'xai_service_unavailable',
10896 - 'provider' => 'xai'
10897 - ];
10898 - }
10899 -
10900 - // Generic error fallback. Route the user-facing text through the
10901 - // leak-safe helper (admins get an actionable hint, visitors a generic
10902 - // fallback) instead of echoing raw provider internals. Preserve the
10903 - // structured contract (error_code/provider/status_code) for logging. plan 5da59a.
10904 - return [
10905 - 'error' => $this->mxchat_friendly_chat_error($status_code, $error_message, 'xAI'),
10906 - 'error_code' => 'xai_api_error',
10907 - 'provider' => 'xai',
10908 - 'status_code' => $status_code
10909 - ];
10910 - }
10911 -
10912 - $response_body = wp_remote_retrieve_body($response);
10913 - $decoded_response = json_decode($response_body, true);
10914 -
10915 - if (isset($decoded_response['choices'][0]['message']['content'])) {
10916 - return trim($decoded_response['choices'][0]['message']['content']);
10917 - } else {
10918 - //error_log('X.AI API Response Format Error: ' . print_r($decoded_response, true));
10919 - return [
10920 - 'error' => esc_html__('Unexpected response format from X.AI.', 'mxchat'),
10921 - 'error_code' => 'xai_response_format_error',
10922 - 'provider' => 'xai'
10923 - ];
10924 - }
10925 -} catch (Exception $e) {
10926 - //error_log('X.AI Exception: ' . $e->getMessage());
10927 - return [
10928 - 'error' => esc_html__('System error when processing X.AI request: ', 'mxchat') . esc_html($e->getMessage()),
10929 - 'error_code' => 'xai_exception',
10930 - 'provider' => 'xai'
10931 - ];
10932 -}
10933 -
10934 -
10935 -}
10936 -private function mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content, $session_id = '') {
10937 - try {
10938 - // Ensure conversation_history is an array
10939 - if (!is_array($conversation_history)) {
10940 - $conversation_history = array();
10941 - }
10942 -
10943 - // Get bot ID from session or request
10944 - $bot_id = $this->get_current_bot_id($session_id);
10945 -
10946 - // Get system prompt instructions using centralized function
10947 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
10948 -
10949 - // Create a new array for the formatted conversation
10950 - $formatted_conversation = array();
10951 -
10952 - // Add system message first
10953 - $formatted_conversation[] = array(
10954 - 'role' => 'system',
10955 - 'content' => $system_prompt_instructions . " " . $relevant_content
10956 - );
10957 -
10958 - // Add the rest of the conversation history
10959 - foreach ($conversation_history as $message) {
10960 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
10961 - $role = $message['role'];
10962 -
10963 - // Convert roles to supported format
10964 - if ($role === 'bot' || $role === 'agent') {
10965 - $role = 'assistant';
10966 - }
10967 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
10968 - $role = 'user';
10969 - }
10970 -
10971 - $formatted_conversation[] = array(
10972 - 'role' => $role,
10973 - 'content' => $message['content']
10974 - );
10975 - }
10976 - }
10977 -
10978 - $body = json_encode([
10979 - 'model' => $selected_model,
10980 - 'messages' => $formatted_conversation,
10981 - 'temperature' => 0.8,
10982 - 'stream' => false
10983 - ]);
10984 -
10985 - $args = [
10986 - 'body' => $body,
10987 - 'headers' => [
10988 - 'Content-Type' => 'application/json',
10989 - 'Authorization' => 'Bearer ' . $deepseek_api_key,
10990 - ],
10991 - 'timeout' => 60,
10992 - 'redirection' => 5,
10993 - 'blocking' => true,
10994 - 'httpversion' => '1.0',
10995 - 'sslverify' => true,
10996 - ];
10997 -
10998 - $response = $this->mxchat_provider_call_with_retry('https://api.deepseek.com/v1/chat/completions', $args, 'openai');
10999 -
11000 - if (is_wp_error($response)) {
11001 - $error_message = $response->get_error_message();
11002 - //error_log('DeepSeek API Error: ' . $error_message);
11003 - return [
11004 - 'error' => $this->mxchat_friendly_chat_error(0, $error_message, 'DeepSeek'),
11005 - 'error_code' => 'deepseek_connection_error',
11006 - 'provider' => 'deepseek'
11007 - ];
11008 - }
11009 -
11010 - $status_code = wp_remote_retrieve_response_code($response);
11011 - if ($status_code !== 200) {
11012 - $response_body = wp_remote_retrieve_body($response);
11013 - $decoded_response = json_decode($response_body, true);
11014 -
11015 - $error_message = isset($decoded_response['error']['message'])
11016 - ? $decoded_response['error']['message']
11017 - : 'HTTP Error ' . $status_code;
11018 -
11019 - $error_type = isset($decoded_response['error']['type'])
11020 - ? $decoded_response['error']['type']
11021 - : 'unknown';
11022 -
11023 - //error_log('DeepSeek API HTTP Error: ' . $status_code . ' - ' . $error_message);
11024 -
11025 - // Handle specific error types
11026 - switch ($status_code) {
11027 - case 401:
11028 - return [
11029 - 'error' => esc_html__('Authentication failed with DeepSeek. Please check your API key.', 'mxchat'),
11030 - 'error_code' => 'deepseek_auth_error',
11031 - 'provider' => 'deepseek'
11032 - ];
11033 -
11034 - case 400:
11035 - if (strpos($error_message, 'API key') !== false) {
11036 - return [
11037 - 'error' => esc_html__('Invalid DeepSeek API key. Please check your API key configuration.', 'mxchat'),
11038 - 'error_code' => 'deepseek_invalid_api_key',
11039 - 'provider' => 'deepseek'
11040 - ];
11041 - }
11042 - break;
11043 -
11044 - case 429:
11045 - if (strpos($error_message, 'quota') !== false) {
11046 - return [
11047 - 'error' => esc_html__('DeepSeek API quota exceeded. Please check your billing details.', 'mxchat'),
11048 - 'error_code' => 'deepseek_quota_exceeded',
11049 - 'provider' => 'deepseek'
11050 - ];
11051 - } else {
11052 - return [
11053 - 'error' => esc_html__('DeepSeek rate limit exceeded. Please try again later.', 'mxchat'),
11054 - 'error_code' => 'deepseek_rate_limit',
11055 - 'provider' => 'deepseek'
11056 - ];
11057 - }
11058 -
11059 - case 500:
11060 - case 502:
11061 - case 503:
11062 - case 504:
11063 - return [
11064 - 'error' => esc_html__('DeepSeek service is currently unavailable. Please try again later.', 'mxchat'),
11065 - 'error_code' => 'deepseek_service_unavailable',
11066 - 'provider' => 'deepseek'
11067 - ];
11068 - }
11069 -
11070 - // Generic error fallback — leak-safe helper (see plan 5da59a / 1d3b0f).
11071 - return [
11072 - 'error' => $this->mxchat_friendly_chat_error($status_code, $error_message, 'DeepSeek'),
11073 - 'error_code' => 'deepseek_api_error',
11074 - 'provider' => 'deepseek',
11075 - 'status_code' => $status_code
11076 - ];
11077 - }
11078 -
11079 - $response_body = wp_remote_retrieve_body($response);
11080 - $decoded_response = json_decode($response_body, true);
11081 -
11082 - if (isset($decoded_response['choices'][0]['message']['content'])) {
11083 - return trim($decoded_response['choices'][0]['message']['content']);
11084 - } else {
11085 - //error_log('DeepSeek API Response Format Error: ' . print_r($decoded_response, true));
11086 - return [
11087 - 'error' => esc_html__('Unexpected response format from DeepSeek.', 'mxchat'),
11088 - 'error_code' => 'deepseek_response_format_error',
11089 - 'provider' => 'deepseek'
11090 - ];
11091 - }
11092 - } catch (Exception $e) {
11093 - //error_log('DeepSeek Exception: ' . $e->getMessage());
11094 - return [
11095 - 'error' => esc_html__('System error when processing DeepSeek request: ', 'mxchat') . esc_html($e->getMessage()),
11096 - 'error_code' => 'deepseek_exception',
11097 - 'provider' => 'deepseek'
11098 - ];
11099 - }
11100 -}
11101 -private function mxchat_generate_response_gemini($selected_model, $gemini_api_key, $conversation_history, $relevant_content, $session_id = '') {
11102 - // Read-time remap: gemini-3-pro-preview was shut down March 9, 2026.
11103 - // Auto-rescue existing installs whose saved model is the dead ID.
11104 - if ($selected_model === 'gemini-3-pro-preview') {
11105 - $selected_model = 'gemini-3.1-pro-preview';
11106 - }
11107 - // Get bot ID from session or request
11108 - $bot_id = $this->get_current_bot_id($session_id);
11109 -
11110 - // Get system prompt instructions using centralized function
11111 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
11112 -
11113 - // Add system prompt to relevant content
11114 - $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
11115 -
11116 - // Format messages for Gemini API
11117 - $formatted_messages = [];
11118 -
11119 - // Add system message as the first user message with role prefix
11120 - // Note: Gemini doesn't have a dedicated system role, so we use a prefixed user message
11121 - $formatted_messages[] = [
11122 - 'role' => 'user',
11123 - 'parts' => [
11124 - ['text' => "[System Instructions] " . $content_with_instructions]
11125 - ]
11126 - ];
11127 -
11128 - // Add model response to acknowledge system instructions
11129 - $formatted_messages[] = [
11130 - 'role' => 'model',
11131 - 'parts' => [
11132 - ['text' => "I understand and will follow these instructions."]
11133 - ]
11134 - ];
11135 -
11136 - // Process the rest of the conversation history
11137 - $current_role = null;
11138 - $current_parts = [];
11139 -
11140 - foreach ($conversation_history as $message) {
11141 - // Skip the first system message as we already handled it
11142 - if ($message['role'] === 'system') {
11143 - continue;
11144 - }
11145 -
11146 - // Map roles to Gemini format
11147 - $gemini_role = '';
11148 - if ($message['role'] === 'user') {
11149 - $gemini_role = 'user';
11150 - } else if (in_array($message['role'], ['assistant', 'bot', 'agent'])) {
11151 - $gemini_role = 'model';
11152 - } else {
11153 - // Skip unsupported roles
11154 - continue;
11155 - }
11156 -
11157 - // If we have a new role, add the previous message
11158 - if ($current_role !== null && $current_role !== $gemini_role && !empty($current_parts)) {
11159 - $formatted_messages[] = [
11160 - 'role' => $current_role,
11161 - 'parts' => $current_parts
11162 - ];
11163 - $current_parts = [];
11164 - }
11165 -
11166 - // Set current role and add text to parts
11167 - $current_role = $gemini_role;
11168 - $current_parts[] = ['text' => $message['content']];
11169 - }
11170 -
11171 - // Add the last message if there's content
11172 - if ($current_role !== null && !empty($current_parts)) {
11173 - $formatted_messages[] = [
11174 - 'role' => $current_role,
11175 - 'parts' => $current_parts
11176 - ];
11177 - }
11178 -
11179 - // Built-in Web Search grounding for Gemini (plan 46b9ea).
11180 - // The enable_web_search toggle historically routed ONLY to OpenAI's web_search
11181 - // tool; for a Gemini chat model it was a silent no-op. Gemini grounds natively
11182 - // (and free) via the Google Search tool, so when the toggle is on we attach it
11183 - // here on the PLAIN dispatch path. The function-calling loop (mxchat_fc_loop_gemini)
11184 - // is a SEPARATE path reached only when AI Tools are active, so grounding here
11185 - // never double-fires with function calling.
11186 - $web_search_enabled = isset($this->options['enable_web_search']) && $this->options['enable_web_search'] === 'on';
11187 - // Gemini ids that do NOT support Google Search grounding (none today — every
11188 - // shipped chat model is 2.x/3.x and grounds natively). Kept as the explicit
11189 - // opt-out list mirroring the OpenAI $unsupported_web_search_models pattern.
11190 - $gemini_unsupported_grounding = array();
11191 - $grounding_active = $web_search_enabled && !in_array($selected_model, $gemini_unsupported_grounding, true);
11192 -
11193 - // Build the request body
11194 - $request_payload = [
11195 - 'contents' => $formatted_messages,
11196 - 'generationConfig' => [
11197 - 'temperature' => 0.7,
11198 - 'topP' => 0.95,
11199 - 'topK' => 40,
11200 - 'maxOutputTokens' => 8192,
11201 - ],
11202 - 'safetySettings' => [
11203 - [
11204 - 'category' => 'HARM_CATEGORY_HARASSMENT',
11205 - 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
11206 - ],
11207 - [
11208 - 'category' => 'HARM_CATEGORY_HATE_SPEECH',
11209 - 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
11210 - ],
11211 - [
11212 - 'category' => 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
11213 - 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
11214 - ],
11215 - [
11216 - 'category' => 'HARM_CATEGORY_DANGEROUS_CONTENT',
11217 - 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
11218 - ]
11219 - ]
11220 - ];
11221 -
11222 - if ($grounding_active) {
11223 - // Gemini 1.5 used the older google_search_retrieval shape; 2.0+ uses the
11224 - // bare google_search tool. Branch by model family so a future 1.5 id still
11225 - // grounds (no 1.5 ships today, so this resolves to google_search). The empty
11226 - // tool config must serialize as a JSON object {}, not an array [].
11227 - if (strpos($selected_model, 'gemini-1.5') !== false) {
11228 - $request_payload['tools'] = [ ['google_search_retrieval' => new \stdClass()] ];
11229 - } else {
11230 - $request_payload['tools'] = [ ['google_search' => new \stdClass()] ];
11231 - }
11232 - }
11233 -
11234 - $body = json_encode($request_payload);
11235 -
11236 - // Prepare the API endpoint
11237 - // Use v1beta for preview models (Gemini 3, experimental), v1 for stable models.
11238 - // Grounding (the google_search tool) is a v1beta feature, so force v1beta whenever
11239 - // it's active — otherwise a stable model on v1 would silently drop the tool.
11240 - $api_version = ($grounding_active || strpos($selected_model, 'preview') !== false || strpos($selected_model, 'exp') !== false) ? 'v1beta' : 'v1';
11241 - $api_endpoint = 'https://generativelanguage.googleapis.com/' . $api_version . '/models/' . $selected_model . ':generateContent?key=' . $gemini_api_key;
11242 -
11243 - // Set up the API request
11244 - $args = [
11245 - 'body' => $body,
11246 - 'headers' => [
11247 - 'Content-Type' => 'application/json',
11248 - ],
11249 - 'timeout' => 60,
11250 - 'redirection' => 5,
11251 - 'blocking' => true,
11252 - 'httpversion' => '1.0',
11253 - 'sslverify' => true,
11254 - ];
11255 -
11256 - // Make the API request
11257 - $response = $this->mxchat_provider_call_with_retry($api_endpoint, $args, 'gemini');
11258 -
11259 - // Process the response
11260 - if (is_wp_error($response)) {
11261 - // plan b13282: route the transport-error string through the leak-safe helper
11262 - // (admin-actionable, generic for visitors) instead of echoing the raw WP HTTP
11263 - // error. http_code 0 = no HTTP response, so the helper uses the generic branch.
11264 - return $this->mxchat_friendly_chat_error(0, $response->get_error_message(), 'Gemini');
11265 - }
11266 -
11267 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
11268 -
11269 - // Handle potential errors in the response. Gemini surfaces errors as a
11270 - // 200/non-200 body with an `error` envelope; route the user-facing text
11271 - // through the leak-safe helper (admin-actionable, no visitor leak) rather
11272 - // than echoing the raw provider message. plan 5da59a.
11273 - if (isset($response_body['error'])) {
11274 - //error_log('Gemini API Error: ' . json_encode($response_body['error']));
11275 - $gemini_error_message = isset($response_body['error']['message'])
11276 - ? $response_body['error']['message']
11277 - : 'Unknown error';
11278 - $gemini_http_code = wp_remote_retrieve_response_code($response);
11279 - return $this->mxchat_friendly_chat_error($gemini_http_code, $gemini_error_message, 'Gemini');
11280 - }
11281 -
11282 - // Extract the response text
11283 - if (isset($response_body['candidates'][0]['content']['parts'][0]['text'])) {
11284 - return trim($response_body['candidates'][0]['content']['parts'][0]['text']);
11285 - } else {
11286 - //error_log('Unexpected Gemini API response format: ' . json_encode($response_body));
11287 - return "Sorry, I couldn't process that request. The response format was unexpected.";
11288 - }
11289 -}
11290 -
11291 -
11292 -public function test_streaming_request() {
11293 - $options = get_option('mxchat_options', []);
11294 - $model = $options['model'] ?? 'gpt-5.1-chat-latest';
11295 -
11296 - // Detect provider from model prefix
11297 - $provider = strtolower(explode('-', $model)[0]);
11298 -
11299 - $sample_prompt = 'Hello! Can you stream this response back to me?';
11300 - $messages = [['role' => 'user', 'content' => $sample_prompt]];
11301 - $headers = [];
11302 - $body = [];
11303 - $url = '';
11304 - $api_key = '';
11305 -
11306 - switch ($provider) {
11307 - case 'gpt':
11308 - case 'o1':
11309 - $api_key = $options['api_key'] ?? '';
11310 - if (empty($api_key)) return '❌ Missing API key for OpenAI';
11311 - $url = 'https://api.openai.com/v1/chat/completions';
11312 - $headers = [
11313 - 'Content-Type: application/json',
11314 - 'Authorization: Bearer ' . $api_key
11315 - ];
11316 - $body = [
11317 - 'model' => $model,
11318 - 'messages' => $messages,
11319 - 'stream' => true
11320 - ];
11321 - break;
11322 -
11323 - case 'claude':
11324 - $api_key = $options['claude_api_key'] ?? '';
11325 - if (empty($api_key)) return '❌ Missing API key for Claude';
11326 - $url = 'https://api.anthropic.com/v1/messages';
11327 - $headers = [
11328 - 'Content-Type: application/json',
11329 - 'x-api-key: ' . $api_key,
11330 - 'anthropic-version: 2023-06-01'
11331 - ];
11332 - $body = [
11333 - 'model' => $model,
11334 - 'messages' => $messages,
11335 - 'max_tokens' => 100,
11336 - 'stream' => true
11337 - ];
11338 - break;
11339 -
11340 - case 'grok':
11341 - $api_key = $options['xai_api_key'] ?? '';
11342 - if (empty($api_key)) return '❌ Missing API key for X.AI';
11343 - $url = 'https://api.x.ai/v1/chat/completions';
11344 - $headers = [
11345 - 'Content-Type: application/json',
11346 - 'Authorization: Bearer ' . $api_key
11347 - ];
11348 - $body = [
11349 - 'model' => $model,
11350 - 'messages' => $messages,
11351 - 'stream' => true
11352 - ];
11353 - break;
11354 -
11355 - case 'deepseek':
11356 - if (empty($deepseek_api_key)) {
11357 - $error_response = [
11358 - 'error' => esc_html__('DeepSeek API key is not configured', 'mxchat'),
11359 - 'error_code' => 'missing_deepseek_api_key'
11360 - ];
11361 - if ($testing_data !== null) {
11362 - $error_response['testing_data'] = $testing_data;
11363 - }
11364 - return $error_response;
11365 - }
11366 - if ($streaming) {
11367 - return $this->mxchat_generate_response_deepseek_stream(
11368 - $selected_model,
11369 - $deepseek_api_key,
11370 - $conversation_history,
11371 - $relevant_content,
11372 - $session_id,
11373 - $testing_data // Pass testing data
11374 - );
11375 - } else {
11376 - $response = $this->mxchat_generate_response_deepseek(
11377 - $selected_model,
11378 - $deepseek_api_key,
11379 - $conversation_history,
11380 - $relevant_content,
11381 - $session_id
11382 - );
11383 - }
11384 - break;
11385 -
11386 - case 'gemini':
11387 - $api_key = $options['gemini_api_key'] ?? '';
11388 - if (empty($api_key)) return '❌ Missing API key for Gemini';
11389 - $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':streamGenerateContent?key=' . $api_key;
11390 - $headers = ['Content-Type: application/json'];
11391 - $body = [
11392 - 'contents' => [['role' => 'user', 'parts' => [['text' => $sample_prompt]]]],
11393 - 'generationConfig' => ['temperature' => 0.7]
11394 - ];
11395 - break;
11396 -
11397 - default:
11398 - return '❌ Unsupported provider: ' . $provider;
11399 - }
11400 -
11401 - // Do the actual streaming test
11402 - $ch = curl_init($url);
11403 - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
11404 - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
11405 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
11406 - curl_setopt($ch, CURLOPT_TIMEOUT, 15);
11407 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
11408 -
11409 - $response = curl_exec($ch);
11410 - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
11411 - $error = curl_error($ch);
11412 - curl_close($ch);
11413 -
11414 - if ($error) return "❌ cURL error: $error";
11415 - if ($http_code !== 200) {
11416 - $error_message = json_decode($response, true)['error']['message'] ?? 'Unknown';
11417 - return "❌ HTTP $http_code: $error_message";
11418 - }
11419 -
11420 - return true;
11421 -}
11422 -
11423 -public function mxchat_dismiss_pre_chat_message() {
11424 - // Get and sanitize the user identifier
11425 - $user_id = $this->mxchat_get_user_identifier();
11426 - $user_id = sanitize_key($user_id);
11427 -
11428 - // Set a transient to track that the user has dismissed the pre-chat message
11429 - $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
11430 - set_transient($transient_key, true, DAY_IN_SECONDS);
11431 -
11432 - wp_send_json_success();
11433 -}
11434 -
11435 -public function mxchat_check_pre_chat_message_status() {
11436 - // Get and sanitize the user identifier
11437 - $user_id = $this->mxchat_get_user_identifier();
11438 - $user_id = sanitize_key($user_id);
11439 -
11440 - // Check if the transient exists (i.e., if the message was dismissed)
11441 - $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
11442 - $dismissed = get_transient($transient_key);
11443 -
11444 - // Log the result to see if it's being set correctly
11445 - //error_log("Check pre-chat message dismissed for $user_id: " . ($dismissed ? 'Yes' : 'No'));
11446 -
11447 - if ($dismissed) {
11448 - wp_send_json_success(['dismissed' => true]);
11449 - } else {
11450 - wp_send_json_success(['dismissed' => false]);
11451 - }
11452 -
11453 - wp_die();
11454 -}
11455 -
11456 -private function mxchat_calculate_cosine_similarity($vectorA, $vectorB) {
11457 - if (!is_array($vectorA) || !is_array($vectorB) || empty($vectorA) || empty($vectorB)) {
11458 - return 0;
11459 - }
11460 -
11461 - $dotProduct = array_sum(array_map(function ($a, $b) {
11462 - return $a * $b;
11463 - }, $vectorA, $vectorB));
11464 - $normA = sqrt(array_sum(array_map(function ($a) {
11465 - return $a * $a;
11466 - }, $vectorA)));
11467 - $normB = sqrt(array_sum(array_map(function ($b) {
11468 - return $b * $b;
11469 - }, $vectorB)));
11470 -
11471 - if ($normA == 0 || $normB == 0) {
11472 - return 0;
11473 - }
11474 -
11475 - return $dotProduct / ($normA * $normB);
11476 - }
11477 -
11478 -
11479 -public function mxchat_enqueue_scripts_styles() {
11480 - // Fetch options from the database first to check loading strategy
11481 - $this->options = get_option('mxchat_options');
11482 - $loading_strategy = isset($this->options['script_loading_strategy']) ? $this->options['script_loading_strategy'] : 'default';
11483 -
11484 - // Always enqueue CSS immediately
11485 - wp_enqueue_style(
11486 - 'mxchat-chat-css',
11487 - plugin_dir_url(__FILE__) . '../css/chat-style.css',
11488 - array(),
11489 - MXCHAT_VERSION
11490 - );
11491 -
11492 - // Handle script loading based on strategy
11493 - if ($loading_strategy === 'default' || $loading_strategy === 'defer') {
11494 - // Enqueue the script normally
11495 - wp_enqueue_script(
11496 - 'mxchat-chat-js',
11497 - plugin_dir_url(__FILE__) . '../js/chat-script.js',
11498 - array('jquery'),
11499 - MXCHAT_VERSION,
11500 - true
11501 - );
11502 -
11503 - // Add defer attribute if strategy is 'defer'
11504 - if ($loading_strategy === 'defer') {
11505 - wp_script_add_data('mxchat-chat-js', 'strategy', 'defer');
11506 - }
11507 - } else {
11508 - // For delay or interaction-based loading, we'll use a custom loader
11509 - // Don't enqueue the main script - we'll load it dynamically
11510 - add_action('wp_footer', array($this, 'mxchat_output_delayed_script_loader'), 99);
11511 - }
11512 -
11513 - $prompts_options = get_option('mxchat_prompts_options', array());
11514 -
11515 - // Check if AI theme is active - if so, skip inline colors in JavaScript
11516 - $theme_options = get_option('mxchat_theme_options', array());
11517 - $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
11518 - $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']);
11519 - $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments;
11520 -
11521 - // Prepare settings for JavaScript
11522 - $style_settings = array(
11523 - 'ajax_url' => admin_url('admin-ajax.php'),
11524 - // The chat-send nonce is now fetched per-request from /wp-json/mxchat/v1/nonce
11525 - // (plan-6a68c9) so it never sits in cached HTML. We still emit a nonce here
11526 - // as a one-shot fallback for the first interaction on a fresh page load
11527 - // (so the very first chat-send doesn't need to wait for a REST round-trip),
11528 - // but the widget refetches before each subsequent send.
11529 - 'nonce' => wp_create_nonce('mxchat_chat_send'),
11530 - 'rest_url' => esc_url_raw(trailingslashit(rest_url('mxchat/v1'))),
11531 - 'contextual_awareness_toggle' => isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off',
11532 - 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
11533 - 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
11534 - 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
11535 - 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
11536 - 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
11537 - 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
11538 - 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
11539 - 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
11540 - 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
11541 - 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
11542 - 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
11543 - 'icon_color' => $this->options['icon_color'] ?? '#fff',
11544 - 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
11545 - 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
11546 - 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off',
11547 - 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
11548 - 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
11549 - 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
11550 - 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
11551 - 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
11552 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
11553 - 'email_collection_enabled' => $this->options['enable_email_block'] ?? 'off', // FIXED
11554 - 'initial_email_state' => null, // Also fixed this undefined variable
11555 - 'skip_email_check' => true,
11556 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1',
11557 - 'skip_inline_colors' => $skip_inline_colors,
11558 - 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array(),
11559 - );
11560 -
11561 - // Behavior gates + labels (model, streaming, rate-limit copy, toolbar,
11562 - // print/transcript, satisfaction rating) come from the shared
11563 - // dynamic-settings method so this inline payload and the first-open
11564 - // refresh endpoint can never drift (plan-32db95).
11565 - $style_settings = array_merge($style_settings, $this->get_dynamic_widget_settings());
11566 -
11567 - // For normal/defer loading, use wp_localize_script
11568 - // For delayed loading, we store settings in a transient to be output inline
11569 - if ($loading_strategy === 'default' || $loading_strategy === 'defer') {
11570 - wp_localize_script('mxchat-chat-js', 'mxchatChat', $style_settings);
11571 - } else {
11572 - // Store settings for the delayed loader to use
11573 - set_transient('mxchat_delayed_settings_' . get_current_user_id(), $style_settings, 60);
11574 - }
11575 -}
11576 -
11577 -/**
11578 - * Output the delayed script loader for performance optimization
11579 - */
11580 -public function mxchat_output_delayed_script_loader() {
11581 - $this->options = get_option('mxchat_options');
11582 - $loading_strategy = isset($this->options['script_loading_strategy']) ? $this->options['script_loading_strategy'] : 'default';
11583 - $script_url = plugin_dir_url(__FILE__) . '../js/chat-script.js?ver=' . MXCHAT_VERSION;
11584 -
11585 - // Get the stored settings
11586 - $prompts_options = get_option('mxchat_prompts_options', array());
11587 - $theme_options = get_option('mxchat_theme_options', array());
11588 - $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
11589 - $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']);
11590 - $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments;
11591 -
11592 - $style_settings = array(
11593 - 'ajax_url' => admin_url('admin-ajax.php'),
11594 - // Per-request nonce — see plan-6a68c9; widget fetches via /wp-json/mxchat/v1/nonce
11595 - // before each send. This inline value is a one-shot fallback for the first interaction.
11596 - 'nonce' => wp_create_nonce('mxchat_chat_send'),
11597 - 'rest_url' => esc_url_raw(trailingslashit(rest_url('mxchat/v1'))),
11598 - 'contextual_awareness_toggle' => isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off',
11599 - 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
11600 - 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
11601 - 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
11602 - 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
11603 - 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
11604 - 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
11605 - 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
11606 - 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
11607 - 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
11608 - 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
11609 - 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
11610 - 'icon_color' => $this->options['icon_color'] ?? '#fff',
11611 - 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
11612 - 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
11613 - 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off',
11614 - 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
11615 - 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
11616 - 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
11617 - 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
11618 - 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
11619 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
11620 - 'email_collection_enabled' => $this->options['enable_email_block'] ?? 'off',
11621 - 'initial_email_state' => null,
11622 - 'skip_email_check' => true,
11623 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1',
11624 - 'skip_inline_colors' => $skip_inline_colors,
11625 - 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array(),
11626 - );
11627 -
11628 - // Behavior gates + labels (model, streaming, rate-limit copy, toolbar,
11629 - // print/transcript, satisfaction rating) come from the shared
11630 - // dynamic-settings method so this inline payload and the first-open
11631 - // refresh endpoint can never drift (plan-32db95).
11632 - $style_settings = array_merge($style_settings, $this->get_dynamic_widget_settings());
11633 -
11634 - // Determine delay time based on strategy
11635 - $delay_ms = 0;
11636 - switch ($loading_strategy) {
11637 - case 'delay_1s':
11638 - $delay_ms = 1000;
11639 - break;
11640 - case 'delay_3s':
11641 - $delay_ms = 3000;
11642 - break;
11643 - case 'delay_5s':
11644 - $delay_ms = 5000;
11645 - break;
11646 - }
11647 -
11648 - ?>
11649 - <script type="text/javascript">
11650 - (function() {
11651 - var mxchatLoaded = false;
11652 - var mxchatChat = <?php echo wp_json_encode($style_settings); ?>;
11653 - window.mxchatChat = mxchatChat;
11654 -
11655 - function loadMxChatScript() {
11656 - if (mxchatLoaded) return;
11657 - mxchatLoaded = true;
11658 -
11659 - function appendChatScript() {
11660 - var script = document.createElement('script');
11661 - script.src = <?php echo wp_json_encode($script_url); ?>;
11662 - script.type = 'text/javascript';
11663 - document.body.appendChild(script);
11664 - }
11665 -
11666 - if (typeof jQuery !== 'undefined') {
11667 - appendChatScript();
11668 - } else {
11669 - var jq = document.createElement('script');
11670 - jq.src = <?php echo wp_json_encode(includes_url('js/jquery/jquery.min.js')); ?>;
11671 - jq.onload = appendChatScript;
11672 - document.body.appendChild(jq);
11673 - }
11674 - }
11675 -
11676 - <?php if ($loading_strategy === 'on_interaction'): ?>
11677 - // Load on user interaction
11678 - var events = ['scroll', 'mousemove', 'touchstart', 'keydown', 'click'];
11679 - events.forEach(function(evt) {
11680 - window.addEventListener(evt, loadMxChatScript, {once: true, passive: true});
11681 - });
11682 - // Fallback: load after 8 seconds if no interaction
11683 - setTimeout(loadMxChatScript, 8000);
11684 - <?php else: ?>
11685 - // Load after specified delay
11686 - setTimeout(loadMxChatScript, <?php echo intval($delay_ms); ?>);
11687 - <?php endif; ?>
11688 - })();
11689 - </script>
11690 - <?php
11691 -}
11692 -
11693 -/**
11694 - * Setup the cron jobs for rate limits with guard against multiple calls
11695 - */
11696 -public function setup_rate_limit_cron_jobs() {
11697 - // Add a guard to prevent multiple rapid calls
11698 - $last_setup = get_transient('mxchat_cron_setup_guard');
11699 - if ($last_setup && (time() - $last_setup) < 60) {
11700 - // Don't run again if we ran less than 60 seconds ago
11701 - return;
11702 - }
11703 -
11704 - // Set the guard
11705 - set_transient('mxchat_cron_setup_guard', time(), 300); // 5 minutes
11706 -
11707 - try {
11708 - // First, check if WordPress cron is disabled
11709 - if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
11710 - //error_log('MxChat: WordPress cron is disabled (DISABLE_WP_CRON = true), using fallback system');
11711 - $this->setup_fallback_rate_limit_system();
11712 - return;
11713 - }
11714 -
11715 - // Check if cron is already scheduled - if so, don't mess with it
11716 - if (wp_next_scheduled('mxchat_reset_rate_limits')) {
11717 - //error_log('MxChat: Rate limit cron already scheduled, skipping setup');
11718 - return;
11719 - }
11720 -
11721 - // Clear any orphaned hooks (but don't loop indefinitely)
11722 - $hooks_to_clear = [
11723 - 'mxchat_reset_rate_limits',
11724 - 'mxchat_reset_hourly_rate_limits',
11725 - 'mxchat_reset_daily_rate_limits',
11726 - 'mxchat_reset_weekly_rate_limits',
11727 - 'mxchat_reset_monthly_rate_limits'
11728 - ];
11729 -
11730 - foreach ($hooks_to_clear as $hook) {
11731 - // Only clear a maximum of 3 instances to prevent infinite loops
11732 - $cleared = 0;
11733 - while (wp_next_scheduled($hook) && $cleared < 3) {
11734 - wp_clear_scheduled_hook($hook);
11735 - $cleared++;
11736 - }
11737 - }
11738 -
11739 - // Small delay after clearing
11740 - usleep(100000); // 0.1 seconds
11741 -
11742 - // Try to schedule the event
11743 - $initial_time = time() + 300; // Start in 5 minutes
11744 - $result = wp_schedule_event($initial_time, 'hourly', 'mxchat_reset_rate_limits');
11745 -
11746 - if ($result === false) {
11747 - //error_log('MxChat: Failed to schedule cron, using fallback system');
11748 - $this->setup_fallback_rate_limit_system();
11749 - } else {
11750 - //error_log('MxChat: Successfully scheduled rate limit reset cron');
11751 - }
11752 -
11753 - } catch (Exception $e) {
11754 - //error_log('MxChat: Cron setup exception: ' . $e->getMessage());
11755 - $this->setup_fallback_rate_limit_system();
11756 - }
11757 -}
11758 -
11759 -/**
11760 - * Try alternative cron scheduling methods
11761 - */
11762 -private function try_alternative_cron_scheduling($initial_time) {
11763 - try {
11764 - // Method 1: Try with current time instead of future time
11765 - $result1 = wp_schedule_event(time(), 'hourly', 'mxchat_reset_rate_limits');
11766 - if ($result1 !== false) {
11767 - //error_log('MxChat: Alternative method 1 (current time) succeeded');
11768 - return true;
11769 - }
11770 -
11771 - // Method 2: Try with a different interval
11772 - $result2 = wp_schedule_event($initial_time, 'daily', 'mxchat_reset_rate_limits');
11773 - if ($result2 !== false) {
11774 - //error_log('MxChat: Alternative method 2 (daily interval) succeeded');
11775 - return true;
11776 - }
11777 -
11778 - // Method 3: Try wp_schedule_single_event first, then recurring
11779 - $result3 = wp_schedule_single_event($initial_time, 'mxchat_reset_rate_limits');
11780 - if ($result3 !== false) {
11781 - //error_log('MxChat: Alternative method 3 (single event) succeeded');
11782 - // Schedule the next one manually in the handler
11783 - return true;
11784 - }
11785 -
11786 - return false;
11787 -
11788 - } catch (Exception $e) {
11789 - //error_log('MxChat: Alternative cron scheduling exception: ' . $e->getMessage());
11790 - return false;
11791 - }
11792 -}
11793 -
11794 -/**
11795 - * Enhanced fallback rate limit system
11796 - */
11797 -private function setup_fallback_rate_limit_system() {
11798 - // Set a flag to use database-based rate limit cleanup
11799 - update_option('mxchat_use_fallback_rate_limits', true);
11800 -
11801 - // Schedule a one-time check to happen on the next plugin load
11802 - update_option('mxchat_next_rate_limit_check', time() + 3600);
11803 -
11804 - // Also set up a more frequent fallback check (every 4 hours)
11805 - update_option('mxchat_fallback_check_interval', 4 * 3600);
11806 -
11807 - //error_log('MxChat: Fallback rate limit system activated');
11808 -}
11809 -
11810 -/**
11811 - * Enhanced fallback check method
11812 - */
11813 -public function check_fallback_rate_limits() {
11814 - $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
11815 -
11816 - if (!$use_fallback) {
11817 - return; // Regular cron is working
11818 - }
11819 -
11820 - $next_check = get_option('mxchat_next_rate_limit_check', 0);
11821 - $check_interval = get_option('mxchat_fallback_check_interval', 3600);
11822 -
11823 - if (time() >= $next_check) {
11824 - //error_log('MxChat: Running fallback rate limit cleanup');
11825 - $this->mxchat_reset_rate_limits();
11826 -
11827 - // Schedule next check
11828 - update_option('mxchat_next_rate_limit_check', time() + $check_interval);
11829 - }
11830 -}
11831 -/**
11832 - * Enhanced rate limit check that includes fallback cleanup and bot-specific rate limits
11833 - */
11834 -public function check_rate_limit() {
11835 - // Check if we need to run fallback cleanup
11836 - $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
11837 - $next_check = get_option('mxchat_next_rate_limit_check', 0);
11838 -
11839 - if ($use_fallback && time() >= $next_check) {
11840 - $this->mxchat_reset_rate_limits();
11841 - update_option('mxchat_next_rate_limit_check', time() + 3600); // Next hour
11842 - }
11843 -
11844 - // Get bot ID from current request context
11845 - $bot_id = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
11846 -
11847 - // Get bot-specific options (includes rate limits if overridden)
11848 - $bot_options = $this->get_bot_options($bot_id);
11849 - $current_options = !empty($bot_options) ? $bot_options : $this->options;
11850 -
11851 - // Use bot-specific rate limits if available, otherwise fall back to default
11852 - $rate_limits_source = isset($current_options['rate_limits']) ? $current_options['rate_limits'] : get_option('mxchat_options', [])['rate_limits'] ?? [];
11853 -
11854 - // -------------------------------------------------------------------
11855 - // Whole-chatbot global cap (independent of role). Evaluated FIRST so
11856 - // it acts as a hard ceiling across all users + all roles. Default is
11857 - // 'unlimited' so existing installs are unchanged. Counter key drops
11858 - // both <role> and <user_id> segments — single pool per bot.
11859 - // -------------------------------------------------------------------
11860 - $global_cfg = isset($current_options['rate_limits_global']) && is_array($current_options['rate_limits_global'])
11861 - ? $current_options['rate_limits_global']
11862 - : (isset(get_option('mxchat_options', [])['rate_limits_global']) ? get_option('mxchat_options', [])['rate_limits_global'] : []);
11863 - $global_limit_raw = isset($global_cfg['limit']) ? (string) $global_cfg['limit'] : 'unlimited';
11864 - $global_timeframe = isset($global_cfg['timeframe']) ? (string) $global_cfg['timeframe'] : 'daily';
11865 - if ($global_limit_raw !== '' && $global_limit_raw !== 'unlimited' && (int) $global_limit_raw >= 1) {
11866 - $bot_id_for_global = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
11867 - $safe_bot_global = preg_replace('/[^a-zA-Z0-9_]/', '_', $bot_id_for_global);
11868 - $global_option = 'mxchat_chat_limit_' . $safe_bot_global . '_global';
11869 - $global_data = get_option($global_option, ['count' => 0, 'timestamp' => time()]);
11870 - if ((int) $global_data['count'] === 0) {
11871 - $global_data['timestamp'] = time();
11872 - update_option($global_option, $global_data);
11873 - }
11874 - $now = time();
11875 - $ts = (int) $global_data['timestamp'];
11876 - $reset = false;
11877 - switch ($global_timeframe) {
11878 - case 'hourly': $reset = ($now - $ts) >= 3600; break;
11879 - case 'daily': $reset = ($now - $ts) >= 86400; break;
11880 - case 'weekly': $reset = ($now - $ts) >= 604800; break;
11881 - case 'monthly': $reset = ($now - $ts) >= 2592000; break;
11882 - }
11883 - if ($reset) {
11884 - $global_data = ['count' => 0, 'timestamp' => $now];
11885 - update_option($global_option, $global_data);
11886 - }
11887 - if ((int) $global_data['count'] >= (int) $global_limit_raw) {
11888 - $global_msg = !empty($global_cfg['message'])
11889 - ? $global_cfg['message']
11890 - : __('This chatbot has reached its message limit. Please try again later.', 'mxchat');
11891 - return [
11892 - 'error' => true,
11893 - 'message' => $this->process_rate_limit_message_html($global_msg),
11894 - ];
11895 - }
11896 - // Reserve the slot for this request. Per-role check below also increments
11897 - // its own counter — that is intentional, both ceilings apply independently.
11898 - $global_data['count']++;
11899 - update_option($global_option, $global_data);
11900 - }
11901 -
11902 - // Determine user role or if logged out
11903 - if (is_user_logged_in()) {
11904 - $user = wp_get_current_user();
11905 - $user_id = $user->ID;
11906 -
11907 - // Get the user's primary role using reset() to safely get the first element
11908 - $user_roles = $user->roles;
11909 -
11910 - // Safely get the first role regardless of array key structure
11911 - if (!empty($user_roles) && is_array($user_roles)) {
11912 - $role = reset($user_roles); // This safely gets the first element regardless of key
11913 - } else {
11914 - $role = 'subscriber'; // Default to subscriber if no role found
11915 - }
11916 - } else {
11917 - $role = 'logged_out';
11918 - // Use IP address for non-logged-in users
11919 - $user_id = $this->get_client_ip();
11920 - }
11921 -
11922 - // Check if rate limits are configured for this role
11923 - if (!isset($rate_limits_source[$role])) {
11924 - return true; // No limit set for this role
11925 - }
11926 -
11927 - $limit = $rate_limits_source[$role]['limit'];
11928 -
11929 - // If unlimited, return true immediately
11930 - if ($limit === 'unlimited') {
11931 - return true;
11932 - }
11933 -
11934 - // Get the option name for this user/role with safer naming (include bot_id for bot-specific limits)
11935 - $safe_role = preg_replace('/[^a-zA-Z0-9_]/', '_', $role);
11936 - $safe_user_id = preg_replace('/[^a-zA-Z0-9_]/', '_', $user_id);
11937 - $safe_bot_id = preg_replace('/[^a-zA-Z0-9_]/', '_', $bot_id);
11938 -
11939 - // Include bot_id in option name so each bot has separate rate limits
11940 - $option_name = 'mxchat_chat_limit_' . $safe_bot_id . '_' . $safe_role . '_' . $safe_user_id;
11941 -
11942 - // Get the counter data
11943 - $limit_data = get_option($option_name, ['count' => 0, 'timestamp' => time()]);
11944 -
11945 - // If first request or counter reset needed, set the initial timestamp
11946 - if ($limit_data['count'] === 0) {
11947 - $limit_data['timestamp'] = time();
11948 - update_option($option_name, $limit_data);
11949 - }
11950 -
11951 - // Get the timeframe
11952 - $timeframe = isset($rate_limits_source[$role]['timeframe']) ?
11953 - $rate_limits_source[$role]['timeframe'] : 'daily';
11954 -
11955 - // Check if the counter needs to be reset based on timeframe
11956 - $current_time = time();
11957 - $timestamp = $limit_data['timestamp'];
11958 - $should_reset = false;
11959 -
11960 - switch ($timeframe) {
11961 - case 'hourly':
11962 - $should_reset = ($current_time - $timestamp) >= 3600; // 1 hour
11963 - break;
11964 - case 'daily':
11965 - $should_reset = ($current_time - $timestamp) >= 86400; // 24 hours
11966 - break;
11967 - case 'weekly':
11968 - $should_reset = ($current_time - $timestamp) >= 604800; // 7 days
11969 - break;
11970 - case 'monthly':
11971 - $should_reset = ($current_time - $timestamp) >= 2592000; // 30 days
11972 - break;
11973 - }
11974 -
11975 - // Reset the counter if the timeframe has passed
11976 - if ($should_reset) {
11977 - $limit_data = ['count' => 0, 'timestamp' => $current_time];
11978 - update_option($option_name, $limit_data);
11979 - }
11980 -
11981 - // Check if user has exceeded their limit
11982 - if ($limit_data['count'] >= intval($limit)) {
11983 - // Get the custom message for this role
11984 - $message = !empty($rate_limits_source[$role]['message'])
11985 - ? $rate_limits_source[$role]['message']
11986 - : __('Rate limit exceeded. Please try again later.', 'mxchat');
11987 -
11988 - // Add timeframe information to the message if placeholders exist
11989 - $timeframe_label = '';
11990 - switch ($timeframe) {
11991 - case 'hourly':
11992 - $timeframe_label = __('hour', 'mxchat');
11993 - break;
11994 - case 'daily':
11995 - $timeframe_label = __('day', 'mxchat');
11996 - break;
11997 - case 'weekly':
11998 - $timeframe_label = __('week', 'mxchat');
11999 - break;
12000 - case 'monthly':
12001 - $timeframe_label = __('month', 'mxchat');
12002 - break;
12003 - }
12004 -
12005 - // Replace placeholders in the message
12006 - $message = str_replace(
12007 - ['{limit}', '{count}', '{remaining}', '{timeframe}'],
12008 - [intval($limit), $limit_data['count'], max(0, intval($limit) - $limit_data['count']), $timeframe_label],
12009 - $message
12010 - );
12011 -
12012 - // Process HTML links in the message
12013 - $message = $this->process_rate_limit_message_html($message);
12014 -
12015 - // Return error with the processed message
12016 - return [
12017 - 'error' => true,
12018 - 'message' => $message
12019 - ];
12020 - }
12021 -
12022 - // Increment the counter
12023 - $limit_data['count']++;
12024 - update_option($option_name, $limit_data);
12025 -
12026 - return true;
12027 -}
12028 -
12029 -/**
12030 - * Enhanced rate limit reset with better error handling
12031 - */
12032 -public function mxchat_reset_rate_limits() {
12033 - try {
12034 - global $wpdb;
12035 - $all_options = get_option('mxchat_options', []);
12036 - $current_time = time();
12037 -
12038 - // Get rate limit options with a safer query and limit
12039 - $option_names = $wpdb->get_col(
12040 - $wpdb->prepare(
12041 - "SELECT option_name FROM {$wpdb->options}
12042 - WHERE option_name LIKE %s
12043 - LIMIT 1000",
12044 - 'mxchat_chat_limit_%'
12045 - )
12046 - );
12047 -
12048 - if (empty($option_names)) {
12049 - return;
12050 - }
12051 -
12052 - $processed_count = 0;
12053 - $max_processing_time = 30; // Maximum 30 seconds
12054 - $start_time = time();
12055 -
12056 - foreach ($option_names as $option_name) {
12057 - // Check processing time limit
12058 - if ((time() - $start_time) > $max_processing_time) {
12059 - //error_log('MxChat: Rate limit reset timeout after processing ' . $processed_count . ' entries');
12060 - break;
12061 - }
12062 -
12063 - // Parse the option name more safely
12064 - if (!preg_match('/^mxchat_chat_limit_(.+)_(.+)$/', $option_name, $matches)) {
12065 - continue;
12066 - }
12067 -
12068 - $role_and_user = $matches[1] . '_' . $matches[2];
12069 - $parts = explode('_', $role_and_user);
12070 -
12071 - if (count($parts) < 2) {
12072 - continue;
12073 - }
12074 -
12075 - // Extract role (everything except the last part which is user ID)
12076 - $user_id_part = array_pop($parts);
12077 - $role = implode('_', $parts);
12078 -
12079 - // Skip if role doesn't exist in our settings
12080 - if (!isset($all_options['rate_limits'][$role])) {
12081 - // Clean up orphaned entries
12082 - delete_option($option_name);
12083 - continue;
12084 - }
12085 -
12086 - $timeframe = $all_options['rate_limits'][$role]['timeframe'] ?? 'daily';
12087 - $limit_data = get_option($option_name);
12088 -
12089 - if (!$limit_data || !is_array($limit_data) || !isset($limit_data['timestamp'])) {
12090 - // Clean up invalid entries
12091 - delete_option($option_name);
12092 - continue;
12093 - }
12094 -
12095 - $timestamp = $limit_data['timestamp'];
12096 - $should_reset = false;
12097 -
12098 - // Determine if we should reset based on the timeframe
12099 - switch ($timeframe) {
12100 - case 'hourly':
12101 - $should_reset = ($current_time - $timestamp) >= 3600;
12102 - break;
12103 - case 'daily':
12104 - $should_reset = ($current_time - $timestamp) >= 86400;
12105 - break;
12106 - case 'weekly':
12107 - $should_reset = ($current_time - $timestamp) >= 604800;
12108 - break;
12109 - case 'monthly':
12110 - $should_reset = ($current_time - $timestamp) >= 2592000;
12111 - break;
12112 - }
12113 -
12114 - // Reset the counter if the timeframe has passed
12115 - if ($should_reset) {
12116 - delete_option($option_name);
12117 - wp_cache_delete($option_name, 'options');
12118 - $processed_count++;
12119 - }
12120 - }
12121 -
12122 - // Clean up any orphaned cache entries
12123 - wp_cache_delete('mxchat_all_chat_limits', 'options');
12124 -
12125 - //error_log("MxChat: Rate limit reset completed. Processed {$processed_count} entries.");
12126 -
12127 - } catch (Exception $e) {
12128 - //error_log('MxChat: Rate limit reset error: ' . $e->getMessage());
12129 - }
12130 -}
12131 -
12132 -
12133 -/**
12134 - * Process HTML links in rate limit messages
12135 - *
12136 - * @param string $message The rate limit message
12137 - * @return string The processed message with safe HTML links
12138 - */
12139 -private function process_rate_limit_message_html($message) {
12140 - // Return original message if empty
12141 - if (empty($message)) {
12142 - return $message;
12143 - }
12144 -
12145 - // First, convert markdown links to HTML
12146 - $message = $this->convert_markdown_links($message);
12147 -
12148 - // Then, auto-convert any remaining plain URLs to links
12149 - $message = $this->auto_link_urls($message);
12150 -
12151 - // Allow basic HTML tags for links and formatting
12152 - $allowed_tags = [
12153 - 'a' => [
12154 - 'href' => true,
12155 - 'target' => true,
12156 - 'rel' => true,
12157 - 'title' => true,
12158 - 'class' => true
12159 - ],
12160 - 'strong' => [],
12161 - 'em' => [],
12162 - 'br' => [],
12163 - 'b' => [],
12164 - 'i' => [],
12165 - 'span' => ['class' => true]
12166 - ];
12167 -
12168 - // Sanitize but allow the specified HTML tags
12169 - $processed_message = wp_kses($message, $allowed_tags);
12170 -
12171 - // If wp_kses stripped everything, return the original message as plain text
12172 - if (empty($processed_message) && !empty($message)) {
12173 - // Strip all HTML and return plain text as fallback
12174 - return wp_strip_all_tags($message);
12175 - }
12176 -
12177 - return $processed_message;
12178 -}
12179 -
12180 -/**
12181 - * Convert markdown links to HTML
12182 - *
12183 - * @param string $text The text to process
12184 - * @return string The text with markdown links converted to HTML
12185 - */
12186 -private function convert_markdown_links($text) {
12187 - // Return original text if empty
12188 - if (empty($text)) {
12189 - return $text;
12190 - }
12191 -
12192 - // Pattern to match markdown links: [text](url)
12193 - $pattern = '/\[([^\]]+)\]\(([^)]+)\)/';
12194 -
12195 - $processed_text = preg_replace_callback($pattern, function($matches) {
12196 - $link_text = $matches[1];
12197 - $url = $matches[2];
12198 -
12199 - // Clean up any trailing punctuation from the URL
12200 - $url = rtrim($url, '.,;:!?');
12201 -
12202 - // Sanitize the link text and URL
12203 - $safe_text = esc_html($link_text);
12204 - $safe_url = esc_url($url);
12205 -
12206 - // Create the HTML link
12207 - return '<a href="' . $safe_url . '" target="_blank" rel="noopener noreferrer">' . $safe_text . '</a>';
12208 - }, $text);
12209 -
12210 - // If preg_replace_callback failed, return original text
12211 - if ($processed_text === null) {
12212 - return $text;
12213 - }
12214 -
12215 - return $processed_text;
12216 -}
12217 -
12218 -/**
12219 - * Auto-convert plain URLs to clickable links
12220 - *
12221 - * @param string $text The text to process
12222 - * @return string The text with URLs converted to links
12223 - */
12224 -private function auto_link_urls($text) {
12225 - // Return original text if empty
12226 - if (empty($text)) {
12227 - return $text;
12228 - }
12229 -
12230 - // Simple pattern that avoids complex lookbehinds
12231 - // This will match URLs that are not already inside href attributes or markdown links
12232 - $pattern = '/(?<!href=["\'])(?<!\]\()https?:\/\/[^\s<>"\')\]]+/i';
12233 -
12234 - $processed_text = preg_replace_callback($pattern, function($matches) {
12235 - $url = $matches[0];
12236 - // Clean up any trailing punctuation that might have been captured
12237 - $url = rtrim($url, '.,;:!?');
12238 -
12239 - // Add target="_blank" and rel="noopener noreferrer" for security
12240 - return '<a href="' . esc_url($url) . '" target="_blank" rel="noopener noreferrer">' . esc_html($url) . '</a>';
12241 - }, $text);
12242 -
12243 - // If preg_replace_callback failed, return original text
12244 - if ($processed_text === null) {
12245 - return $text;
12246 - }
12247 -
12248 - return $processed_text;
12249 -}
12250 -
12251 -
12252 -// Helper function to get client IP address
12253 -private function get_client_ip() {
12254 - // Check for shared internet/ISP IP
12255 - if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
12256 - return sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
12257 - }
12258 -
12259 - // Check for IPs passing through proxies
12260 - if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
12261 - // Use the first value in the comma-separated list
12262 - $forwarded_for = explode(',', sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']));
12263 - return trim($forwarded_for[0]);
12264 - }
12265 -
12266 - if (!empty($_SERVER['REMOTE_ADDR'])) {
12267 - return sanitize_text_field($_SERVER['REMOTE_ADDR']);
12268 - }
12269 -
12270 - // Fallback
12271 - return 'unknown';
12272 -}
12273 -
12274 -/**
12275 - * AJAX handler to get system information for testing panel
12276 - */
12277 -/**
12278 - * AJAX handler to get system information for testing panel
12279 - */
12280 -public function mxchat_get_system_info() {
12281 - // Verify nonce for security
12282 - if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
12283 - wp_send_json_error(['message' => 'Invalid nonce']);
12284 - return;
12285 - }
12286 -
12287 - // Only allow admin users
12288 - if (!current_user_can('administrator')) {
12289 - wp_send_json_error(['message' => 'Unauthorized']);
12290 - return;
12291 - }
12292 -
12293 - // Get system prompt from options
12294 - $system_prompt = isset($this->options['system_prompt_instructions'])
12295 - ? $this->options['system_prompt_instructions']
12296 - : 'No system prompt configured';
12297 -
12298 - // Get selected model
12299 - $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-5.1-chat-latest';
12300 -
12301 - // Check if OpenRouter is being used
12302 - $is_openrouter = ($selected_model === 'openrouter');
12303 - $openrouter_model = '';
12304 -
12305 - if ($is_openrouter) {
12306 - // Get the actual OpenRouter model that's selected
12307 - $openrouter_model = isset($this->options['openrouter_selected_model'])
12308 - ? $this->options['openrouter_selected_model']
12309 - : 'No OpenRouter model selected';
12310 -
12311 - // Update selected_model display to show both
12312 - $selected_model = 'OpenRouter: ' . $openrouter_model;
12313 - }
12314 -
12315 - // Get API key status (just check if they exist, don't expose the keys)
12316 - $api_status = [];
12317 - $api_status['openai'] = !empty($this->options['api_key']);
12318 - $api_status['claude'] = !empty($this->options['claude_api_key']);
12319 - $api_status['gemini'] = !empty($this->options['gemini_api_key']);
12320 - $api_status['xai'] = !empty($this->options['xai_api_key']);
12321 - $api_status['deepseek'] = !empty($this->options['deepseek_api_key']);
12322 - $api_status['openrouter'] = !empty($this->options['openrouter_api_key']);
12323 -
12324 - wp_send_json_success([
12325 - 'system_prompt' => $system_prompt,
12326 - 'selected_model' => $selected_model,
12327 - 'is_openrouter' => $is_openrouter,
12328 - 'openrouter_model' => $openrouter_model,
12329 - 'api_status' => $api_status
12330 - ]);
12331 -}
12332 -
12333 -/**
12334 - * AJAX handler to get similarity threshold
12335 - */
12336 -public function mxchat_get_similarity_threshold() {
12337 - // Verify nonce for security
12338 - if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
12339 - wp_send_json_error(['message' => 'Invalid nonce']);
12340 - return;
12341 - }
12342 -
12343 - // Only allow admin users
12344 - if (!current_user_can('administrator')) {
12345 - wp_send_json_error(['message' => 'Unauthorized']);
12346 - return;
12347 - }
12348 -
12349 - // Get similarity threshold from main options (default 35%)
12350 - $similarity_threshold = isset($this->options['similarity_threshold'])
12351 - ? ((int) $this->options['similarity_threshold']) / 100
12352 - : 0.35;
12353 -
12354 - wp_send_json_success([
12355 - 'threshold' => $similarity_threshold,
12356 - 'threshold_percentage' => ($similarity_threshold * 100) . '%'
12357 - ]);
12358 -}
12359 -
12360 -/**
12361 - * AJAX handler to get knowledge base status
12362 - */
12363 -public function mxchat_get_kb_status() {
12364 - // Verify nonce for security
12365 - if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
12366 - wp_send_json_error(['message' => 'Invalid nonce']);
12367 - return;
12368 - }
12369 -
12370 - // Only allow admin users
12371 - if (!current_user_can('administrator')) {
12372 - wp_send_json_error(['message' => 'Unauthorized']);
12373 - return;
12374 - }
12375 -
12376 - // Check OpenAI Vector Store first (takes priority)
12377 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
12378 - $use_vectorstore = (isset($vectorstore_options['mxchat_use_openai_vectorstore']) && $vectorstore_options['mxchat_use_openai_vectorstore'] === '1');
12379 -
12380 - if ($use_vectorstore) {
12381 - $vectorstore_ids = $vectorstore_options['mxchat_openai_vectorstore_ids'] ?? '';
12382 - $id_count = !empty($vectorstore_ids) ? count(array_filter(array_map('trim', explode(',', $vectorstore_ids)))) : 0;
12383 -
12384 - $kb_info = [
12385 - 'type' => 'OpenAI Vector Store',
12386 - 'status' => 'Active',
12387 - 'documents' => $id_count > 0 ? $id_count . ' vector store' . ($id_count > 1 ? 's' : '') . ' configured' : 'No vector stores configured'
12388 - ];
12389 -
12390 - wp_send_json_success($kb_info);
12391 - return;
12392 - }
12393 -
12394 - // Check Pinecone vs WordPress
12395 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
12396 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1');
12397 -
12398 - $kb_info = [
12399 - 'type' => $use_pinecone ? 'Pinecone' : 'WordPress Database',
12400 - 'status' => 'Active'
12401 - ];
12402 -
12403 - // Get document count
12404 - if ($use_pinecone) {
12405 - $kb_info['documents'] = 'Connected to Pinecone';
12406 - $kb_info['api_configured'] = !empty($addon_options['mxchat_pinecone_api_key']);
12407 - } else {
12408 - // Count documents in WordPress database
12409 - global $wpdb;
12410 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
12411 - $count = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
12412 - $kb_info['documents'] = $count ? $count . ' documents' : 'No documents';
12413 - }
12414 -
12415 - wp_send_json_success($kb_info);
12416 -}
12417 -
12418 -/**
12419 - * AJAX handler to start a completely fresh session (NEW - replaces old clear session)
12420 - */
12421 -public function mxchat_start_fresh_session() {
12422 - // Verify nonce for security
12423 - if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
12424 - wp_send_json_error(['message' => 'Invalid nonce']);
12425 - return;
12426 - }
12427 -
12428 - // Only allow admin users
12429 - if (!current_user_can('administrator')) {
12430 - wp_send_json_error(['message' => 'Unauthorized']);
12431 - return;
12432 - }
12433 -
12434 - $old_session_id = isset($_POST['old_session_id']) ? sanitize_text_field($_POST['old_session_id']) : '';
12435 - $new_session_id = isset($_POST['new_session_id']) ? sanitize_text_field($_POST['new_session_id']) : '';
12436 -
12437 - if (empty($old_session_id)) {
12438 - wp_send_json_error(['message' => 'Old session ID required']);
12439 - return;
12440 - }
12441 -
12442 - // If no new session ID provided, generate one
12443 - if (empty($new_session_id)) {
12444 - // Cryptographically strong session id (plan-0c17b5). Prefix preserved
12445 - // exactly (other code pattern-matches on 'mxchat_chat_'). random_bytes
12446 - // is guaranteed on all supported PHP (7+).
12447 - $new_session_id = 'mxchat_chat_' . bin2hex(random_bytes(16));
12448 - }
12449 -
12450 - // Clear ALL data associated with the old session
12451 - $this->clear_complete_session_data($old_session_id);
12452 -
12453 - // Initialize the new session
12454 - $this->initialize_fresh_session($new_session_id);
12455 -
12456 - wp_send_json_success([
12457 - 'message' => 'Fresh session started successfully',
12458 - 'new_session_id' => $new_session_id,
12459 - 'old_session_id' => $old_session_id
12460 - ]);
12461 -}
12462 -
12463 -/**
12464 - * Clear ALL data associated with a session (ENHANCED)
12465 - */
12466 -private function clear_complete_session_data($session_id) {
12467 - // Clear chat history
12468 - delete_option("mxchat_history_{$session_id}");
12469 -
12470 - // Clear chat mode
12471 - delete_option("mxchat_mode_{$session_id}");
12472 -
12473 - // Clear any PDF/Word transients
12474 - $this->clear_pdf_transients($session_id);
12475 - if (method_exists($this, 'clear_word_transients')) {
12476 - $this->clear_word_transients($session_id);
12477 - }
12478 -
12479 - // Clear agent-related data
12480 - delete_option("mxchat_channel_{$session_id}");
12481 - delete_option("mxchat_agent_name_{$session_id}");
12482 - delete_option("mxchat_email_{$session_id}");
12483 -
12484 - // Clear any recommendation flow state
12485 - delete_option("mxchat_sr_flow_state_{$session_id}");
12486 -
12487 - // Clear any cached embeddings or context
12488 - delete_transient("mxchat_context_{$session_id}");
12489 - delete_transient("mxchat_last_query_{$session_id}");
12490 -
12491 - // Clear any testing data
12492 - delete_transient("mxchat_testing_data_{$session_id}");
12493 -
12494 - // Clear any rate limiting data for this session
12495 - delete_transient("mxchat_rate_limit_{$session_id}");
12496 -
12497 - // Clear any other session-specific transients
12498 - delete_transient("mxchat_waiting_for_pdf_url_{$session_id}");
12499 - delete_transient("mxchat_include_pdf_in_context_{$session_id}");
12500 - delete_transient("mxchat_include_word_in_context_{$session_id}");
12501 -
12502 - // Clear form addon state (pending forms and submitted forms)
12503 - delete_option("mxchat_pending_form_{$session_id}");
12504 - delete_option("mxchat_submitted_forms_{$session_id}");
12505 -
12506 - //error_log("MxChat: Cleared all data for session: {$session_id}");
12507 -}
12508 -
12509 -/**
12510 - * Initialize a fresh session with default data
12511 - */
12512 -private function initialize_fresh_session($session_id) {
12513 - // Set default chat mode
12514 - update_option("mxchat_mode_{$session_id}", 'ai');
12515 -
12516 - //error_log("MxChat: Initialized fresh session: {$session_id}");
12517 -}
12518 -
12519 -/**
12520 - * Helper method to clear Word document transients (if you have Word support)
12521 - */
12522 -private function clear_word_transients($session_id) {
12523 - delete_transient('mxchat_word_url_' . $session_id);
12524 - delete_transient('mxchat_word_filename_' . $session_id);
12525 - delete_transient('mxchat_word_embeddings_' . $session_id);
12526 - delete_transient('mxchat_include_word_in_context_' . $session_id);
12527 -}
12528 -
12529 -/**
12530 - * Simplified testing data capture method (CLEANED UP)
12531 - */
12532 -private function capture_testing_data($user_embedding, $message, $session_id) {
12533 - // Only capture for admin users
12534 - if (!current_user_can('administrator')) {
12535 - return null;
12536 - }
12537 -
12538 - $testing_data = [
12539 - 'query' => $message,
12540 - 'timestamp' => time(),
12541 - 'top_matches' => [],
12542 - 'action_matches' => [] // Add action matches
12543 - ];
12544 -
12545 - // Get similarity threshold
12546 - $similarity_threshold = isset($this->options['similarity_threshold'])
12547 - ? ((int) $this->options['similarity_threshold']) / 100
12548 - : 0.35;
12549 -
12550 - $testing_data['similarity_threshold'] = $similarity_threshold;
12551 -
12552 - // Use the real similarity analysis if available
12553 - if ($this->last_similarity_analysis !== null) {
12554 - $testing_data['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'];
12555 - $testing_data['top_matches'] = $this->last_similarity_analysis['top_matches'];
12556 - $testing_data['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
12557 - } else {
12558 - // Fallback: determine knowledge base type
12559 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
12560 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1');
12561 -
12562 - $testing_data['knowledge_base_type'] = $use_pinecone ? 'Pinecone' : 'WordPress Database';
12563 - }
12564 -
12565 - // Include action analysis if available
12566 - if (isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
12567 - $testing_data['action_matches'] = $this->last_action_analysis;
12568 -
12569 - // Clear it after capturing to avoid stale data
12570 - $this->last_action_analysis = null;
12571 - }
12572 -
12573 - return $testing_data;
12574 -}
12575 -
12576 -
12577 -/**
12578 - * Track URL clicks from chatbot responses
12579 - */
12580 -public function mxchat_track_url_click() {
12581 - // Verify nonce for security
12582 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce($_POST['nonce'])) {
12583 - wp_send_json_error(['message' => 'Invalid nonce']);
12584 - wp_die();
12585 - }
12586 -
12587 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
12588 - $clicked_url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
12589 - $message_context = isset($_POST['message_context']) ? sanitize_textarea_field($_POST['message_context']) : '';
12590 -
12591 - if (empty($session_id) || empty($clicked_url)) {
12592 - wp_send_json_error(['message' => 'Missing required data']);
12593 - wp_die();
12594 - }
12595 -
12596 - global $wpdb;
12597 - $table_name = $wpdb->prefix . 'mxchat_url_clicks';
12598 -
12599 - // Insert click tracking record
12600 - $wpdb->insert(
12601 - $table_name,
12602 - [
12603 - 'session_id' => $session_id,
12604 - 'clicked_url' => $clicked_url,
12605 - 'message_context' => $message_context,
12606 - 'click_timestamp' => current_time('mysql', 1),
12607 - 'user_ip' => $_SERVER['REMOTE_ADDR'],
12608 - 'user_agent' => $_SERVER['HTTP_USER_AGENT']
12609 - ]
12610 - );
12611 -
12612 - wp_send_json_success(['message' => 'Click tracked']);
12613 - wp_die();
12614 -}
12615 -
12616 -/**
12617 - * Get URL click analytics for a session
12618 - */
12619 -public function mxchat_get_url_clicks($session_id) {
12620 - global $wpdb;
12621 - $table_name = $wpdb->prefix . 'mxchat_url_clicks';
12622 -
12623 - $clicks = $wpdb->get_results($wpdb->prepare(
12624 - "SELECT * FROM $table_name WHERE session_id = %s ORDER BY click_timestamp ASC",
12625 - $session_id
12626 - ));
12627 -
12628 - return $clicks;
12629 -}
12630 -/**
12631 - * Track the originating page where chat was started
12632 - */
12633 -public function mxchat_track_originating_page() {
12634 - // Verify nonce
12635 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce($_POST['nonce'])) {
12636 - wp_send_json_error(['message' => 'Invalid nonce']);
12637 - wp_die();
12638 - }
12639 -
12640 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
12641 - $page_url = isset($_POST['page_url']) ? esc_url_raw($_POST['page_url']) : '';
12642 - $page_title = isset($_POST['page_title']) ? sanitize_text_field($_POST['page_title']) : '';
12643 -
12644 - if (empty($session_id)) {
12645 - wp_send_json_error(['message' => 'Missing session ID']);
12646 - wp_die();
12647 - }
12648 -
12649 - global $wpdb;
12650 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
12651 -
12652 - // Check if we've already tracked for this session
12653 - $existing = $wpdb->get_var($wpdb->prepare(
12654 - "SELECT COUNT(*) FROM $table_name
12655 - WHERE session_id = %s
12656 - AND originating_page_url IS NOT NULL",
12657 - $session_id
12658 - ));
12659 -
12660 - if ($existing > 0) {
12661 - wp_send_json_success(['message' => 'Already tracked']);
12662 - wp_die();
12663 - }
12664 -
12665 - // Update the first message in this session with originating page info
12666 - $wpdb->query($wpdb->prepare(
12667 - "UPDATE $table_name
12668 - SET originating_page_url = %s,
12669 - originating_page_title = %s
12670 - WHERE session_id = %s
12671 - ORDER BY timestamp ASC
12672 - LIMIT 1",
12673 - $page_url,
12674 - $page_title,
12675 - $session_id
12676 - ));
12677 -
12678 - wp_send_json_success(['message' => 'Originating page tracked']);
12679 - wp_die();
12680 -}
12681 -
12682 -/**
12683 - * Validate and clean URLs from AI response
12684 - * Removes any URLs that aren't in the knowledge base
12685 - *
12686 - * @param string $response_text The AI-generated response
12687 - * @param array $valid_urls Array of URLs from the knowledge base
12688 - * @return string Cleaned response with invalid URLs removed/flagged
12689 - */
12690 -private function validate_and_clean_urls($response_text, $valid_urls, $session_id = null, $bot_id = null) {
12691 - /**
12692 - * Filter the list of URLs treated as valid (allowlisted) BEFORE the
12693 - * response URL sanitizer strips any link not in the list. Lets a site
12694 - * owner / developer whitelist links their custom function-calling tools
12695 - * return (e.g. session or speaker pages), which are otherwise absent from
12696 - * the RAG/system-prompt-derived list and get stripped to plain text.
12697 - *
12698 - * Purely additive: with no hook registered, apply_filters returns
12699 - * $valid_urls untouched, so there is zero behavior change for anyone who
12700 - * does not use the filter. Applied before the empty-check so a hooked
12701 - * allowlist can participate. (plan-mxchat-20260710-13a471)
12702 - *
12703 - * @param array $valid_urls URLs already known-valid (RAG + system prompt).
12704 - * @param string|null $session_id Current chat session id, if available.
12705 - * @param string|null $bot_id Current bot id, if available.
12706 - */
12707 - $valid_urls = apply_filters('mxchat_valid_urls', $valid_urls, $session_id, $bot_id);
12708 -
12709 - // A bad mu-plugin returning a non-array (or non-string entries) must never
12710 - // fatal the response path — coerce defensively before any use.
12711 - if (!is_array($valid_urls)) {
12712 - $valid_urls = array();
12713 - }
12714 - $valid_urls = array_values(array_filter($valid_urls, static function ($u) {
12715 - return is_string($u) && $u !== '';
12716 - }));
12717 -
12718 - // If no valid URLs provided or empty response, return as-is
12719 - if (empty($valid_urls) || empty($response_text)) {
12720 - //error_log("Validation skipped - empty valid_urls or response");
12721 - return $response_text;
12722 - }
12723 -
12724 - // Extract all URLs from the AI response
12725 - // This regex matches http:// and https:// URLs
12726 - preg_match_all(
12727 - '#\bhttps?://[^\s<>"\')\]]+#i',
12728 - $response_text,
12729 - $matches
12730 - );
12731 -
12732 - // If no URLs found in response, return as-is
12733 - if (empty($matches[0])) {
12734 - //error_log("No URLs found in response");
12735 - return $response_text;
12736 - }
12737 -
12738 - $found_urls = $matches[0];
12739 - $cleaned_response = $response_text;
12740 - $removed_count = 0;
12741 -
12742 - // Normalize valid URLs for comparison (remove trailing slashes, fragments, etc.)
12743 - $normalized_valid_urls = array_map(function($url) {
12744 - // Remove trailing slash
12745 - $url = rtrim($url, '/');
12746 - // Remove URL fragments (#section)
12747 - $url = preg_replace('/#.*$/', '', $url);
12748 - // Remove trailing punctuation that might have been captured
12749 - $url = rtrim($url, '.,;:!?');
12750 - return $url;
12751 - }, $valid_urls);
12752 -
12753 - //error_log("Normalized valid URLs: " . print_r($normalized_valid_urls, true));
12754 -
12755 - foreach ($found_urls as $found_url) {
12756 - // Clean up the found URL (remove trailing punctuation that might have been captured)
12757 - $clean_found_url = rtrim($found_url, '.,;:!?)');
12758 -
12759 - // DEBUG: Log each URL being checked
12760 - //error_log("Checking found URL: " . $found_url);
12761 -
12762 - // Normalize for comparison
12763 - $normalized_found = rtrim($clean_found_url, '/');
12764 - $normalized_found = preg_replace('/#.*$/', '', $normalized_found);
12765 -
12766 - //error_log("Normalized found URL: " . $normalized_found);
12767 -
12768 - // Check if this URL exists in our valid URLs list
12769 - $is_valid = false;
12770 -
12771 - //error_log("Starting validation checks for: " . $normalized_found);
12772 -
12773 - // First, try exact match
12774 - if (in_array($normalized_found, $normalized_valid_urls)) {
12775 - $is_valid = true;
12776 - //error_log("EXACT MATCH FOUND");
12777 - } else {
12778 - //error_log("No exact match, checking variations...");
12779 - // If no exact match, check if it's a variation (with query params, etc.)
12780 - foreach ($normalized_valid_urls as $valid_url) {
12781 - //error_log(" Comparing against valid URL: " . $valid_url);
12782 -
12783 - // Check if the found URL starts with a valid URL (handles query params)
12784 - if (strpos($normalized_found, $valid_url) === 0) {
12785 - // Check what comes after the valid URL
12786 - $remainder = substr($normalized_found, strlen($valid_url));
12787 -
12788 - // Only valid if:
12789 - // 1. Exact match (remainder is empty)
12790 - // 2. Query params (starts with ?)
12791 - // 3. Fragment (starts with #)
12792 - if (empty($remainder) || $remainder[0] === '?' || $remainder[0] === '#') {
12793 - $is_valid = true;
12794 - //error_log(" MATCH: Found URL is valid variation of base URL");
12795 - break;
12796 - } else {
12797 - //error_log(" NOT A MATCH: Found URL extends path beyond valid URL (remainder: " . $remainder . ")");
12798 - }
12799 - }
12800 - // Also check the reverse (in case valid URL has query params)
12801 - if (strpos($valid_url, $normalized_found) === 0) {
12802 - $is_valid = true;
12803 - //error_log(" MATCH: Valid URL starts with found URL");
12804 - break;
12805 - }
12806 - }
12807 -
12808 - if (!$is_valid) {
12809 - //error_log("NO MATCH FOUND - URL should be removed");
12810 - }
12811 - }
12812 -
12813 - // If URL is not valid, remove it from the response
12814 - if (!$is_valid) {
12815 - // Log the removal for debugging
12816 - //error_log("MxChat: Removed hallucinated URL: " . $found_url);
12817 - //error_log("MxChat: Valid URLs were: " . implode(', ', array_slice($normalized_valid_urls, 0, 5)));
12818 -
12819 - $removed_count++;
12820 -
12821 - // Check if URL is part of a markdown link: [text](url)
12822 - $markdown_pattern = '/\[([^\]]+)\]\(' . preg_quote($found_url, '/') . '\)/';
12823 - if (preg_match($markdown_pattern, $cleaned_response)) {
12824 - //error_log("Found markdown link, removing but keeping text");
12825 - // Remove the markdown link but keep the text
12826 - $cleaned_response = preg_replace($markdown_pattern, '$1', $cleaned_response);
12827 - }
12828 - // Check if URL is part of an HTML link: <a href="url">text</a>
12829 - else if (preg_match('/<a[^>]*href=["\']' . preg_quote($found_url, '/') . '["\'][^>]*>(.*?)<\/a>/i', $cleaned_response, $link_match)) {
12830 - //error_log("Found HTML link, removing but keeping text");
12831 - // Remove the HTML link but keep the text
12832 - $link_text = $link_match[1];
12833 - $cleaned_response = preg_replace(
12834 - '/<a[^>]*href=["\']' . preg_quote($found_url, '/') . '["\'][^>]*>.*?<\/a>/i',
12835 - $link_text,
12836 - $cleaned_response
12837 - );
12838 - }
12839 - // Otherwise just remove the bare URL
12840 - else {
12841 - //error_log("Removing bare URL");
12842 - $cleaned_response = str_replace($found_url, '', $cleaned_response);
12843 - }
12844 - }
12845 - }
12846 -
12847 - // Log summary if any URLs were removed
12848 - if ($removed_count > 0) {
12849 - //error_log("MxChat: URL Validation Summary - Removed {$removed_count} hallucinated URL(s)");
12850 - } else {
12851 - //error_log("MxChat: URL Validation Summary - No URLs removed, all were valid");
12852 - }
12853 -
12854 - // Clean up any double spaces or awkward punctuation left behind
12855 - // IMPORTANT: Only collapse horizontal whitespace (spaces/tabs), preserve newlines for markdown formatting
12856 - $cleaned_response = preg_replace('/[^\S\n]+/', ' ', $cleaned_response); // Collapse spaces/tabs but NOT newlines
12857 - $cleaned_response = preg_replace('/[^\S\n]+([.,;:!?])/', '$1', $cleaned_response); // Same for punctuation cleanup
12858 -
12859 - //error_log("Final cleaned response: " . $cleaned_response);
12860 -
12861 - return trim($cleaned_response);
12862 -}
12863 -
12864 -/**
12865 - * AJAX handler to get current chat mode for a session
12866 - */
12867 -public function mxchat_get_current_chat_mode() {
12868 - // Verify nonce for security
12869 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce($_POST['nonce'])) {
12870 - wp_send_json_error(['message' => 'Invalid nonce']);
12871 - wp_die();
12872 - }
12873 -
12874 - $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
12875 -
12876 - if (empty($session_id)) {
12877 - wp_send_json_error(['message' => 'Session ID missing']);
12878 - wp_die();
12879 - }
12880 -
12881 - // Get the current chat mode for this session
12882 - $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
12883 -
12884 - wp_send_json_success([
12885 - 'chat_mode' => $chat_mode
12886 - ]);
12887 - wp_die();
12888 -}
12889 -
12890 -
12891 -
12892 -}
12893 -?>
1 +<?php
2 +if (!defined('ABSPATH')) {
3 + exit;
4 +}
5 +
6 +class MxChat_Integrator {
7 + private $options;
8 + private $chat_count;
9 +
10 +public function __construct() {
11 + $this->options = get_option('mxchat_options');
12 + $this->chat_count = get_option('mxchat_chat_count', 0);
13 +
14 + // Add WooCommerce hooks
15 + add_action('wp_insert_post', array($this, 'mxchat_handle_product_change'), 10, 3);
16 +
17 + // Ensure embeddings are removed when a product is moved to trash or permanently deleted
18 + add_action('wp_trash_post', array($this, 'mxchat_handle_product_delete'));
19 + add_action('before_delete_post', array($this, 'mxchat_handle_product_delete'));
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 +
35 +
36 + if (!wp_next_scheduled('mxchat_reset_rate_limits')) {
37 + wp_schedule_event(time(), 'daily', 'mxchat_reset_rate_limits');
38 + }
39 +
40 + add_action('mxchat_reset_rate_limits', array($this, 'mxchat_reset_rate_limits'));
41 +}
42 +
43 +public function mxchat_handle_product_change($post_id, $post, $update) {
44 + // Ensure this is a product post type
45 + if ($post->post_type !== 'product') {
46 + return;
47 + }
48 +
49 + // Only generate embeddings if the product is published
50 + if ($post->post_status === 'publish') {
51 + // Delay the embedding slightly to ensure all product data is available
52 + add_action('shutdown', function() use ($post_id) {
53 + $product = wc_get_product($post_id);
54 + if ($product && $product->get_price() !== '') {
55 + $this->mxchat_store_product_embedding($product);
56 + } else {
57 + // Optionally, log or handle the case where product data is incomplete
58 + // error_log("Product {$post_id} does not have complete data. Embedding not generated.");
59 + }
60 + });
61 + }
62 +}
63 +
64 +public function mxchat_handle_product_delete($post_id) {
65 + if (get_post_type($post_id) !== 'product') {
66 + return;
67 + }
68 +
69 + global $wpdb;
70 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
71 +
72 + // Delete the embedding associated with this product
73 + $wpdb->delete($table_name, array('source_url' => get_permalink($post_id)), array('%s'));
74 +}
75 +
76 +private function mxchat_store_product_embedding($product) {
77 + if (isset($this->options['enable_woocommerce_integration']) && $this->options['enable_woocommerce_integration'] === '1') {
78 +
79 + $source_url = get_permalink($product->get_id());
80 + $regular_price = $product->get_regular_price();
81 + $sale_price = $product->get_sale_price();
82 + $price = $sale_price ?: $regular_price;
83 +
84 + $description = $product->get_description() . "\n\n" .
85 + "Short Description: " . $product->get_short_description() . "\n" .
86 + "Price: " . $regular_price . "\n" .
87 + "Sale Price: " . ($sale_price ?: 'N/A') . "\n" .
88 + "SKU: " . $product->get_sku();
89 +
90 + global $wpdb;
91 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
92 +
93 + // Delete any existing embedding for this product
94 + $wpdb->delete($table_name, array('source_url' => $source_url), array('%s'));
95 +
96 + // Submit the new content and embedding to the database
97 + MxChat_Utils::submit_content_to_db($description, $source_url, $this->options['api_key']);
98 + }
99 +}
100 +
101 +
102 +
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' => 'Session ID missing.']);
114 + wp_die();
115 + }
116 +
117 + $session_id = sanitize_text_field($_POST['session_id']);
118 + $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history
119 +
120 + if (empty($history)) {
121 + wp_send_json_error(['message' => 'No history found.']);
122 + wp_die();
123 + }
124 +
125 + wp_send_json_success(['conversation' => $history]);
126 + wp_die();
127 +}
128 +private function mxchat_fetch_conversation_history_for_ajax($session_id) {
129 + $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history based on session ID
130 + $formatted_history = [];
131 +
132 + // Format the history to align with the expected structure for OpenAI
133 + foreach ($history as $entry) {
134 + $formatted_history[] = [
135 + 'role' => $entry['role'], // Ensure this matches 'user' or 'assistant'
136 + 'content' => $entry['content']
137 + ];
138 + }
139 +
140 + return $formatted_history;
141 +}
142 +
143 +
144 +private function mxchat_save_chat_message($session_id, $role, $message) {
145 + global $wpdb;
146 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
147 +
148 + $user_id = is_user_logged_in() ? get_current_user_id() : 0;
149 + $user_identifier = MxChat_User::mxchat_get_user_identifier();
150 + $user_email = MxChat_User::mxchat_get_user_email();
151 +
152 + $history = get_option("mxchat_history_{$session_id}", []);
153 + $history[] = ['role' => $role, 'content' => $message];
154 + update_option("mxchat_history_{$session_id}", $history);
155 +
156 + $wpdb->insert($table_name, [
157 + 'user_id' => $user_id,
158 + 'user_identifier' => $user_identifier,
159 + 'user_email' => $user_email,
160 + 'session_id' => $session_id,
161 + 'role' => $role,
162 + 'message' => $message,
163 + 'timestamp' => current_time('mysql', 1)
164 + ]);
165 +}
166 +
167 +
168 +public function mxchat_handle_chat_request() {
169 + global $wpdb;
170 +
171 + // Get and sanitize the user identifier
172 + $user_id = $this->mxchat_get_user_identifier();
173 + $user_id = sanitize_key($user_id);
174 +
175 + // Setup rate limiting
176 + $rate_limit_transient_key = 'mxchat_chat_limit_' . $user_id;
177 + $chat_count = get_transient($rate_limit_transient_key) ?: 0;
178 +
179 + // Retrieve the session ID from the client's POST data
180 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
181 +
182 + if (empty($session_id)) {
183 + // Handle the case where the session ID is missing
184 + wp_send_json_error('Session ID is missing.');
185 + wp_die();
186 + }
187 +
188 + // No need to set transients or server-side cookies for the session ID
189 +
190 + // Check rate limit
191 + $rate_limit_option = $this->options['rate_limit'] ?? 'unlimited';
192 + if ($rate_limit_option !== 'unlimited' && $chat_count >= intval($rate_limit_option)) {
193 + wp_send_json_error(['message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.']);
194 + wp_die();
195 + }
196 + set_transient($rate_limit_transient_key, $chat_count + 1, DAY_IN_SECONDS);
197 +
198 + // Validate and sanitize the incoming message
199 + if (empty($_POST['message'])) {
200 + wp_send_json_error('No message received');
201 + wp_die();
202 + }
203 +
204 + $message = sanitize_text_field($_POST['message']);
205 + $this->mxchat_save_chat_message($session_id, 'user', $message);
206 +
207 + // Track email capture and WooCommerce flows with individual transients
208 + $email_capture_prompt = get_transient('mxchat_email_capture_' . $user_id);
209 + $interaction_count = get_transient('mxchat_email_interaction_count_' . $user_id) ?: 0;
210 + $woocommerce_prompt = get_transient('mxchat_woocommerce_prompt_' . $user_id);
211 +
212 + // Handle email capture flow
213 + if ($email_capture_prompt) {
214 + if (preg_match('/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/i', $message, $matches)) {
215 + $email = $matches[0];
216 + $this->add_email_to_loops($email);
217 + $response = $this->options['email_capture_response'] ?? 'Thank you for providing your email! You\'ve been added to our list.';
218 +
219 + delete_transient('mxchat_email_capture_' . $user_id);
220 + delete_transient('mxchat_email_interaction_count_' . $user_id);
221 + delete_transient('mxchat_woocommerce_prompt_' . $user_id);
222 +
223 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
224 + wp_send_json(['message' => $response]);
225 + wp_die();
226 + } else {
227 + if ($interaction_count >= 3) {
228 + delete_transient('mxchat_email_capture_' . $user_id);
229 + delete_transient('mxchat_email_interaction_count_' . $user_id);
230 + } else {
231 + set_transient('mxchat_email_interaction_count_' . $user_id, ++$interaction_count, 5 * MINUTE_IN_SECONDS);
232 + }
233 + }
234 + }
235 +
236 + // Handle WooCommerce add-to-cart flow
237 + if (class_exists('WooCommerce') && stripos($message, 'add to cart') !== false) {
238 + $last_product_id = get_transient('mxchat_last_discussed_product_' . $user_id);
239 + if ($last_product_id) {
240 + $added = WC()->cart->add_to_cart($last_product_id);
241 + $product = wc_get_product($last_product_id);
242 +
243 + if ($added) {
244 + $response = "The product '{$product->get_name()}' has been added to your cart. To proceed to checkout, please type 'checkout'.";
245 + set_transient('mxchat_checkout_prompt_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
246 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
247 + wp_send_json(['message' => $response]);
248 + wp_die();
249 + } else {
250 + $response = "Sorry, I couldn't add the product to your cart. Please try again.";
251 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
252 + wp_send_json(['message' => $response]);
253 + wp_die();
254 + }
255 + } else {
256 + $response = "I couldn't find the product to add. Please mention the product name again.";
257 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
258 + wp_send_json(['message' => $response]);
259 + wp_die();
260 + }
261 + }
262 +
263 + // Handle checkout response
264 + if (class_exists('WooCommerce') && stripos($message, 'checkout') !== false) {
265 + $checkout_prompt = get_transient('mxchat_checkout_prompt_' . $user_id);
266 + if ($checkout_prompt && WC()->cart->get_cart_contents_count() > 0) {
267 + $checkout_url = wc_get_checkout_url();
268 + $response = "Great! Redirecting you to the checkout page...";
269 + delete_transient('mxchat_checkout_prompt_' . $user_id);
270 +
271 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
272 + wp_send_json(['message' => $response, 'redirect_url' => $checkout_url]);
273 + wp_die();
274 + } else {
275 + $response = "It seems like there is no active checkout prompt or no items in your cart. Please add a product to the cart first.";
276 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
277 + wp_send_json(['message' => $response]);
278 + wp_die();
279 + }
280 + }
281 +
282 + // Handle order-related queries
283 + if (class_exists('WooCommerce') && MxChat_WooCommerce::mxchat_is_order_related_query($message)) {
284 + $response = MxChat_WooCommerce::mxchat_fetch_user_orders_details();
285 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
286 + wp_send_json(['message' => $response]);
287 + wp_die();
288 + }
289 +
290 + // Check for trigger keywords to initiate email capture
291 + $trigger_keywords = explode(',', $this->options['trigger_keywords'] ?? '');
292 + if (!empty($trigger_keywords) && $trigger_keywords[0] !== '') {
293 + foreach ($trigger_keywords as $keyword) {
294 + if (stripos($message, trim($keyword)) !== false) {
295 + $response = $this->options['triggered_phrase_response'] ?? "Would you like to join our mailing list? Please provide your email below.";
296 + set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
297 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
298 + wp_send_json(['message' => $response]);
299 + wp_die();
300 + }
301 + }
302 + }
303 +
304 + // Store product discussion in transient
305 + $last_discussed_product_id = MxChat_WooCommerce::mxchat_extract_product_id_from_message($message);
306 + if ($last_discussed_product_id) {
307 + set_transient('mxchat_last_discussed_product_' . $user_id, $last_discussed_product_id, 3600);
308 + }
309 +
310 + // Standard chat processing
311 + $user_message_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
312 + if (!is_array($user_message_embedding)) {
313 + wp_send_json_error('Error processing your message.');
314 + wp_die();
315 + }
316 +
317 + $relevant_content = $this->mxchat_find_relevant_content($user_message_embedding);
318 + $conversation_history = $this->mxchat_fetch_conversation_history_for_ajax($session_id);
319 + $this->mxchat_increment_chat_count();
320 + $response = $this->mxchat_generate_response(
321 + $relevant_content,
322 + $this->options['api_key'], // OpenAI API Key
323 + $this->options['xai_api_key'], // X.AI API Key
324 + $this->options['claude_api_key'], // Claude API Key
325 + $conversation_history
326 + );
327 +
328 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
329 + wp_send_json(['message' => $response, 'session_id' => $session_id]);
330 + wp_die();
331 +}
332 +
333 +
334 +// Function to add the captured email to Loops
335 +private function add_email_to_loops($email) {
336 + $api_key = $this->options['loops_api_key'];
337 + $mailing_list_id = $this->options['loops_mailing_list'];
338 +
339 + $data = array(
340 + 'email' => $email,
341 + 'subscribed' => true,
342 + 'source' => 'MxChat AI Chatbot',
343 + 'mailingLists' => array($mailing_list_id => true),
344 + );
345 +
346 + $url = "https://app.loops.so/api/v1/contacts/create";
347 + $args = array(
348 + 'body' => json_encode($data),
349 + 'headers' => array(
350 + 'Authorization' => 'Bearer ' . $api_key,
351 + 'Content-Type' => 'application/json',
352 + ),
353 + 'method' => 'POST',
354 + 'timeout' => 45,
355 + );
356 +
357 + wp_remote_post($url, $args);
358 +}
359 +
360 +
361 +private function mxchat_get_user_identifier() {
362 + return MxChat_User::mxchat_get_user_identifier();
363 +}
364 +
365 +
366 +
367 + private function mxchat_generate_embedding($text, $api_key) {
368 + $endpoint = 'https://api.openai.com/v1/embeddings';
369 +
370 + $body = wp_json_encode([
371 + 'input' => $text,
372 + 'model' => 'text-embedding-ada-002'
373 + ]);
374 +
375 + $args = [
376 + 'body' => $body,
377 + 'headers' => [
378 + 'Content-Type' => 'application/json',
379 + 'Authorization' => 'Bearer ' . $api_key,
380 + ],
381 + 'timeout' => 60,
382 + 'redirection' => 5,
383 + 'blocking' => true,
384 + 'httpversion' => '1.0',
385 + 'sslverify' => true,
386 + ];
387 +
388 + $response = wp_remote_post($endpoint, $args);
389 +
390 + if (is_wp_error($response)) {
391 + return null;
392 + }
393 +
394 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
395 +
396 + if (isset($response_body['data'][0]['embedding']) && is_array($response_body['data'][0]['embedding'])) {
397 + return $response_body['data'][0]['embedding'];
398 + } else {
399 + return null;
400 + }
401 + }
402 +
403 +private function mxchat_find_relevant_content($user_embedding) {
404 + global $wpdb;
405 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
406 +
407 + // Define a cache key for embeddings
408 + $cache_key = 'mxchat_system_prompt_embeddings';
409 +
410 + // Attempt to get the embeddings from the cache
411 + $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
412 +
413 + if ($embeddings === false) {
414 + // Cache miss, query the database and cache the results
415 + $query = "SELECT id, embedding_vector FROM {$system_prompt_table}";
416 + $embeddings = $wpdb->get_results($query);
417 +
418 + if ($embeddings === null || empty($embeddings)) {
419 + //error_log("No embeddings found in the database.");
420 + return null; // Return null to handle no embeddings gracefully
421 + }
422 +
423 + // Cache the results if successful
424 + wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600); // Cache for 1 hour
425 + }
426 +
427 + $most_relevant_id = null;
428 + $highest_similarity = -INF;
429 +
430 + foreach ($embeddings as $embedding) {
431 + $database_embedding = maybe_unserialize($embedding->embedding_vector);
432 +
433 + // Debugging: Log the embeddings
434 + // if (!is_array($database_embedding)) {
435 + // error_log("Invalid database embedding format for ID {$embedding->id}: " . print_r($database_embedding, true));
436 + // continue;
437 + // }
438 +
439 + if (is_array($user_embedding)) {
440 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
441 +
442 + // Debugging: Log the similarity score
443 + // error_log("Calculated similarity for ID {$embedding->id}: {$similarity}");
444 +
445 + if ($similarity > $highest_similarity) {
446 + $highest_similarity = $similarity;
447 + $most_relevant_id = $embedding->id;
448 + }
449 + } else {
450 + // error_log("User embedding is not an array. Embedding data: " . print_r($user_embedding, true));
451 + }
452 + }
453 +
454 + if ($most_relevant_id !== null) {
455 + // Fetch content with product links
456 + return $this->fetch_content_with_product_links($most_relevant_id);
457 + }
458 +
459 + //error_log("No relevant content found. Most relevant ID was null.");
460 + return null; // Return null if no relevant content is found
461 +}
462 +
463 +
464 +private function fetch_content_with_product_links($most_relevant_id) {
465 + global $wpdb;
466 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
467 +
468 + // Fetch the article content and associated product URL
469 + $query = $wpdb->prepare("SELECT article_content, source_url FROM {$system_prompt_table} WHERE id = %d", $most_relevant_id);
470 + $result = $wpdb->get_row($query);
471 +
472 + if ($result) {
473 + // Append the product link to the content if available
474 + $content = $result->article_content;
475 + if (!empty($result->source_url)) {
476 + $content .= "\n\nFor more details, check out this product: " . esc_url($result->source_url);
477 + }
478 + return $content;
479 + }
480 +
481 + return null;
482 +}
483 +
484 +private function mxchat_generate_response($relevant_content, $api_key, $xai_api_key, $claude_api_key, $conversation_history) {
485 + if (!$relevant_content) {
486 + return "I'm sorry, I couldn't find relevant information on that topic.";
487 + }
488 +
489 + // Check the selected model
490 + $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-3.5-turbo';
491 +
492 + // Call the appropriate function based on the selected model
493 + if (strpos($selected_model, 'claude') !== false) {
494 + return $this->mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content);
495 + } elseif ($selected_model === 'grok-beta') {
496 + return $this->mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content);
497 + } else {
498 + return $this->mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content);
499 + }
500 +}
501 +
502 +private function mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content) {
503 + // Get system prompt instructions from options
504 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
505 +
506 + // Add system prompt to relevant content
507 + $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
508 +
509 + // Prepend system instructions to the conversation history
510 + array_unshift($conversation_history, [
511 + 'role' => 'system',
512 + 'content' => "Here are your instructions: " . $content_with_instructions
513 + ]);
514 +
515 + // Ensure consistency: Replace 'bot' role with 'assistant' in conversation history
516 + foreach ($conversation_history as &$message) {
517 + if ($message['role'] === 'bot') {
518 + $message['role'] = 'assistant';
519 + }
520 + }
521 +
522 + // Build the request body
523 + $body = json_encode([
524 + 'model' => $selected_model,
525 + 'messages' => $conversation_history,
526 + 'temperature' => 0.8,
527 + 'stream' => false
528 + ]);
529 +
530 + // Set up the API request
531 + $args = [
532 + 'body' => $body,
533 + 'headers' => [
534 + 'Content-Type' => 'application/json',
535 + 'Authorization' => 'Bearer ' . $api_key,
536 + ],
537 + 'timeout' => 60,
538 + 'redirection' => 5,
539 + 'blocking' => true,
540 + 'httpversion' => '1.0',
541 + 'sslverify' => true,
542 + ];
543 +
544 + // Make the API request
545 + $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
546 +
547 + // Process the response
548 + if (is_wp_error($response)) {
549 + return "Sorry, there was an error processing your request.";
550 + }
551 +
552 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
553 +
554 + if (isset($response_body['choices'][0]['message']['content'])) {
555 + return trim($response_body['choices'][0]['message']['content']);
556 + } else {
557 + return "Sorry, I couldn't process that request.";
558 + }
559 +}
560 +
561 +private function mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content) {
562 + // Get system prompt instructions from options
563 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
564 +
565 + // Add system prompt to relevant content
566 + $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
567 +
568 + // Prepend system instructions to the conversation history
569 + array_unshift($conversation_history, [
570 + 'role' => 'system',
571 + 'content' => "Here are your instructions: " . $content_with_instructions
572 + ]);
573 +
574 + // Ensure consistency: Replace 'bot' role with 'assistant' in conversation history
575 + foreach ($conversation_history as &$message) {
576 + if ($message['role'] === 'bot') {
577 + $message['role'] = 'assistant';
578 + }
579 + }
580 +
581 + // Build the request body
582 + $body = json_encode([
583 + 'model' => $selected_model,
584 + 'messages' => $conversation_history,
585 + 'temperature' => 0.8,
586 + 'stream' => false
587 + ]);
588 +
589 + // Set up the API request
590 + $args = [
591 + 'body' => $body,
592 + 'headers' => [
593 + 'Content-Type' => 'application/json',
594 + 'Authorization' => 'Bearer ' . $xai_api_key,
595 + ],
596 + 'timeout' => 60,
597 + 'redirection' => 5,
598 + 'blocking' => true,
599 + 'httpversion' => '1.0',
600 + 'sslverify' => true,
601 + ];
602 +
603 + // Make the API request
604 + $response = wp_remote_post('https://api.x.ai/v1/chat/completions', $args);
605 +
606 + // Process the response
607 + if (is_wp_error($response)) {
608 + return "Sorry, there was an error processing your request.";
609 + }
610 +
611 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
612 +
613 + if (isset($response_body['choices'][0]['message']['content'])) {
614 + return trim($response_body['choices'][0]['message']['content']);
615 + } else {
616 + return "Sorry, I couldn't process that request.";
617 + }
618 +}
619 +
620 +private function mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content) {
621 + // The system prompt should be passed at the beginning of the conversation
622 + $system_prompt = "You are an AI Chatbot assistant for MxChat.AI. Your role is to answer questions about the MxChat WordPress plugin and its features. Provide concise and helpful responses.";
623 +
624 + // If conversation history is empty, add the system prompt
625 + if (empty($conversation_history)) {
626 + $conversation_history[] = [
627 + 'role' => 'system',
628 + 'content' => $system_prompt
629 + ];
630 + }
631 +
632 + // Add the new user message to the conversation
633 + $conversation_history[] = [
634 + 'role' => 'user',
635 + 'content' => $relevant_content
636 + ];
637 +
638 + // Build the request body
639 + $body = json_encode([
640 + 'model' => $selected_model,
641 + 'max_tokens' => 1000,
642 + 'temperature' => 0.8,
643 + 'messages' => $conversation_history
644 + ]);
645 +
646 + // Set up the API request
647 + $args = [
648 + 'body' => $body,
649 + 'headers' => [
650 + 'Content-Type' => 'application/json',
651 + 'x-api-key' => $claude_api_key,
652 + 'anthropic-version' => '2023-06-01',
653 + ],
654 + 'timeout' => 60,
655 + 'redirection' => 5,
656 + 'blocking' => true,
657 + 'httpversion' => '1.0',
658 + 'sslverify' => true,
659 + ];
660 +
661 + // Make the API request
662 + $response = wp_remote_post('https://api.anthropic.com/v1/messages', $args);
663 +
664 + // Process the response
665 + if (is_wp_error($response)) {
666 + return "Sorry, there was an error processing your request.";
667 + }
668 +
669 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
670 +
671 + if (isset($response_body['content'][0]['text'])) {
672 + return trim($response_body['content'][0]['text']);
673 + } else {
674 + return "Sorry, I couldn't process that request.";
675 + }
676 +}
677 +
678 +
679 +public function mxchat_dismiss_pre_chat_message() {
680 + // Get and sanitize the user identifier
681 + $user_id = $this->mxchat_get_user_identifier();
682 + $user_id = sanitize_key($user_id);
683 +
684 + // Set a transient to track that the user has dismissed the pre-chat message
685 + $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
686 + set_transient($transient_key, true, DAY_IN_SECONDS);
687 +
688 + wp_send_json_success();
689 +}
690 +
691 +public function mxchat_check_pre_chat_message_status() {
692 + // Get and sanitize the user identifier
693 + $user_id = $this->mxchat_get_user_identifier();
694 + $user_id = sanitize_key($user_id);
695 +
696 + // Check if the transient exists (i.e., if the message was dismissed)
697 + $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
698 + $dismissed = get_transient($transient_key);
699 +
700 + // Log the result to see if it's being set correctly
701 + //error_log("Check pre-chat message dismissed for $user_id: " . ($dismissed ? 'Yes' : 'No'));
702 +
703 + if ($dismissed) {
704 + wp_send_json_success(['dismissed' => true]);
705 + } else {
706 + wp_send_json_success(['dismissed' => false]);
707 + }
708 +
709 + wp_die();
710 +}
711 +
712 +
713 +
714 +
715 +
716 + private function mxchat_calculate_cosine_similarity($vectorA, $vectorB) {
717 + if (!is_array($vectorA) || !is_array($vectorB) || empty($vectorA) || empty($vectorB)) {
718 + return 0;
719 + }
720 +
721 + $dotProduct = array_sum(array_map(function ($a, $b) {
722 + return $a * $b;
723 + }, $vectorA, $vectorB));
724 + $normA = sqrt(array_sum(array_map(function ($a) {
725 + return $a * $a;
726 + }, $vectorA)));
727 + $normB = sqrt(array_sum(array_map(function ($b) {
728 + return $b * $b;
729 + }, $vectorB)));
730 +
731 + if ($normA == 0 || $normB == 0) {
732 + return 0;
733 + }
734 +
735 + return $dotProduct / ($normA * $normB);
736 + }
737 +
738 + public function mxchat_enqueue_scripts_styles() {
739 + // Define version numbers for the styles and scripts
740 + $chat_style_version = '1.2'; // Replace with your actual version
741 + $chat_script_version = '1.2'; // Replace with your actual version
742 +
743 + // Correct path to the script file
744 + wp_enqueue_script(
745 + 'mxchat-chat-js', // Handle for the script
746 + plugin_dir_url(__FILE__) . '../js/chat-script.js', // Correct path using __FILE__
747 + array('jquery'), // Dependencies
748 + $chat_script_version, // Version for cache busting
749 + true // Load script in footer
750 + );
751 +
752 + // Enqueue the CSS file similarly
753 + wp_enqueue_style(
754 + 'mxchat-chat-css', // Handle for the style
755 + plugin_dir_url(__FILE__) . '../css/chat-style.css', // Correct path using __FILE__
756 + array(), // No dependencies
757 + $chat_style_version // Version for cache busting
758 + );
759 +
760 + // Fetch options from the database
761 + $this->options = get_option('mxchat_options');
762 +
763 + // Prepare settings to pass to JavaScript
764 + $style_settings = array(
765 + 'ajax_url' => admin_url('admin-ajax.php'),
766 + 'nonce' => wp_create_nonce('mxchat_chat_nonce'), // Nonce for security
767 + 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
768 + 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off'
769 + );
770 +
771 + // Localize the script with necessary data
772 + wp_localize_script('mxchat-chat-js', 'mxchatChat', $style_settings);
773 + }
774 +
775 +
776 +
777 + public function mxchat_reset_rate_limits() {
778 + global $wpdb;
779 +
780 + // Define a cache key pattern for rate limits
781 + $cache_key_pattern = 'mxchat_chat_limit_%';
782 +
783 + // Retrieve all option names matching the pattern
784 + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
785 + $option_names = $wpdb->get_col("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
786 +
787 + // db call ok; no-cache ok
788 + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- db call ok
789 + $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
790 +
791 + // Clear the relevant cache entries
792 + foreach ($option_names as $option_name) {
793 + wp_cache_delete($option_name, 'options');
794 + }
795 +
796 + // Optionally, clear a general cache if you have one
797 + wp_cache_delete('mxchat_all_chat_limits', 'options');
798 + }
799 +
800 +
801 +private function mxchat_fetch_woocommerce_products() {
802 + // Ensure WooCommerce is active
803 + if (!class_exists('WooCommerce')) {
804 + return [];
805 + }
806 +
807 + $args = array(
808 + 'post_type' => 'product',
809 + 'post_status' => 'publish',
810 + 'posts_per_page' => -1,
811 + );
812 +
813 + $products = get_posts($args);
814 + $product_data = [];
815 +
816 + foreach ($products as $product) {
817 + $product_id = $product->ID;
818 + $product_obj = wc_get_product($product_id);
819 +
820 + $product_data[] = array(
821 + 'id' => $product_id,
822 + 'name' => $product_obj->get_name(),
823 + 'description' => $product_obj->get_description(),
824 + 'short_description' => $product_obj->get_short_description(),
825 + 'url' => get_permalink($product_id),
826 + 'price' => $product_obj->get_regular_price(),
827 + 'sale_price' => $product_obj->get_sale_price(),
828 + 'stock_status' => $product_obj->get_stock_status(),
829 + 'sku' => $product_obj->get_sku(),
830 + 'in_stock' => $product_obj->is_in_stock(),
831 + 'total_sales' => $product_obj->get_total_sales(),
832 + );
833 + }
834 +
835 + return $product_data;
836 +}
837 +
838 +}
839 +?>