PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 2.1.7
MxChat – AI Chatbot & Content Generation for WordPress v2.1.7
3.2.22 3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 All 153 releases
← All changes | includes/class-mxchat-integrator.php +4453 -14128 3.2.192.1.7 View file →
@@ -1,14128 +1,4453 @@
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 - // plan-mxchat-20260813-470f68 — per-message trace of the AI Tools that fired.
27 - // Request-scoped: one entry per tool EXECUTION (so a multi-round loop records
28 - // every round), appended in mxchat_fc_execute_tool and folded into the
29 - // message's rag_context at save time. Never a new table — an additive key
30 - // alongside the existing rag/action channels.
31 - private $fc_tool_records = array();
32 - // plan-mxchat-20260722-59bc1b — {context} placeholder support. When the
33 - // owner's system instructions carry {context}, the assembled KB block is
34 - // stashed here (instead of being appended to $context_content) and
35 - // get_system_instructions() injects it at the token's position. Null until
36 - // the per-turn KB assembly has run — the early URL-extraction call to
37 - // get_system_instructions() must NOT consume the token.
38 - private $context_kb_block = null;
39 - private $word_handler;
40 - private $last_similarity_analysis = null;
41 - private $current_valid_urls = [];
42 - private $last_vectorstore_error = null;
43 - private $last_pdf_embedding_error = null; // First embedding failure reason from the most recent PDF split (104a75)
44 - private $is_streaming = false; // ADDED: Track if current request is streaming
45 - private $streaming_headers_sent = false; // Track if streaming headers have been sent
46 - private $pending_originating_page = null; // Originating page captured at session start, consumed on row insert
47 - private $current_action_instruction = null; // Success-message instruction injected into the next system context
48 - private $last_action_analysis = null; // Last action-match analysis for testing_data payloads
49 -
50 -/**
51 - * Setup streaming headers - call this right before actually streaming
52 - * This delays header setup to allow actions/forms to return JSON responses
53 - */
54 -/**
55 - * Auto-retry wrapper around wp_remote_post for chat-send provider calls.
56 - *
57 - * Retries up to twice (750ms then 2000ms backoff) when the upstream provider
58 - * returns a TRANSIENT error: WP timeout, 429, 502, 503, 504, or a provider-
59 - * specific "overloaded" / "rate limit" body string. Returns immediately on
60 - * permanent errors (401/403/404/422) so misconfiguration surfaces fast.
61 - *
62 - * Drop-in replacement for wp_remote_post — returns the same shape
63 - * (WP_Error or response array) so the caller's existing error-handling
64 - * code path is unchanged.
65 - *
66 - * STREAMING PATH NOTE: this helper is ONLY for non-streaming chat-send
67 - * paths (the *_response_openai / *_response_claude / etc functions).
68 - * For the *_stream variants, the cURL initial-connect happens inside a
69 - * read-chunks loop — retrying there safely (without re-emitting partial
70 - * stream chunks to the client) is a separate problem. Streaming paths
71 - * are NOT wrapped in this build; tracked as a follow-on.
72 - *
73 - * Honors the `mxchat_options['auto_retry_on_transient_error']` toggle
74 - * (default true). When false, behavior is identical to plain wp_remote_post.
75 - */
76 -private function mxchat_provider_call_with_retry($url, $args, $provider_hint = '') {
77 - $opts = is_array($this->options ?? null) ? $this->options : array();
78 - $enabled = !isset($opts['auto_retry_on_transient_error']) ||
79 - (string) $opts['auto_retry_on_transient_error'] !== '0';
80 -
81 - if (!$enabled) {
82 - return wp_remote_post($url, $args);
83 - }
84 -
85 - $backoffs = array(0, 750, 2000); // ms — first attempt 0, then retry waits
86 - $last_response = null;
87 -
88 - foreach ($backoffs as $i => $delay_ms) {
89 - if ($delay_ms > 0) {
90 - usleep($delay_ms * 1000);
91 - }
92 - $response = wp_remote_post($url, $args);
93 - $last_response = $response;
94 -
95 - if (!$this->mxchat_is_transient_provider_error($response, $provider_hint)) {
96 - return $response;
97 - }
98 -
99 - if (defined('WP_DEBUG') && WP_DEBUG) {
100 - $code_for_log = is_wp_error($response) ? 'wp_error:' . $response->get_error_code()
101 - : (int) wp_remote_retrieve_response_code($response);
102 - error_log(sprintf(
103 - '[MxChat] Transient provider error (provider=%s, attempt=%d/3, status=%s). %s',
104 - $provider_hint ?: 'unknown',
105 - $i + 1,
106 - $code_for_log,
107 - ($i + 1) < count($backoffs) ? 'Retrying.' : 'Giving up.'
108 - ));
109 - }
110 - }
111 -
112 - return $last_response;
113 -}
114 -
115 -/**
116 - * Returns true if a wp_remote_post response represents a TRANSIENT
117 - * provider error worth retrying. Conservative — only retries on signals
118 - * that are very likely to clear within a few seconds.
119 - *
120 - * Transient signals:
121 - * - WP_Error with timeout / connection / dns / ssl
122 - * - HTTP 429, 502, 503, 504
123 - * - Provider-specific overload bodies (gemini "overloaded", openai
124 - * "server_error", anthropic "overloaded_error", xai/grok "Rate limit")
125 - *
126 - * NOT transient (return false — fail-fast):
127 - * - 200/2xx (success)
128 - * - 401, 403, 404, 422 (auth / config errors — retrying wastes the
129 - * budget; the user needs to fix something)
130 - * - Any other 4xx (assume permanent unless explicitly listed above)
131 - * - 5xx other than the four listed above (e.g. 500 generic server error
132 - * is often a malformed request on our side, not a transient outage)
133 - */
134 -private function mxchat_is_transient_provider_error($response, $provider_hint = '') {
135 - if (is_wp_error($response)) {
136 - $code = $response->get_error_code();
137 - return in_array($code, array('http_request_failed', 'connection_failed', 'connection_timeout'), true)
138 - || stripos((string) $response->get_error_message(), 'timed out') !== false
139 - || stripos((string) $response->get_error_message(), 'timeout') !== false;
140 - }
141 -
142 - $status = (int) wp_remote_retrieve_response_code($response);
143 - if (in_array($status, array(429, 502, 503, 504), true)) {
144 - return true;
145 - }
146 - if ($status >= 200 && $status < 300) {
147 - return false;
148 - }
149 - // Permanent 4xx that should fail fast — even with no body.
150 - if (in_array($status, array(401, 403, 404, 405, 422), true)) {
151 - return false;
152 - }
153 -
154 - // Provider-specific body inspection for the cases where the upstream
155 - // returns 200 with an error envelope (gemini does this for overload).
156 - $body = (string) wp_remote_retrieve_body($response);
157 - if ($body === '') {
158 - return false;
159 - }
160 - $lower = strtolower($body);
161 - $hint = strtolower((string) $provider_hint);
162 -
163 - if ($hint === 'gemini' && (strpos($lower, 'overloaded') !== false
164 - || strpos($lower, 'high demand') !== false
165 - || strpos($lower, 'model is overloaded') !== false)) {
166 - return true;
167 - }
168 - if ($hint === 'openai' && (strpos($lower, 'rate limit reached') !== false
169 - || strpos($lower, '"type":"server_error"') !== false
170 - || strpos($lower, '"code":"server_error"') !== false)) {
171 - return true;
172 - }
173 - if ($hint === 'anthropic' && (strpos($lower, '"type":"overloaded_error"') !== false
174 - || strpos($lower, 'overloaded_error') !== false)) {
175 - return true;
176 - }
177 - if (($hint === 'xai' || $hint === 'grok') && strpos($lower, 'rate limit') !== false) {
178 - return true;
179 - }
180 -
181 - return false;
182 -}
183 -
184 -/**
185 - * Streaming-path classifier: same rules as mxchat_is_transient_provider_error
186 - * but takes a raw (http_code, body, provider_hint, curl_errno) tuple as
187 - * captured during a cURL streaming exec. cURL's WRITEFUNCTION/HEADERFUNCTION
188 - * collect status separately from a plain wp_remote_post array shape, so the
189 - * non-streaming helper above can't be called directly. This delegate keeps
190 - * the classification rules identical across both paths.
191 - */
192 -private function mxchat_is_transient_provider_error_raw($http_code, $body, $provider_hint = '', $curl_errno = 0) {
193 - if ($curl_errno) {
194 - // cURL transport-level error (timeout, connection failure, DNS, etc.)
195 - // Match the same WP_Error timeout/connection signals the array variant treats as transient.
196 - return in_array($curl_errno, array(
197 - CURLE_OPERATION_TIMEDOUT,
198 - CURLE_COULDNT_CONNECT,
199 - CURLE_COULDNT_RESOLVE_HOST,
200 - CURLE_SSL_CONNECT_ERROR,
201 - CURLE_GOT_NOTHING,
202 - CURLE_SEND_ERROR,
203 - CURLE_RECV_ERROR,
204 - ), true);
205 - }
206 -
207 - $status = (int) $http_code;
208 - if (in_array($status, array(429, 502, 503, 504), true)) {
209 - return true;
210 - }
211 - if ($status >= 200 && $status < 300) {
212 - return false;
213 - }
214 - if (in_array($status, array(401, 403, 404, 405, 422), true)) {
215 - return false;
216 - }
217 -
218 - $body = (string) $body;
219 - if ($body === '') {
220 - return false;
221 - }
222 - $lower = strtolower($body);
223 - $hint = strtolower((string) $provider_hint);
224 -
225 - if ($hint === 'gemini' && (strpos($lower, 'overloaded') !== false
226 - || strpos($lower, 'high demand') !== false
227 - || strpos($lower, 'model is overloaded') !== false)) {
228 - return true;
229 - }
230 - if ($hint === 'openai' && (strpos($lower, 'rate limit reached') !== false
231 - || strpos($lower, '"type":"server_error"') !== false
232 - || strpos($lower, '"code":"server_error"') !== false)) {
233 - return true;
234 - }
235 - if ($hint === 'anthropic' && (strpos($lower, '"type":"overloaded_error"') !== false
236 - || strpos($lower, 'overloaded_error') !== false)) {
237 - return true;
238 - }
239 - if (($hint === 'xai' || $hint === 'grok') && strpos($lower, 'rate limit') !== false) {
240 - return true;
241 - }
242 -
243 - return false;
244 -}
245 -
246 -/**
247 - * Whether transient-error auto-retry is enabled in admin settings.
248 - * Default true unless explicitly set to '0'. Used by both wp_remote_post
249 - * (mxchat_provider_call_with_retry) and cURL streaming paths.
250 - */
251 -private function mxchat_retry_enabled() {
252 - $opts = is_array($this->options ?? null) ? $this->options : array();
253 - return !isset($opts['auto_retry_on_transient_error']) ||
254 - (string) $opts['auto_retry_on_transient_error'] !== '0';
255 -}
256 -
257 -private function setup_streaming_headers() {
258 - if ($this->streaming_headers_sent || headers_sent()) {
259 - return false;
260 - }
261 -
262 - // Headers MUST be set BEFORE the buffers are torn down: flushing a
263 - // buffer that holds any stray output commits the response and turns
264 - // every later header() into a logged no-op — dropping all four SSE
265 - // headers, including the X-Accel-Buffering that stops nginx-fronted
266 - // hosts from de-streaming the reply (plan fe130d).
267 - header('Content-Type: text/event-stream');
268 - header('Cache-Control: no-cache');
269 - header('Connection: keep-alive');
270 - header('X-Accel-Buffering: no');
271 -
272 - // Dev-mode diagnostic: with the reorder, stray buffered bytes become
273 - // the first bytes of the SSE stream — record what they are so a future
274 - // switch to ob_end_clean() can be decided on evidence (fe130d follow-up).
275 - if (defined('MXCHAT_DEV_MODE') && MXCHAT_DEV_MODE && ob_get_level() > 0) {
276 - $buffered = ob_get_contents();
277 - if (is_string($buffered) && $buffered !== '') {
278 - error_log('MxChat SSE teardown: output buffer held ' . strlen($buffered) . ' byte(s): ' . substr($buffered, 0, 200));
279 - }
280 - }
281 -
282 - // Disable output buffering
283 - while (ob_get_level()) {
284 - ob_end_flush();
285 - }
286 -
287 - ob_implicit_flush(true);
288 - flush();
289 -
290 - $this->streaming_headers_sent = true;
291 - return true;
292 -}
293 -
294 -/**
295 - * Class constructor
296 - */
297 -public function __construct() {
298 - $this->options = get_option('mxchat_options');
299 - $this->prompts_options = get_option('mxchat_prompts_options', array());
300 - $this->chat_count = get_option('mxchat_chat_count', 0);
301 - $this->word_handler = new MXChat_Word_Handler($this->options);
302 -
303 - // Add all action hooks
304 - add_action('wp_enqueue_scripts', array($this, 'mxchat_enqueue_scripts_styles'));
305 - add_action('wp_ajax_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
306 - add_action('wp_ajax_nopriv_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
307 - add_action('wp_ajax_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
308 - add_action('wp_ajax_nopriv_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
309 -
310 - // Add the AJAX actions for checking if the pre-chat message was dismissed
311 - add_action('wp_ajax_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
312 - add_action('wp_ajax_nopriv_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
313 - add_action('wp_ajax_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
314 - add_action('wp_ajax_nopriv_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
315 - add_action('wp_ajax_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
316 - add_action('wp_ajax_nopriv_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
317 -
318 - // Add REST API routes registration
319 - add_action('rest_api_init', array($this, 'register_routes'));
320 - add_action('wp_ajax_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
321 - add_action('wp_ajax_nopriv_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
322 -
323 - // Rate limit action - notice we removed the old schedule setup
324 - add_action('mxchat_reset_rate_limits', array($this, 'mxchat_reset_rate_limits'));
325 -
326 - // Self-heal: if the reset event is ever lost (cron row cleared, botched
327 - // migration, deactivate/reactivate race), an admin-context request brings it
328 - // back. Cheap by construction: 60s transient guard + early return when the
329 - // event is already scheduled. Without this, a lost event with the fallback
330 - // flag unset leaves visitors rate-limited forever.
331 - add_action('admin_init', array($this, 'setup_rate_limit_cron_jobs'));
332 -
333 - // File upload and handling actions
334 - add_action('wp_ajax_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
335 - add_action('wp_ajax_nopriv_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
336 - add_action('wp_ajax_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
337 - add_action('wp_ajax_nopriv_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
338 -
339 - // Word document handling actions
340 - add_action('wp_ajax_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
341 - add_action('wp_ajax_nopriv_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
342 - add_action('wp_ajax_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
343 - add_action('wp_ajax_nopriv_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
344 - add_action('wp_ajax_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
345 - add_action('wp_ajax_nopriv_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
346 -
347 - // Email handling actions
348 - add_action('wp_ajax_nopriv_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
349 - add_action('wp_ajax_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
350 - add_action('wp_ajax_nopriv_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
351 - add_action('wp_ajax_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
352 -
353 - add_action('wp_ajax_mxchat_stream_chat', array($this, 'mxchat_handle_chat_request'));
354 - add_action('wp_ajax_nopriv_mxchat_stream_chat', array($this, 'mxchat_handle_chat_request'));
355 -
356 - // Testing panel AJAX actions
357 - add_action('wp_ajax_mxchat_get_system_info', array($this, 'mxchat_get_system_info'));
358 - add_action('wp_ajax_mxchat_get_similarity_threshold', array($this, 'mxchat_get_similarity_threshold'));
359 - add_action('wp_ajax_mxchat_get_kb_status', array($this, 'mxchat_get_kb_status'));
360 - add_action('wp_ajax_mxchat_start_fresh_session', array($this, 'mxchat_start_fresh_session'));
361 - // Add to your existing constructor, in the section with other AJAX actions:
362 - add_action('wp_ajax_mxchat_track_url_click', array($this, 'mxchat_track_url_click'));
363 - add_action('wp_ajax_nopriv_mxchat_track_url_click', array($this, 'mxchat_track_url_click'));
364 - add_action('wp_ajax_mxchat_track_originating_page', array($this, 'mxchat_track_originating_page'));
365 - add_action('wp_ajax_nopriv_mxchat_track_originating_page', array($this, 'mxchat_track_originating_page'));
366 - // Add chat mode checking actions
367 - add_action('wp_ajax_mxchat_get_current_chat_mode', array($this, 'mxchat_get_current_chat_mode'));
368 - add_action('wp_ajax_nopriv_mxchat_get_current_chat_mode', array($this, 'mxchat_get_current_chat_mode'));
369 -
370 - // Nonce refresh for page-cache compatibility (WP Rocket, LiteSpeed, etc.)
371 - add_action('wp_ajax_mxchat_refresh_nonce', array($this, 'mxchat_refresh_nonce'));
372 - add_action('wp_ajax_nopriv_mxchat_refresh_nonce', array($this, 'mxchat_refresh_nonce'));
373 -
374 - // Auto-email transcript action
375 - add_action('mxchat_send_delayed_transcript', array($this, 'mxchat_send_delayed_transcript'), 10, 1);
376 -
377 - add_filter('mxchat_check_actions_only', array($this, 'check_actions_for_addons'), 10, 4);
378 -
379 -
380 -}
381 -
382 -/**
383 - * Return a fresh nonce so cached pages can replace the stale one.
384 - * With `with_settings`, also returns the current behavior-gate settings so
385 - * the widget can correct stale inline-localized values (plan-32db95).
386 - */
387 -public function mxchat_refresh_nonce() {
388 - nocache_headers();
389 - $payload = array('nonce' => wp_create_nonce('mxchat_chat_nonce'));
390 - if (!empty($_REQUEST['with_settings'])) {
391 - $payload['settings'] = $this->get_dynamic_widget_settings(true);
392 - }
393 - wp_send_json_success($payload);
394 -}
395 -
396 -/**
397 - * Behavior-gate settings the widget may re-fetch at runtime (plan-32db95).
398 - *
399 - * Every widget setting ships inline in page HTML via wp_localize_script, so
400 - * full-page caches (host caches, WP Rocket, LiteSpeed, W3TC, FlyingPress,
401 - * WP Super Cache, Cloudflare APO, the browser itself) keep serving a stale
402 - * snapshot after an admin changes a setting. MxChat_Cache_Purge clears the
403 - * caches PHP can reach; this payload covers the rest — the widget requests
404 - * it on first open (via the nonce-refresh endpoints) and merges it over
405 - * `mxchatChat`, the same distrust-cached-HTML pattern the 3.2.7 per-request
406 - * nonce uses.
407 - *
408 - * Behavior gates + labels ONLY — colors stay inline because they're also
409 - * server-inline-styled, and a runtime swap would visibly flash.
410 - *
411 - * Both wp_localize_script blocks merge this exact array, so the inline and
412 - * refreshed payloads cannot drift.
413 - *
414 - * @param bool $fresh Re-read mxchat_options from the DB (endpoint paths)
415 - * instead of trusting the instance copy.
416 - * @return array
417 - */
418 -public function get_dynamic_widget_settings($fresh = false) {
419 - $options = $fresh ? get_option('mxchat_options', array()) : $this->options;
420 - if (!is_array($options)) {
421 - $options = array();
422 - }
423 - return array(
424 - 'model' => isset($options['model']) ? $options['model'] : 'gpt-5.6-sol',
425 - 'enable_streaming_toggle' => isset($options['enable_streaming_toggle']) ? $options['enable_streaming_toggle'] : 'on',
426 - 'rate_limit_message' => $options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
427 - 'chat_toolbar_toggle' => $options['chat_toolbar_toggle'] ?? 'off',
428 - 'print_button_enabled' => $options['print_button_enabled'] ?? 'on',
429 - 'print_button_label' => esc_html__('Download Transcript', 'mxchat'),
430 - // "Start new chat" header-menu item (plan ac2e81). Default OFF.
431 - 'reset_chat_enabled' => $options['reset_chat_enabled'] ?? 'off',
432 - 'reset_chat_label' => !empty($options['reset_chat_label']) ? esc_html($options['reset_chat_label']) : esc_html__('Start new chat', 'mxchat'),
433 - 'reset_chat_confirm' => esc_html__('Start a new chat? This clears the current conversation.', 'mxchat'),
434 - 'stop_button_label' => esc_html__('Stop response', 'mxchat'),
435 - 'print_header_title' => esc_html(get_bloginfo('name')) . ' — ' . esc_html__('Chat transcript', 'mxchat'),
436 - // Emit 'on'/'off' STRINGS, never booleans: wp_localize_script casts
437 - // scalars to string, and (string) false === '' — which the widget's
438 - // old gate read as enabled (plan-4bba64). The filter keeps its
439 - // boolean contract; only the emitted value is stringified.
440 - 'satisfaction_rating_enabled' => apply_filters(
441 - 'mxchat_satisfaction_rating_enabled',
442 - ($options['satisfaction_rating_enabled'] ?? 'off') === 'on'
443 - ) ? 'on' : 'off',
444 - 'satisfaction_rating_idle_seconds' => max(5, min(600, intval($options['satisfaction_rating_idle_seconds'] ?? 60))),
445 - 'satisfaction_rating_copy' => array(
446 - 'question' => !empty($options['satisfaction_rating_question']) ? esc_html($options['satisfaction_rating_question']) : esc_html__('Was this helpful?', 'mxchat'),
447 - 'helpful' => esc_html__('Helpful', 'mxchat'),
448 - 'not_helpful' => esc_html__('Not helpful', 'mxchat'),
449 - 'dismiss' => esc_html__('Dismiss', 'mxchat'),
450 - 'thanks' => !empty($options['satisfaction_rating_thanks']) ? esc_html($options['satisfaction_rating_thanks']) : esc_html__('Thanks! Anything we should improve? (optional)', 'mxchat'),
451 - 'placeholder' => !empty($options['satisfaction_rating_placeholder']) ? esc_html($options['satisfaction_rating_placeholder']) : esc_html__('Tell us what could be better…', 'mxchat'),
452 - 'send' => esc_html__('Send', 'mxchat'),
453 - 'skip' => esc_html__('Skip', 'mxchat'),
454 - 'saved' => !empty($options['satisfaction_rating_saved']) ? esc_html($options['satisfaction_rating_saved']) : esc_html__('Thanks for the feedback.', 'mxchat'),
455 - ),
456 - );
457 -}
458 -
459 -// In your core plugin's check_actions_for_addons method:
460 -public function check_actions_for_addons($default, $message, $user_id, $session_id) {
461 - //error_log('MxChat Core: check_actions_for_addons called with message: ' . $message);
462 -
463 - $result = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
464 -
465 - //error_log('MxChat Core: Intent check result = ' . ($result === false ? 'false' : 'true'));
466 -
467 - return $result;
468 -}
469 -
470 - private function mxchat_increment_chat_count() {
471 - $chat_count = get_option('mxchat_chat_count', 0);
472 - $chat_count++;
473 - update_option('mxchat_chat_count', $chat_count);
474 - }
475 -
476 -function mxchat_fetch_conversation_history() {
477 - if (empty($_POST['session_id'])) {
478 - wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
479 - wp_die();
480 - }
481 -
482 - $session_id = MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id']));
483 -
484 - // SECURITY FIX: Verify session ownership before retrieving data
485 - // If IP/user changed, signal frontend to reset session instead of blocking
486 - $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
487 -
488 - // Check if this session has an owner recorded
489 - $session_owner = MxChat_Session_Store::get($session_id, 'owner');
490 -
491 - // Update session owner if it changed (e.g. IP changed due to network switch)
492 - // The session ID itself is the authentication — if the client has it, they own it
493 - if (!$session_owner || $session_owner !== $current_user_identifier) {
494 - MxChat_Session_Store::set($session_id, 'owner', $current_user_identifier);
495 - }
496 -
497 - $history = MxChat_Utils::get_session_history($session_id); // Transcripts table since 3.2.19 (839c4c)
498 - $chat_mode = MxChat_Session_Store::get($session_id, 'mode', 'ai'); // Get current chat mode
499 -
500 - if (empty($history)) {
501 - // Even if history is empty, return the chat mode
502 - wp_send_json_success([
503 - 'conversation' => [],
504 - 'chat_mode' => $chat_mode
505 - ]);
506 - wp_die();
507 - }
508 -
509 - wp_send_json_success([
510 - 'conversation' => $history,
511 - 'chat_mode' => $chat_mode
512 - ]);
513 - wp_die();
514 -}
515 -private function mxchat_fetch_conversation_history_for_ai($session_id, $session_start_timestamp = 0) {
516 - $history = MxChat_Utils::get_session_history($session_id);
517 -
518 - // Check persistence setting - when OFF, only include messages from current page load
519 - $options = get_option('mxchat_options', []);
520 - $persistence_enabled = isset($options['chat_persistence_toggle']) && $options['chat_persistence_toggle'] === 'on';
521 -
522 - // Filter history when persistence is OFF to match what the user sees
523 - if (!$persistence_enabled && $session_start_timestamp > 0) {
524 - // History timestamps are second-resolution x1000 since 3.2.19
525 - // (839c4c) while the client cutoff is real milliseconds. Floor the
526 - // cutoff to the second boundary and keep >= : erring inclusive means
527 - // at worst one pre-load message from the same second replays, where
528 - // the exclusive direction silently eats the visitor's first message.
529 - $cutoff = (int) floor($session_start_timestamp / 1000) * 1000;
530 - $history = array_filter($history, function($entry) use ($cutoff) {
531 - // Include messages from this page load onwards
532 - return isset($entry['timestamp']) && $entry['timestamp'] >= $cutoff;
533 - });
534 - // Re-index array after filtering
535 - $history = array_values($history);
536 - }
537 -
538 - $formatted_history = [];
539 -
540 - // Adjusted for code-heavy conversations
541 - $max_tokens = 120000; // Context window size
542 - $reserved_tokens = 5000; // Space for system prompts + current query
543 - $current_token_count = 0;
544 -
545 - // Allowed HTML tags for content sanitization
546 - $allowed_tags = [
547 - 'pre' => ['class' => true],
548 - 'code' => ['class' => true],
549 - 'span' => ['class' => true],
550 - 'div' => ['class' => true],
551 - 'strong' => [],
552 - 'em' => []
553 - ];
554 -
555 - foreach (array_reverse($history) as $entry) {
556 - // Preserve code blocks while sanitizing other HTML
557 - $clean_content = wp_kses($entry['content'], $allowed_tags);
558 -
559 - // Detect code blocks in content
560 - $has_code = false;
561 -// Replace the HTML check with:
562 -// Allow messages that contain code blocks or are plain text
563 -if (strpos($clean_content, '<pre') === false &&
564 - strpos($clean_content, '<code') === false &&
565 - $clean_content !== strip_tags($entry['content'])) {
566 - continue;
567 -}
568 -
569 - // Skip entries that lost significant content during sanitization
570 - if (!$has_code && $clean_content !== strip_tags($entry['content'])) {
571 - continue;
572 - }
573 -
574 - // More accurate token estimation (1 token ≈ 4 characters)
575 - $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
576 -
577 - // Check token budget with the new estimate
578 - if (($current_token_count + $token_estimate + $reserved_tokens) > $max_tokens) {
579 - // Try to fit partial content if it's the first entry
580 - if (empty($formatted_history)) {
581 - $clean_content = mb_substr($clean_content, 0, ($max_tokens - $reserved_tokens) * 4);
582 - $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
583 - } else {
584 - break;
585 - }
586 - }
587 -
588 - // Add to formatted history
589 - $formatted_history[] = [
590 - 'role' => $entry['role'],
591 - 'content' => $clean_content
592 - ];
593 -
594 - $current_token_count += $token_estimate;
595 - }
596 -
597 - // Reverse back to maintain chronological order
598 - $formatted_history = array_reverse($formatted_history);
599 -
600 - // Add system message about code context
601 - array_unshift($formatted_history, [
602 - 'role' => 'system',
603 - 'content' => 'Preserved code blocks are marked with [CODE BLOCK PRESERVED]. '
604 - . 'Maintain formatting and syntax highlighting when referencing code.'
605 - ]);
606 -
607 - return $formatted_history;
608 -}
609 -
610 -public function register_routes() {
611 - //error_log(esc_html__('Registering MxChat REST routes', 'mxchat'));
612 -
613 - // Per-request chat-send nonce endpoint — issues a fresh nonce on demand
614 - // so the chat widget never depends on a stale nonce embedded in cached HTML.
615 - // Public (no auth), rate-limited (1 call / IP / second via a transient).
616 - register_rest_route('mxchat/v1', '/nonce', [
617 - 'methods' => 'GET',
618 - 'callback' => [$this, 'mxchat_issue_chat_send_nonce'],
619 - 'permission_callback' => '__return_true',
620 - ]);
621 -
622 - register_rest_route('mxchat/v1', '/stream', [
623 - 'methods' => 'GET',
624 - 'callback' => [$this, 'mxchat_stream_events'],
625 - 'permission_callback' => [$this, 'verify_chat_session'],
626 - ]);
627 -
628 - register_rest_route('mxchat/v1', '/agent-response', [
629 - 'methods' => 'POST',
630 - 'callback' => [$this, 'mxchat_handle_agent_response'],
631 - 'permission_callback' => [$this, 'verify_slack_request'],
632 - ]);
633 -
634 - register_rest_route('mxchat/v1', '/slack-interaction', [
635 - 'methods' => 'POST',
636 - 'callback' => [$this, 'handle_slack_interaction'],
637 - 'permission_callback' => [$this, 'verify_slack_request'],
638 - ]);
639 -
640 - register_rest_route('mxchat/v1', '/slack-messages', [
641 - 'methods' => 'POST',
642 - 'callback' => [$this, 'handle_slack_messages'],
643 - 'permission_callback' => [$this, 'verify_slack_request'],
644 - ]);
645 -
646 - // Telegram webhook endpoint
647 - register_rest_route('mxchat/v1', '/telegram-webhook', [
648 - 'methods' => 'POST',
649 - 'callback' => [$this, 'handle_telegram_webhook'],
650 - 'permission_callback' => [$this, 'verify_telegram_request'],
651 - ]);
652 -
653 - //error_log(esc_html__('MxChat REST routes registered', 'mxchat'));
654 -}
655 -
656 -/**
657 - * Issue a fresh per-request nonce for chat-send. Returned to the widget which
658 - * caches it for the session and includes it on every chat-send / stream-send /
659 - * upload call. By moving the nonce out of inline `window.mxchatChat = {...}` HTML
660 - * we eliminate the entire class of "first-message Access denied" failures that
661 - * plague WP installs behind a full-page cache (WP Rocket, LiteSpeed, FlyingPress,
662 - * W3 Total Cache, Cloudflare APO) — the nonce is never cached because it never
663 - * lives in the HTML body.
664 - *
665 - * Public endpoint. Rate-limited to 1 call / IP / 1s via a transient so a single
666 - * client browser can't be used to flood the nonce-issuance path.
667 - *
668 - * Nonce action: `mxchat_chat_send` (new). The chat-send AJAX handlers accept
669 - * BOTH this action AND the legacy `mxchat_chat_nonce` action for a 30-day
670 - * backwards-compat window so cached pages still in users' browsers don't break
671 - * mid-session.
672 - *
673 - * @since 3.2.7
674 - */
675 -public function mxchat_issue_chat_send_nonce(WP_REST_Request $request) {
676 - $ip = '';
677 - if (!empty($_SERVER['REMOTE_ADDR'])) {
678 - $ip = preg_replace('#[^0-9a-fA-F:\.]#', '', wp_unslash((string) $_SERVER['REMOTE_ADDR']));
679 - }
680 - if ($ip !== '') {
681 - // Best-effort rate limit. WP transients with sub-second TTL are racy
682 - // (parallel bursts can squeak through before set_transient completes);
683 - // we use 2s to make the gate slightly more reliable. Real production
684 - // rate-limiting at sub-second granularity needs Redis or DB row locks
685 - // — out of scope for this endpoint, which is already cheap.
686 - $key = 'mxchat_nonce_rl_' . md5($ip);
687 - if (get_transient($key)) {
688 - return new WP_REST_Response(array(
689 - 'error' => 'rate_limited',
690 - 'message' => __('Too many nonce requests. Try again shortly.', 'mxchat'),
691 - ), 429);
692 - }
693 - set_transient($key, 1, 2);
694 - }
695 -
696 - // The widget calls this endpoint without an X-WP-Nonce header, so WordPress does not
697 - // honor the auth cookie and the request runs as uid=0 even for logged-in users. That
698 - // makes wp_create_nonce() bind the nonce to uid=0, which then fails wp_verify_nonce()
699 - // at admin-ajax (which runs as the real uid) -> logged-in users get a 403 on upload.
700 - // Resolve the real user from the logged_in cookie so the nonce binds to the correct uid.
701 - if ( ! is_user_logged_in() ) {
702 - $maybe_uid = wp_validate_auth_cookie( '', 'logged_in' );
703 - if ( $maybe_uid ) {
704 - wp_set_current_user( $maybe_uid );
705 - }
706 - }
707 -
708 - $payload = array(
709 - 'nonce' => wp_create_nonce('mxchat_chat_send'),
710 - 'expires_in' => 86400, // WP nonces live 24h; widget caches for 12h conservatively.
711 - );
712 -
713 - // plan-32db95: the widget's first-open refresh asks for current behavior
714 - // settings in the same round-trip, so stale inline-localized values on
715 - // cached pages get corrected without a second request. All values in
716 - // this payload already ship in public page HTML — nothing sensitive.
717 - if ($request->get_param('with_settings')) {
718 - $payload['settings'] = $this->get_dynamic_widget_settings(true);
719 - }
720 -
721 - return new WP_REST_Response($payload, 200);
722 -}
723 -
724 -/**
725 - * Verify a chat-send nonce. Accepts BOTH the new `mxchat_chat_send` action
726 - * (issued by /wp-json/mxchat/v1/nonce) AND the legacy `mxchat_chat_nonce`
727 - * action (inline-localized in older cached HTML). The legacy acceptance is
728 - * a 30-day backwards-compat window — to be removed in a follow-up release
729 - * after 2026-06-27.
730 - *
731 - * @param string $posted_nonce
732 - * @return bool
733 - */
734 -public static function mxchat_verify_chat_send_nonce($posted_nonce) {
735 - if (!is_string($posted_nonce) || $posted_nonce === '') {
736 - return false;
737 - }
738 - return (bool) wp_verify_nonce($posted_nonce, 'mxchat_chat_send')
739 - || (bool) wp_verify_nonce($posted_nonce, 'mxchat_chat_nonce');
740 -}
741 -
742 -/**
743 - * Verify valid chat session
744 - */
745 -public function verify_chat_session($request) {
746 - $session_id = $request->get_param('session_id');
747 - if (empty($session_id)) {
748 - //error_log(esc_html__('Empty session ID in chat request', 'mxchat'));
749 - return false;
750 - }
751 -
752 - $chat_mode = MxChat_Session_Store::get($session_id, 'mode', 'ai');
753 - return $chat_mode === 'agent';
754 -}
755 -
756 -/**
757 - * Verify request is coming from Slack.
758 - *
759 - * @param WP_REST_Request $request
760 - * @return bool True if valid, false otherwise.
761 - */
762 -public function verify_slack_request($request) {
763 - // Get the Slack signing secret from your plugin options
764 - $valid_key = $this->options['live_agent_secret_key'] ?? '';
765 -
766 - if (empty($valid_key)) {
767 - //error_log(esc_html__('Slack signing secret not configured', 'mxchat'));
768 - return false;
769 - }
770 -
771 - $timestamp = $request->get_header('X-Slack-Request-Timestamp');
772 - $slack_signature = $request->get_header('X-Slack-Signature');
773 -
774 - // Verify timestamp to prevent replay attacks
775 - if (abs(time() - intval($timestamp)) > 300) {
776 - //error_log(esc_html__('Slack request timestamp too old', 'mxchat'));
777 - return false;
778 - }
779 -
780 - // Get raw request body from the WP_REST_Request object
781 - // (php://input may already be consumed by WordPress at this point)
782 - $request_body = $request->get_body();
783 -
784 - // Create the signature base string
785 - $sig_basestring = "v0:{$timestamp}:{$request_body}";
786 -
787 - // Calculate expected signature
788 - $my_signature = 'v0=' . hash_hmac('sha256', $sig_basestring, $valid_key);
789 -
790 - // Compare signatures
791 - return hash_equals($my_signature, $slack_signature);
792 -}
793 -
794 -/**
795 - * Verify request is coming from Telegram.
796 - *
797 - * @param WP_REST_Request $request
798 - * @return bool True if valid, false otherwise.
799 - */
800 -public function verify_telegram_request($request) {
801 - $secret_token = $this->options['telegram_webhook_secret'] ?? '';
802 -
803 - //error_log('[MxChat Telegram DEBUG] verify_telegram_request called');
804 - //error_log('[MxChat Telegram DEBUG] Stored secret: ' . (empty($secret_token) ? 'EMPTY' : substr($secret_token, 0, 10) . '...'));
805 -
806 - if (empty($secret_token)) {
807 - // No secret configured (legacy setup). Do NOT fail open to the whole
808 - // internet — that lets an unauthenticated caller write agent-branded
809 - // messages. Fall back to verifying the request originates from
810 - // Telegram's published webhook IP ranges so existing no-secret installs
811 - // keep working while an arbitrary-internet caller is blocked. Setting a
812 - // real secret (see the admin notice) is the recommended path.
813 - // (plan-0c17b5)
814 - $peer = isset($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : '';
815 - if ($this->mxchat_ip_in_telegram_ranges($peer)) {
816 - return true;
817 - }
818 - error_log('MxChat: Telegram webhook has no secret configured and the request '
819 - . 'is not from a Telegram IP range; rejected. Set a webhook secret to secure it.');
820 - return false;
821 - }
822 -
823 - // Telegram sends the secret token in the X-Telegram-Bot-Api-Secret-Token header
824 - $request_token = $request->get_header('X-Telegram-Bot-Api-Secret-Token');
825 -
826 - //error_log('[MxChat Telegram DEBUG] Request token: ' . (empty($request_token) ? 'EMPTY' : substr($request_token, 0, 10) . '...'));
827 -
828 - if (empty($request_token)) {
829 - //error_log('[MxChat Telegram DEBUG] Request rejected: No token in header');
830 - return false;
831 - }
832 -
833 - // Timing-safe comparison
834 - $result = hash_equals($secret_token, $request_token);
835 - //error_log('[MxChat Telegram DEBUG] Token comparison result: ' . ($result ? 'MATCH' : 'MISMATCH'));
836 - return $result;
837 -}
838 -
839 -/**
840 - * Whether $ip falls within Telegram's published webhook IPv4 ranges
841 - * (149.154.160.0/20 and 91.108.4.0/22). Used as an authenticity fallback for
842 - * the Telegram webhook when no secret token is configured, so a legacy
843 - * no-secret install keeps working without failing open to the entire internet.
844 - *
845 - * Uses the real TCP peer (REMOTE_ADDR); a spoofable X-Forwarded-For is NOT
846 - * consulted. Behind a reverse proxy / CDN that rewrites REMOTE_ADDR this may
847 - * not match — which is exactly why configuring a real webhook secret is the
848 - * recommended path. (plan-0c17b5)
849 - *
850 - * @param string $ip Candidate IPv4 address.
851 - * @return bool
852 - */
853 -private function mxchat_ip_in_telegram_ranges($ip) {
854 - if (!is_string($ip) || $ip === '' || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
855 - return false;
856 - }
857 - $ip_long = ip2long($ip);
858 - if ($ip_long === false) {
859 - return false;
860 - }
861 - $ranges = array(
862 - array('149.154.160.0', 20),
863 - array('91.108.4.0', 22),
864 - );
865 - foreach ($ranges as $range) {
866 - $subnet_long = ip2long($range[0]);
867 - if ($subnet_long === false) {
868 - continue;
869 - }
870 - $mask = (0xFFFFFFFF << (32 - $range[1])) & 0xFFFFFFFF;
871 - if (($ip_long & $mask) === ($subnet_long & $mask)) {
872 - return true;
873 - }
874 - }
875 - return false;
876 -}
877 -
878 -public function mxchat_stream_events(WP_REST_Request $request) {
879 - header('Content-Type: text/event-stream');
880 - header('Cache-Control: no-cache');
881 - header('Connection: keep-alive');
882 -
883 - $session_id = MxChat_Utils::sanitize_session_id($request->get_param('session_id'));
884 - $last_seen_id = sanitize_text_field($request->get_param('last_seen_id')) ?: '';
885 -
886 - if (empty($session_id)) {
887 - echo esc_html__("event: error\ndata: ", 'mxchat') . esc_html__('Missing session_id', 'mxchat') . "\n\n";
888 - flush();
889 - exit;
890 - }
891 -
892 - $history = MxChat_Utils::get_session_history($session_id);
893 -
894 - // Message ids are transcripts-table integers since 3.2.19 (839c4c). A
895 - // client that was mid-conversation at upgrade time still holds a legacy
896 - // uniqid() string as last_seen_id — PHP compares an int against a
897 - // non-numeric string AS STRINGS ('6a7e...' outranks any row id), which
898 - // silently marks everything already-seen and drops live-agent messages.
899 - // Treat any non-numeric bookmark as "replay from session start" instead:
900 - // one duplicate replay beats a dropped message.
901 - if ($last_seen_id !== '' && !ctype_digit($last_seen_id)) {
902 - $last_seen_id = '';
903 - }
904 - $last_seen = ($last_seen_id === '') ? 0 : (int) $last_seen_id;
905 -
906 - // Filter only new messages
907 - $new_messages = array_filter($history, function ($message) use ($last_seen) {
908 - return !empty($message['id']) && (int) $message['id'] > $last_seen;
909 - });
910 -
911 - // Send new messages if available
912 - if (!empty($new_messages)) {
913 - echo esc_html__("event: newMessages\ndata: ", 'mxchat') . json_encode(array_values($new_messages)) . "\n\n";
914 - } else {
915 - // Keep the connection alive
916 - echo esc_html__("event: keepAlive\ndata: ", 'mxchat') . "{}\n\n";
917 - }
918 - flush();
919 - exit;
920 -}
921 -
922 -
923 -
924 -
925 -private function mxchat_save_chat_message($session_id, $role, $message, $originating_page = null, $rag_context = null) {
926 - global $wpdb;
927 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
928 - //error_log("[DEBUG] mxchat_save_chat_message -> START for session_id: {$session_id}, role: {$role}");
929 -
930 - // Check if this is the first message in a new session (before any other database operations)
931 - $is_new_session = false;
932 - if ($role === 'user') { // Only check for user messages, not bot responses
933 - $existing_messages = $wpdb->get_var($wpdb->prepare(
934 - "SELECT COUNT(*) FROM $table_name WHERE session_id = %s",
935 - $session_id
936 - ));
937 - $is_new_session = ($existing_messages == 0);
938 -
939 - // Log for debugging
940 - if ($is_new_session) {
941 - //error_log("[DEBUG] This is a NEW session - first message");
942 - }
943 - }
944 -
945 - // SECURITY FIX: Set session ownership for new sessions
946 - if ($is_new_session && $role === 'user') {
947 - $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
948 -
949 - // Only set ownership if not already set
950 - if (!MxChat_Session_Store::get($session_id, 'owner')) {
951 - MxChat_Session_Store::set($session_id, 'owner', $current_user_identifier);
952 - //error_log("[DEBUG] Set session ownership for {$session_id} to {$current_user_identifier}");
953 - }
954 - }
955 -
956 - // 1) Extract agent name if present
957 - $agent_name = '';
958 - if (preg_match('/^Agent: (.*?) - /', $message, $matches)) {
959 - $agent_name = $matches[1];
960 - $message = str_replace("Agent: $agent_name - ", '', $message);
961 - if (empty(MxChat_Session_Store::get($session_id, 'agent_name'))) {
962 - MxChat_Session_Store::set($session_id, 'agent_name', $agent_name);
963 - }
964 - }
965 -
966 - // 2) The message id is the transcripts row id since 3.2.19 (plan 839c4c)
967 - // — assigned by the INSERT below, not generated here.
968 -
969 - // 3) Determine user_id
970 - $user_id = is_user_logged_in() ? get_current_user_id() : 0;
971 -
972 - // 4) Determine user_identifier
973 - $user_identifier = $agent_name
974 - ? $agent_name
975 - : MxChat_User::mxchat_get_user_identifier();
976 -
977 - // 5) Determine displayed_name
978 - $user_email = MxChat_User::mxchat_get_user_email();
979 - $displayed_name = $agent_name ? $agent_name : ($user_email ?: $user_identifier);
980 -
981 - // 6) Check for a saved email in the session store
982 - $saved_email = MxChat_Session_Store::get($session_id, 'email');
983 -
984 - // Check for a saved name in the session store
985 - $saved_name = MxChat_Session_Store::get($session_id, 'name');
986 -
987 - // If found, update DB user_email and user_name
988 - if ($saved_email || $saved_name) {
989 - $update_data = [];
990 - if ($saved_email) {
991 - $update_data['user_email'] = $saved_email;
992 - }
993 - if ($saved_name) {
994 - $update_data['user_name'] = $saved_name;
995 - }
996 -
997 - if (!empty($update_data)) {
998 - $update_res = $wpdb->update(
999 - $table_name,
1000 - $update_data,
1001 - ['session_id' => $session_id],
1002 - array_fill(0, count($update_data), '%s'),
1003 - ['%s']
1004 - );
1005 - //error_log("[DEBUG] mxchat_save_chat_message -> Attempted DB user_email/user_name update for session_id {$session_id}. update_res: {$update_res}");
1006 - }
1007 - }
1008 -
1009 - // 7) Session history lives ONLY in the transcripts table since 3.2.19
1010 - // (plan 839c4c). The mxchat_history_<sid> option this step used to
1011 - // write was a duplicate of the INSERT below at up to 64 KB a row;
1012 - // MxChat_Utils::get_session_history() now serves every reader from
1013 - // the table in the same array shape.
1014 -
1015 - // 8) Save the message to DB (INSERT)
1016 - $insert_data = [
1017 - 'user_id' => $user_id,
1018 - 'user_identifier'=> $user_identifier,
1019 - 'user_email' => $saved_email ?: $user_email,
1020 - 'user_name' => $saved_name ?: '', // Add name to insert data
1021 - 'session_id' => $session_id,
1022 - 'role' => $role,
1023 - 'message' => $message,
1024 - 'timestamp' => current_time('mysql', 1),
1025 - ];
1026 -
1027 - // IMPROVED: Handle originating page data
1028 - $columns_exist = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'");
1029 -
1030 - if ($columns_exist) {
1031 - if ($is_new_session && $role === 'user') {
1032 - // For the first user message, set originating page data
1033 -
1034 - // First check if we have it from the parameter
1035 - if ($originating_page && !empty($originating_page['url'])) {
1036 - $insert_data['originating_page_url'] = $originating_page['url'];
1037 - $insert_data['originating_page_title'] = $originating_page['title'] ?? '';
1038 -
1039 - //error_log("[DEBUG] Setting originating page from parameter: " . $originating_page['url']);
1040 - }
1041 - // Otherwise check if it's stored in the instance property
1042 - else if (isset($this->pending_originating_page) && !empty($this->pending_originating_page['url'])) {
1043 - $insert_data['originating_page_url'] = $this->pending_originating_page['url'];
1044 - $insert_data['originating_page_title'] = $this->pending_originating_page['title'] ?? '';
1045 -
1046 - //error_log("[DEBUG] Setting originating page from pending_originating_page: " . $this->pending_originating_page['url']);
1047 -
1048 - // Clear after using (= null, not unset(): unset() undeclares the property
1049 - // and the next assignment recreates it dynamic, re-triggering the PHP 8.2 deprecation)
1050 - $this->pending_originating_page = null;
1051 - }
1052 - // Fallback to HTTP_REFERER if nothing else is available
1053 - else if (isset($_SERVER['HTTP_REFERER'])) {
1054 - $referer_url = esc_url_raw($_SERVER['HTTP_REFERER']);
1055 - $insert_data['originating_page_url'] = $referer_url;
1056 -
1057 - // Generate title from URL
1058 - $parsed_url = parse_url($referer_url);
1059 - $path = isset($parsed_url['path']) ? trim($parsed_url['path'], '/') : '';
1060 -
1061 - if (empty($path) || $path === 'index.php' || $path === 'index.html') {
1062 - $insert_data['originating_page_title'] = 'Homepage';
1063 - } else {
1064 - $title = str_replace(['-', '_', '/', '.php', '.html'], ' ', $path);
1065 - $insert_data['originating_page_title'] = ucwords(trim($title));
1066 - }
1067 -
1068 - //error_log("[DEBUG] Setting originating page from HTTP_REFERER: " . $referer_url);
1069 - }
1070 -
1071 - // Store for this session so all messages have the same originating page
1072 - if (!empty($insert_data['originating_page_url'])) {
1073 - MxChat_Session_Store::set($session_id, 'originating_page', [
1074 - 'url' => $insert_data['originating_page_url'],
1075 - 'title' => $insert_data['originating_page_title']
1076 - ]);
1077 - }
1078 - } else {
1079 - // For subsequent messages in the session, use the stored originating page
1080 - $stored_originating = MxChat_Session_Store::get($session_id, 'originating_page');
1081 - if ($stored_originating && !empty($stored_originating['url'])) {
1082 - $insert_data['originating_page_url'] = $stored_originating['url'];
1083 - $insert_data['originating_page_title'] = $stored_originating['title'] ?? '';
1084 - }
1085 - }
1086 - }
1087 -
1088 - // Add RAG context if provided (for bot messages)
1089 - if ($rag_context !== null && $role === 'bot') {
1090 - $rag_context_column_exists = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'rag_context'");
1091 - if ($rag_context_column_exists) {
1092 - $insert_data['rag_context'] = is_array($rag_context) ? wp_json_encode($rag_context) : $rag_context;
1093 - }
1094 - }
1095 -
1096 - $wpdb->insert($table_name, $insert_data);
1097 - //error_log("[DEBUG] mxchat_save_chat_message -> Inserted message into DB. row_id: {$wpdb->insert_id}, data: " . print_r($insert_data, true));
1098 -
1099 - // The row id IS the message id now. Flush the per-request history cache
1100 - // so a read later in this same request (the AI context build, the
1101 - // handover context slice) sees this message — the read-your-own-write
1102 - // behavior the old update_option() write provided.
1103 - $message_id = (int) $wpdb->insert_id;
1104 - MxChat_Utils::flush_session_history_cache($session_id);
1105 -
1106 - // 9) Send notification email if this is the first user message in a new session
1107 - if ($wpdb->insert_id && $is_new_session && $role === 'user') {
1108 - $this->send_new_chat_notification($session_id, array(
1109 - 'identifier' => $user_identifier,
1110 - 'email' => $saved_email ?: $user_email,
1111 - 'ip' => $_SERVER['REMOTE_ADDR']
1112 - ));
1113 - }
1114 -
1115 - // 10) Schedule delayed transcript email if enabled and message is from user
1116 - if ($wpdb->insert_id && $role === 'user') {
1117 - $this->schedule_delayed_transcript_email($session_id);
1118 - }
1119 -
1120 - //error_log("[DEBUG] mxchat_save_chat_message -> END for session_id: {$session_id}");
1121 - return $message_id;
1122 -}
1123 -
1124 -private function send_new_chat_notification($session_id, $user_info = array()) {
1125 - $options = get_option('mxchat_transcripts_options');
1126 -
1127 - // Check if notifications are enabled
1128 - if (empty($options['mxchat_enable_notifications'])) {
1129 - return false;
1130 - }
1131 -
1132 - // Get notification email
1133 - // Multiple recipients supported (plan 2f131a). wp_mail() takes the array
1134 - // directly. Empty field still falls back to admin_email inside the helper;
1135 - // an unusable stored value sends nowhere, as before.
1136 - $to = MxChat_Utils::notification_recipients($options);
1137 -
1138 - if (empty($to)) {
1139 - return false;
1140 - }
1141 -
1142 - // Prepare email content
1143 - $subject = sprintf('[%s] New Chat Session Started', get_bloginfo('name'));
1144 -
1145 - $user_identifier = isset($user_info['identifier']) ? $user_info['identifier'] : 'Guest';
1146 - $user_email = isset($user_info['email']) ? $user_info['email'] : 'Not provided';
1147 - $user_ip = isset($user_info['ip']) ? $user_info['ip'] : $_SERVER['REMOTE_ADDR'];
1148 -
1149 - $message = sprintf(
1150 - "A new chat session has started on your website.\n\n" .
1151 - "Session ID: %s\n" .
1152 - "User: %s\n" .
1153 - "Email: %s\n" .
1154 - "IP Address: %s\n" .
1155 - "Time: %s\n\n" .
1156 - "View transcripts: %s",
1157 - $session_id,
1158 - $user_identifier,
1159 - $user_email,
1160 - $user_ip,
1161 - current_time('mysql'),
1162 - admin_url('admin.php?page=mxchat-transcripts')
1163 - );
1164 -
1165 - // Send email
1166 - return wp_mail($to, $subject, $message);
1167 -}
1168 -
1169 -/**
1170 - * Schedule delayed transcript email for a session
1171 - * Reschedules if a new user message is received
1172 - */
1173 -private function schedule_delayed_transcript_email($session_id) {
1174 - $options = get_option('mxchat_transcripts_options');
1175 -
1176 - // Check if auto-email is enabled
1177 - if (empty($options['mxchat_auto_email_transcript_enabled'])) {
1178 - return;
1179 - }
1180 -
1181 - // Get notification email
1182 - // Gate only — the recipients are resolved again at send time, not carried
1183 - // through the cron args (plan 2f131a).
1184 - if (empty(MxChat_Utils::notification_recipients($options))) {
1185 - return;
1186 - }
1187 -
1188 - // Get delay in minutes (default 30)
1189 - $delay_minutes = isset($options['mxchat_auto_email_transcript_delay']) ?
1190 - intval($options['mxchat_auto_email_transcript_delay']) : 30;
1191 -
1192 - // Clear any existing scheduled event for this session
1193 - $hook = 'mxchat_send_delayed_transcript';
1194 - $args = array($session_id);
1195 - $timestamp = wp_next_scheduled($hook, $args);
1196 -
1197 - if ($timestamp) {
1198 - wp_unschedule_event($timestamp, $hook, $args);
1199 - }
1200 -
1201 - // Schedule new event
1202 - $schedule_time = time() + ($delay_minutes * 60);
1203 - wp_schedule_single_event($schedule_time, $hook, $args);
1204 -}
1205 -
1206 -/**
1207 - * Check if chat messages contain contact information (email or phone number)
1208 - *
1209 - * @param array $messages Array of message objects with 'message' property
1210 - * @param object|null $session_data Session data object with user_email property
1211 - * @return bool True if contact info found, false otherwise
1212 - */
1213 -private function chat_contains_contact_info($messages, $session_data = null) {
1214 - // Check if session already has a stored email
1215 - if ($session_data && !empty($session_data->user_email)) {
1216 - return true;
1217 - }
1218 -
1219 - // Email regex pattern
1220 - $email_pattern = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/';
1221 -
1222 - // Phone number patterns (covers various formats including international, WhatsApp style)
1223 - // Matches: +1234567890, (123) 456-7890, 123-456-7890, 123.456.7890, 1234567890, +1 234 567 8900, etc.
1224 - $phone_pattern = '/(?:\+?\d{1,3}[-.\s]?)?\(?\d{2,4}\)?[-.\s]?\d{2,4}[-.\s]?\d{2,4}(?:[-.\s]?\d{1,4})?/';
1225 -
1226 - // Only check user messages (not assistant responses)
1227 - foreach ($messages as $msg) {
1228 - if ($msg->role !== 'user') {
1229 - continue;
1230 - }
1231 -
1232 - $message_text = $msg->message;
1233 -
1234 - // Check for email
1235 - if (preg_match($email_pattern, $message_text)) {
1236 - return true;
1237 - }
1238 -
1239 - // Check for phone number (must be at least 7 digits total to avoid false positives)
1240 - if (preg_match($phone_pattern, $message_text, $matches)) {
1241 - // Count actual digits to avoid matching short numbers
1242 - $digits_only = preg_replace('/\D/', '', $matches[0]);
1243 - if (strlen($digits_only) >= 7) {
1244 - return true;
1245 - }
1246 - }
1247 - }
1248 -
1249 - return false;
1250 -}
1251 -
1252 -/**
1253 - * Send the delayed transcript email with .txt attachment
1254 - */
1255 -public function mxchat_send_delayed_transcript($session_id) {
1256 - global $wpdb;
1257 -
1258 - // plan-mxchat-20260731-d42bec — this is the one place a session id becomes a
1259 - // filesystem path segment (see the $temp_file build below), so validate here
1260 - // too even though intake is now validated. This runs from a scheduled event,
1261 - // so its argument comes from whatever was stored at schedule time rather than
1262 - // straight from the current request.
1263 - $session_id = MxChat_Utils::sanitize_session_id($session_id);
1264 - if ($session_id === '') {
1265 - return false;
1266 - }
1267 -
1268 - $options = get_option('mxchat_transcripts_options');
1269 -
1270 - // Get notification recipients (plan 2f131a — may be a list)
1271 - $to = MxChat_Utils::notification_recipients($options);
1272 -
1273 - if (empty($to)) {
1274 - return false;
1275 - }
1276 -
1277 - // Get all messages for this session
1278 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1279 - $messages = $wpdb->get_results($wpdb->prepare(
1280 - "SELECT role, message, timestamp FROM {$table_name}
1281 - WHERE session_id = %s
1282 - ORDER BY timestamp ASC",
1283 - $session_id
1284 - ));
1285 -
1286 - if (empty($messages)) {
1287 - return false;
1288 - }
1289 -
1290 - // Get session metadata
1291 - $sessions_table = $wpdb->prefix . 'mxchat_sessions';
1292 - $session_data = $wpdb->get_row($wpdb->prepare(
1293 - "SELECT * FROM {$sessions_table} WHERE session_id = %s",
1294 - $session_id
1295 - ));
1296 -
1297 - // Check if contact info is required and if it's present
1298 - $require_contact = !empty($options['mxchat_auto_email_transcript_require_contact']);
1299 - if ($require_contact && !$this->chat_contains_contact_info($messages, $session_data)) {
1300 - // Contact info required but not found - skip sending
1301 - return false;
1302 - }
1303 -
1304 - // Build transcript content
1305 - $transcript_content = "Chat Transcript\n";
1306 - $transcript_content .= "================\n\n";
1307 - $transcript_content .= "Session ID: " . $session_id . "\n";
1308 -
1309 - if ($session_data) {
1310 - $transcript_content .= "User: " . ($session_data->user_identifier ?: 'Guest') . "\n";
1311 - $transcript_content .= "Email: " . ($session_data->user_email ?: 'Not provided') . "\n";
1312 - $transcript_content .= "Started: " . $session_data->created_at . "\n";
1313 - }
1314 -
1315 - $transcript_content .= "\n" . str_repeat("=", 50) . "\n\n";
1316 -
1317 - // Add messages
1318 - foreach ($messages as $msg) {
1319 - // 'agent' rows are live-agent (human) replies — label them as such in
1320 - // the emailed transcript, same distinction the Transcripts viewer draws.
1321 - $role_label = ($msg->role === 'user') ? 'User' : (($msg->role === 'agent') ? 'Live Agent' : 'Assistant');
1322 - $transcript_content .= "[{$msg->timestamp}] {$role_label}:\n";
1323 - $transcript_content .= $msg->message . "\n\n";
1324 - }
1325 -
1326 - // Create temporary file for attachment using WP_Filesystem
1327 - $upload_dir = wp_upload_dir();
1328 - // basename() is the SECOND independent control on this write
1329 - // (plan-mxchat-20260731-d42bec). The validator above already rejects any id
1330 - // containing a path separator; this survives someone loosening it later.
1331 - $temp_file = $upload_dir['basedir'] . '/' . basename('mxchat-transcript-' . $session_id . '.txt');
1332 - global $wp_filesystem;
1333 - if (empty($wp_filesystem)) {
1334 - require_once ABSPATH . 'wp-admin/includes/file.php';
1335 - WP_Filesystem();
1336 - }
1337 - $wp_filesystem->put_contents($temp_file, $transcript_content, FS_CHMOD_FILE);
1338 -
1339 - // Prepare email
1340 - $subject = sprintf('[%s] Chat Transcript - Session %s', get_bloginfo('name'), substr($session_id, 0, 8));
1341 -
1342 - $message = "Please find attached the full chat transcript.\n\n";
1343 - $message .= "Session ID: {$session_id}\n";
1344 -
1345 - if ($session_data) {
1346 - $message .= "User: " . ($session_data->user_identifier ?: 'Guest') . "\n";
1347 - $message .= "Email: " . ($session_data->user_email ?: 'Not provided') . "\n";
1348 - }
1349 -
1350 - $message .= "\nView online: " . admin_url('admin.php?page=mxchat-transcripts');
1351 -
1352 - // Send email with attachment
1353 - $attachments = array($temp_file);
1354 - $result = wp_mail($to, $subject, $message, '', $attachments);
1355 -
1356 - // Clean up temporary file
1357 - if (file_exists($temp_file)) {
1358 - unlink($temp_file);
1359 - }
1360 -
1361 - return $result;
1362 -}
1363 -
1364 -
1365 -
1366 -public function mxchat_handle_save_email_and_response() {
1367 - //error_log('[DEBUG] ---------- mxchat_handle_save_email_and_response START ----------');
1368 - //error_log('DEBUG: POST data: ' . print_r($_POST, true));
1369 -
1370 - nocache_headers();
1371 -
1372 - // Validate nonce
1373 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce($_POST['nonce'])) {
1374 - //error_log(esc_html__('[ERROR] Invalid nonce in mxchat_handle_save_email_and_response', 'mxchat'));
1375 - wp_send_json_error(['message' => esc_html__('Invalid nonce.', 'mxchat')]);
1376 - wp_die();
1377 - }
1378 -
1379 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
1380 - $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
1381 - $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
1382 -
1383 - //error_log("[DEBUG] handle_save_email_and_response -> session_id: {$session_id}, email: {$email}, name: {$name}");
1384 -
1385 - if (empty($session_id) || $session_id === 'null' || empty($email)) {
1386 - //error_log("[ERROR] Missing session_id or email: session_id={$session_id}, email={$email}");
1387 - wp_send_json_error(['message' => esc_html__('Session ID or email is missing.', 'mxchat')]);
1388 - wp_die();
1389 - }
1390 -
1391 - // Validate name if provided (check if name field is enabled and name is required)
1392 - $options = get_option('mxchat_options', []);
1393 - $name_field_enabled = isset($options['enable_name_field']) &&
1394 - ($options['enable_name_field'] === '1' || $options['enable_name_field'] === 'on');
1395 -
1396 - if ($name_field_enabled && (empty($name) || strlen(trim($name)) < 2 || strlen(trim($name)) > 100)) {
1397 - //error_log("[ERROR] Invalid name: {$name} (enabled: {$name_field_enabled})");
1398 - wp_send_json_error(['message' => esc_html__('Name must be between 2 and 100 characters.', 'mxchat')]);
1399 - wp_die();
1400 - }
1401 -
1402 - // 1) Always store email in the session store (one row per session, 5658f2)
1403 - MxChat_Session_Store::set($session_id, 'email', $email);
1404 -
1405 - // Store name if provided
1406 - if (!empty($name)) {
1407 - MxChat_Session_Store::set($session_id, 'name', $name);
1408 - }
1409 -
1410 - // 2) (Optional) Also store in DB if a row already exists
1411 - global $wpdb;
1412 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1413 -
1414 - // Make sure we have a valid placeholder in prepare
1415 - $sql = $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", $session_id);
1416 - $session_count = $wpdb->get_var($sql);
1417 -
1418 - //error_log("[DEBUG] handle_save_email_and_response -> session_count for {$session_id}: {$session_count} (SQL: {$sql})");
1419 -
1420 - if ($session_count) {
1421 - // Update both user_email and user_name if row(s) exist
1422 - if (!empty($name)) {
1423 - $update_sql = $wpdb->prepare(
1424 - "UPDATE {$table_name} SET user_email = %s, user_name = %s WHERE session_id = %s",
1425 - $email,
1426 - $name,
1427 - $session_id
1428 - );
1429 - } else {
1430 - $update_sql = $wpdb->prepare(
1431 - "UPDATE {$table_name} SET user_email = %s WHERE session_id = %s",
1432 - $email,
1433 - $session_id
1434 - );
1435 - }
1436 - $wpdb->query($update_sql);
1437 - //error_log("[DEBUG] handle_save_email_and_response -> DB updated: {$update_sql}");
1438 - } else {
1439 - //error_log("[INFO] handle_save_email_and_response -> No DB entry for {$session_id}, so email/name is only in wp_options.");
1440 - }
1441 -
1442 - // Provide success response (same as original)
1443 - $bot_message = __('Thanks for providing your email! You can continue chatting now.', 'mxchat');
1444 - //error_log("[DEBUG] handle_save_email_and_response -> success, returning bot_message: {$bot_message}");
1445 - wp_send_json_success(['message' => $bot_message]);
1446 - wp_die();
1447 -}
1448 -
1449 -public function mxchat_check_email_provided() {
1450 - //error_log('[DEBUG] ---------- mxchat_check_email_provided START ----------');
1451 -
1452 - nocache_headers();
1453 -
1454 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce($_POST['nonce'])) {
1455 - //error_log('[ERROR] Invalid nonce in mxchat_check_email_provided');
1456 - wp_send_json_error(['message' => esc_html__('Invalid nonce', 'mxchat')]);
1457 - }
1458 -
1459 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
1460 - if (empty($session_id) || $session_id === 'null') {
1461 - //error_log('[ERROR] No session ID provided in mxchat_check_email_provided');
1462 - wp_send_json_error(['message' => esc_html__('No session ID provided', 'mxchat')]);
1463 - }
1464 -
1465 - // Check if the user is logged in
1466 - if (is_user_logged_in()) {
1467 - $current_user = wp_get_current_user();
1468 - //error_log("[DEBUG] User is logged in as {$current_user->user_email}");
1469 -
1470 - // Get user's display name for logged in users
1471 - $user_name = !empty($current_user->display_name) ? $current_user->display_name :
1472 - (!empty($current_user->first_name) ? $current_user->first_name : '');
1473 -
1474 - $response_data = ['logged_in' => true, 'email' => $current_user->user_email];
1475 - if (!empty($user_name)) {
1476 - $response_data['name'] = $user_name;
1477 - }
1478 -
1479 - wp_send_json_success($response_data);
1480 - }
1481 -
1482 - // Check if name field is required
1483 - $options = get_option('mxchat_options', []);
1484 - $name_field_enabled = isset($options['enable_name_field']) &&
1485 - ($options['enable_name_field'] === '1' || $options['enable_name_field'] === 'on');
1486 -
1487 - $stored_email = MxChat_Session_Store::get($session_id, 'email', '');
1488 -
1489 - // Check for stored name
1490 - $stored_name = MxChat_Session_Store::get($session_id, 'name', '');
1491 -
1492 - // Check if we have email and name (if name is required)
1493 - $has_required_info = !empty($stored_email);
1494 -
1495 - if ($name_field_enabled) {
1496 - $has_required_info = $has_required_info && !empty($stored_name);
1497 - }
1498 -
1499 - if ($has_required_info) {
1500 - //error_log("[DEBUG] mxchat_check_email_provided -> Required info found, returning success");
1501 -
1502 - $response_data = ['email' => $stored_email];
1503 - if (!empty($stored_name)) {
1504 - $response_data['name'] = $stored_name;
1505 - }
1506 -
1507 - wp_send_json_success($response_data);
1508 - } else {
1509 - //error_log("[DEBUG] mxchat_check_email_provided -> Required info missing, returning error");
1510 - wp_send_json_error(['message' => esc_html__('No email found', 'mxchat')]);
1511 - }
1512 -}
1513 -
1514 -/**
1515 - * Send error response in appropriate format based on streaming mode
1516 - * ADDED: Helper method to consistently handle errors in both streaming and non-streaming modes
1517 - *
1518 - * @param string $error_message The error message to display
1519 - * @param string $error_code Optional error code for debugging
1520 - */
1521 -private function send_error_response($error_message, $error_code = 'api_error') {
1522 - if ($this->is_streaming) {
1523 - echo "data: " . json_encode([
1524 - 'error' => true,
1525 - 'error_message' => $error_message,
1526 - 'error_code' => $error_code,
1527 - 'text' => $error_message,
1528 - 'message' => $error_message
1529 - ]) . "\n\n";
1530 - echo "data: [DONE]\n\n";
1531 - flush();
1532 - } else {
1533 - wp_send_json_error([
1534 - 'error_message' => $error_message,
1535 - 'error_code' => $error_code
1536 - ]);
1537 - }
1538 - wp_die();
1539 -}
1540 -
1541 -public function mxchat_handle_chat_request() {
1542 - global $wpdb;
1543 -
1544 - // Debug: Log incoming bot_id
1545 - $bot_id = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
1546 - //error_log("=== MXCHAT DEBUG: Starting chat request ===");
1547 - //error_log("MXCHAT DEBUG: Bot ID received: " . $bot_id);
1548 -
1549 - // Get bot-specific options
1550 - $bot_options = $this->get_bot_options($bot_id);
1551 - $current_options = !empty($bot_options) ? $bot_options : $this->options;
1552 -
1553 - // Check if this is a streaming request
1554 - // Allow force_streaming_test parameter to bypass the setting check (for admin compatibility testing)
1555 - $force_streaming_test = isset($_POST['force_streaming_test']) && $_POST['force_streaming_test'] === '1' && current_user_can('administrator');
1556 - $is_streaming = isset($_POST['action']) && $_POST['action'] === 'mxchat_stream_chat' &&
1557 - ($force_streaming_test || (isset($current_options['enable_streaming_toggle']) && $current_options['enable_streaming_toggle'] === 'on'));
1558 -
1559 - // ADDED: Store streaming state in class property for use in private methods
1560 - $this->is_streaming = $is_streaming;
1561 -
1562 - // NOTE: Streaming headers are now set later via setup_streaming_headers()
1563 - // This allows actions/forms to return JSON responses without header conflicts
1564 -
1565 - // Check if MX Chat Moderation is active
1566 - if (class_exists('MX_Chat_Moderation')) {
1567 - // Get user email and IP
1568 - $user_email = '';
1569 - $user_ip = $_SERVER['REMOTE_ADDR'];
1570 -
1571 - // If user is logged in, get their email
1572 - if (is_user_logged_in()) {
1573 - $current_user = wp_get_current_user();
1574 - $user_email = $current_user->user_email;
1575 - }
1576 -
1577 - // Create ban handler instance
1578 - $ban_handler = new MX_Chat_Ban_Handler();
1579 -
1580 - // Check if user is banned by IP
1581 - if ($ban_handler->check_ban($user_ip, 'ip')) {
1582 - wp_send_json([
1583 - 'success' => false,
1584 - 'message' => esc_html__('Access denied. Your IP address has been banned.', 'mxchat'),
1585 - 'status' => 'banned'
1586 - ]);
1587 - wp_die();
1588 - }
1589 -
1590 - // If user is logged in, also check email
1591 - if (!empty($user_email) && $ban_handler->check_ban($user_email, 'email')) {
1592 - wp_send_json([
1593 - 'success' => false,
1594 - 'message' => esc_html__('Access denied. Your email address has been banned.', 'mxchat'),
1595 - 'status' => 'banned'
1596 - ]);
1597 - wp_die();
1598 - }
1599 - }
1600 -
1601 - $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
1602 - $this->productCardHtml = '';
1603 - $this->videoEmbedHtml = '';
1604 - // Reset the per-turn function-calling UI capture (plan 48a57a).
1605 - $this->fc_ui_html = '';
1606 - $this->fc_ui_images = array();
1607 - $this->fc_ui_captured = false;
1608 -
1609 - // Get the actual WordPress user ID if logged in
1610 - $is_logged_in = is_user_logged_in();
1611 - if ($is_logged_in) {
1612 - $user_id = get_current_user_id(); // This will get the actual WordPress user ID
1613 - } else {
1614 - // For logged-out users, use your existing identifier method
1615 - $user_id = $this->mxchat_get_user_identifier();
1616 - }
1617 -
1618 - // Get and sanitize the user identifier
1619 - $user_id = sanitize_key($user_id);
1620 -
1621 - // Check rate limit using new settings structure
1622 - $rate_limit_result = $this->check_rate_limit();
1623 -
1624 - if ($rate_limit_result !== true) {
1625 - wp_send_json([
1626 - 'success' => false,
1627 - 'message' => $rate_limit_result['message'],
1628 - 'status' => 'rate_limit_exceeded'
1629 - ]);
1630 - wp_die();
1631 - }
1632 -
1633 - // Rest of your existing code...
1634 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
1635 -
1636 - // Treat the literal strings 'null' / 'undefined' as missing too. Browser edge cases
1637 - // (Safari ITP, private mode, cross-origin iframes with partitioned storage) can cause
1638 - // the frontend FormData.append() to stringify a null session_id into the literal
1639 - // "null", which would otherwise pass empty() and pollute the transcripts table with
1640 - // ghost sessions that group every visitor's first message under one row.
1641 - if ($session_id === 'null' || $session_id === 'undefined') {
1642 - $session_id = '';
1643 - }
1644 -
1645 - if (empty($session_id)) {
1646 - wp_send_json_error(esc_html__('Session ID is missing.', 'mxchat'));
1647 - wp_die();
1648 - }
1649 -
1650 - // Update session owner if it changed (e.g. IP changed due to network switch)
1651 - // The session ID itself is the authentication — if the client has it, they own it
1652 - $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
1653 - $session_owner = MxChat_Session_Store::get($session_id, 'owner');
1654 -
1655 - if (!$session_owner || $session_owner !== $current_user_identifier) {
1656 - MxChat_Session_Store::set($session_id, 'owner', $current_user_identifier);
1657 - }
1658 -
1659 - // Validate and sanitize the incoming message
1660 - if (empty($_POST['message'])) {
1661 - wp_send_json_error(esc_html__('No message received.', 'mxchat'));
1662 - wp_die();
1663 - }
1664 -
1665 - // Enforce the configurable max input length (plan a3fae2 part C). 0 = unlimited.
1666 - // Server-side guard backing the textarea's client-side maxlength (which is bypassable).
1667 - // Reads the global core setting and measures characters (mb_strlen on the unslashed
1668 - // raw POST), matching the maxlength semantics.
1669 - $mxchat_max_input_length = isset($this->options['max_input_length']) ? intval($this->options['max_input_length']) : 0;
1670 - if ($mxchat_max_input_length > 0) {
1671 - $mxchat_incoming_raw = is_string($_POST['message']) ? wp_unslash($_POST['message']) : '';
1672 - if (mb_strlen($mxchat_incoming_raw) > $mxchat_max_input_length) {
1673 - wp_send_json([
1674 - 'success' => false,
1675 - /* translators: %d: maximum allowed characters */
1676 - 'message' => sprintf(esc_html__('Your message is too long. Please keep it under %d characters.', 'mxchat'), $mxchat_max_input_length),
1677 - 'status' => 'message_too_long'
1678 - ]);
1679 - wp_die();
1680 - }
1681 - }
1682 -
1683 -
1684 - // Track originating page for first message in session
1685 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1686 -
1687 - // Check if originating page columns exist
1688 - $columns_exist = $wpdb->get_var("SHOW COLUMNS FROM $table_name LIKE 'originating_page_url'");
1689 -
1690 - if ($columns_exist) {
1691 - // Check if this session already has messages
1692 - $message_count = $wpdb->get_var($wpdb->prepare(
1693 - "SELECT COUNT(*) FROM $table_name WHERE session_id = %s",
1694 - $session_id
1695 - ));
1696 -
1697 - // If this is the first message in the session
1698 - if ($message_count == 0) {
1699 - // Get originating page from JavaScript (preferred) or HTTP_REFERER (fallback)
1700 - $originating_url = '';
1701 - $originating_title = '';
1702 -
1703 - // Try to get from POST data first (sent by JavaScript)
1704 - if (isset($_POST['current_page_url'])) {
1705 - $originating_url = esc_url_raw($_POST['current_page_url']);
1706 - $originating_title = isset($_POST['current_page_title'])
1707 - ? sanitize_text_field($_POST['current_page_title'])
1708 - : '';
1709 - }
1710 - // Fallback to HTTP_REFERER if not provided by JavaScript
1711 - else if (isset($_SERVER['HTTP_REFERER'])) {
1712 - $originating_url = esc_url_raw($_SERVER['HTTP_REFERER']);
1713 - }
1714 -
1715 - // Generate title if we have URL but no title
1716 - if ($originating_url && empty($originating_title)) {
1717 - $parsed_url = parse_url($originating_url);
1718 - $path = isset($parsed_url['path']) ? trim($parsed_url['path'], '/') : '';
1719 -
1720 - if (empty($path) || $path === 'index.php' || $path === 'index.html') {
1721 - $originating_title = 'Homepage';
1722 - } else {
1723 - // Clean up the path to make a readable title
1724 - $originating_title = str_replace(['-', '_', '/', '.php', '.html'], ' ', $path);
1725 - $originating_title = ucwords(trim($originating_title));
1726 - }
1727 - }
1728 -
1729 - // Store for later use when saving the message
1730 - $this->pending_originating_page = [
1731 - 'url' => $originating_url,
1732 - 'title' => $originating_title
1733 - ];
1734 - }
1735 - }
1736 -
1737 -
1738 -
1739 - // Get page context if provided
1740 - $page_context = null;
1741 - if (isset($_POST['page_context']) && !empty($_POST['page_context'])) {
1742 - $page_context_raw = stripslashes($_POST['page_context']);
1743 - $page_context = json_decode($page_context_raw, true);
1744 -
1745 - // Validate page context structure
1746 - if (is_array($page_context) &&
1747 - isset($page_context['url']) &&
1748 - isset($page_context['title']) &&
1749 - isset($page_context['content'])) {
1750 -
1751 - // Sanitize page context
1752 - $page_context['url'] = esc_url_raw($page_context['url']);
1753 - $page_context['title'] = sanitize_text_field($page_context['title']);
1754 - $page_context['content'] = wp_kses_post($page_context['content']);
1755 - } else {
1756 - $page_context = null;
1757 - }
1758 - }
1759 -
1760 - // Modify the message sanitization to preserve PHP tags in code blocks
1761 - $allowed_tags = [
1762 - 'pre' => [],
1763 - 'code' => ['class' => true],
1764 - 'span' => ['class' => true],
1765 - 'div' => ['class' => true],
1766 - ];
1767 -
1768 - // First preserve code blocks
1769 - $message = preg_replace_callback('/<pre><code.*?>.*?<\/code><\/pre>/s', function($matches) {
1770 - return htmlspecialchars_decode($matches[0]);
1771 - }, $_POST['message']);
1772 -
1773 - // Then apply sanitization
1774 - $message = wp_kses($message, $allowed_tags);
1775 -
1776 - // Preserve code blocks from markdown conversion
1777 - $message = preg_replace('/```(\w+)?\s*([\s\S]+?)```/s', '<pre><code class="$1">$2</code></pre>', $message);
1778 - $message = apply_filters('mxchat_filter_message', $message, 'prompt', $session_id);
1779 -
1780 - // ===== SIMPLIFIED TESTING PANEL INITIALIZATION =====
1781 - // Always initialize testing data for admins (no toggle needed)
1782 - $testing_data = null;
1783 - if (current_user_can('administrator')) {
1784 - // For vision messages, use the original user message for the query display
1785 - $query_for_testing = $message;
1786 - if (isset($_POST['vision_processed']) && $_POST['vision_processed'] && isset($_POST['original_user_message'])) {
1787 - $query_for_testing = sanitize_textarea_field($_POST['original_user_message']);
1788 - }
1789 -
1790 - $testing_data = [
1791 - 'query' => $query_for_testing,
1792 - 'timestamp' => time(),
1793 - 'top_matches' => [],
1794 - 'action_matches' => [], // Initialize action matches array
1795 - 'page_context' => $page_context, // Include page context in testing data
1796 - 'is_vision' => isset($_POST['vision_processed']) && $_POST['vision_processed'],
1797 - 'bot_id' => $bot_id // Include bot ID in testing data
1798 - ];
1799 -
1800 - // Get similarity threshold from bot options or default options
1801 - $similarity_threshold = isset($current_options['similarity_threshold'])
1802 - ? ((int) $current_options['similarity_threshold']) / 100
1803 - : 0.35;
1804 -
1805 - $testing_data['similarity_threshold'] = $similarity_threshold;
1806 -
1807 - // Determine knowledge base type using bot-specific config
1808 - $bot_pinecone_config = $this->get_bot_pinecone_config($bot_id);
1809 - $use_pinecone = isset($bot_pinecone_config['use_pinecone']) ? $bot_pinecone_config['use_pinecone'] : false;
1810 - $testing_data['knowledge_base_type'] = $use_pinecone ? 'Pinecone' : 'WordPress Database';
1811 - }
1812 - // ===== END SIMPLIFIED TESTING INITIALIZATION =====
1813 -
1814 - // Add debug before and after:
1815 - //error_log('MxChat Core: About to call mxchat_pre_process_message filter with message: ' . $message);
1816 - $pre_processed_result = apply_filters('mxchat_pre_process_message', $message, $user_id, $session_id);
1817 - //error_log('MxChat Core: Filter returned: ' . (is_array($pre_processed_result) ? 'array' : $pre_processed_result));
1818 -
1819 -
1820 - // If the pre-processing returned a result (not the original message), use it directly
1821 - if (is_array($pre_processed_result) && isset($pre_processed_result['text'])) {
1822 - // Save the AI response
1823 - $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['text']);
1824 -
1825 - // Save HTML content if provided
1826 - if (!empty($pre_processed_result['html'])) {
1827 - $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['html']);
1828 - }
1829 -
1830 - // Add testing data if admin
1831 - $response_data = [
1832 - 'text' => $pre_processed_result['text'],
1833 - 'html' => $pre_processed_result['html'] ?? '',
1834 - 'session_id' => $session_id
1835 - ];
1836 -
1837 - if ($testing_data !== null) {
1838 - $response_data['testing_data'] = $testing_data;
1839 - }
1840 -
1841 - wp_send_json($response_data);
1842 - wp_die();
1843 - }
1844 -
1845 - // Save the user's message - handle vision processed messages differently
1846 - if (isset($_POST['vision_processed']) && $_POST['vision_processed'] && isset($_POST['original_user_message'])) {
1847 - // For vision messages, save the original user message with image indicator
1848 - $original_message = sanitize_textarea_field($_POST['original_user_message']);
1849 - if (isset($_POST['vision_images_count']) && $_POST['vision_images_count'] > 0) {
1850 - $image_count = intval($_POST['vision_images_count']);
1851 - $original_message .= " [{$image_count} image(s)]";
1852 - }
1853 - $this->mxchat_save_chat_message($session_id, 'user', $original_message);
1854 - } else {
1855 - // Regular message - save as normal
1856 - $this->mxchat_save_chat_message($session_id, 'user', $message);
1857 - }
1858 -
1859 -
1860 - if (is_email($message)) {
1861 - // Add the email to Loops
1862 - $this->add_email_to_loops($message);
1863 -
1864 - // Get the user's success message instruction using current_options
1865 - $user_success_message = $current_options['email_capture_response'] ?? __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
1866 -
1867 - // Set instruction for AI using the user's success message
1868 - $this->current_action_instruction = $user_success_message;
1869 -
1870 - // Clear the email capture transient since we got the email
1871 - delete_transient('mxchat_email_capture_' . $user_id);
1872 - }
1873 -
1874 - // Check if we're in an email capture flow but user hasn't provided email yet
1875 - elseif (get_transient('mxchat_email_capture_' . $user_id)) {
1876 - // Check if the message contains an email (not the whole message being an email)
1877 - if (preg_match('/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/', $message, $matches)) {
1878 - $extracted_email = $matches[0];
1879 -
1880 - // Add the extracted email to Loops
1881 - $this->add_email_to_loops($extracted_email);
1882 -
1883 - // Get the user's success message instruction using current_options
1884 - $user_success_message = $current_options['email_capture_response'] ?? __('Thank you for providing your email! You\'ve been added to our list.', 'mxchat');
1885 -
1886 - // Set instruction for AI using the user's success message
1887 - $this->current_action_instruction = $user_success_message;
1888 -
1889 - // Clear the email capture transient since we got the email
1890 - delete_transient('mxchat_email_capture_' . $user_id);
1891 - }
1892 - // If no email found but we're in capture mode, remind them
1893 - else {
1894 - // Get the original instruction to remind them using current_options
1895 - $original_instruction = $current_options['triggered_phrase_response'] ?? __("Please provide your email address.", 'mxchat');
1896 - $this->current_action_instruction = $original_instruction;
1897 - }
1898 - }
1899 -
1900 - $intent_info = '';
1901 -
1902 - // Check chat mode
1903 - $chat_mode = MxChat_Session_Store::get($session_id, 'mode', 'ai');
1904 -
1905 - // Handle agent mode
1906 - // Handle agent mode
1907 - if ($chat_mode === 'agent') {
1908 - // First, check for switch intent before doing anything else
1909 - $intent_matched = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
1910 -
1911 - // Capture action analysis for testing panel after intent check
1912 - if ($testing_data !== null && isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
1913 - $testing_data['action_matches'] = $this->last_action_analysis;
1914 - }
1915 -
1916 - // Around line 506, in the agent mode handling section:
1917 - if ($intent_matched && !empty($this->fallbackResponse['text'])) {
1918 - // Update chat mode first
1919 - MxChat_Session_Store::set($session_id, 'mode', 'ai');
1920 -
1921 - // Clear any existing PDF context to start fresh
1922 - $this->clear_pdf_transients($session_id);
1923 -
1924 - // Prepare clean switch response with explicit chat_mode
1925 - $response_data = [
1926 - 'text' => $this->fallbackResponse['text'],
1927 - 'html' => $this->fallbackResponse['html'] ?? '',
1928 - 'session_id' => $session_id,
1929 - 'chat_mode' => 'ai' // EXPLICITLY SET THIS
1930 - ];
1931 -
1932 - if ($testing_data !== null) {
1933 - $response_data['testing_data'] = $testing_data;
1934 - }
1935 -
1936 - // Save the mode switch message
1937 - $this->mxchat_save_chat_message($session_id, 'system', esc_html__('Switched to AI chat mode', 'mxchat'));
1938 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
1939 -
1940 - // Send response and exit
1941 - wp_send_json($response_data);
1942 - wp_die();
1943 - } elseif (!$intent_matched) {
1944 - // No intent matched, handle live agent message
1945 - try {
1946 - $this->mxchat_send_user_message_to_agent($message, $user_id, $session_id);
1947 -
1948 - $agent_response = [
1949 - 'status' => 'waiting_for_agent',
1950 - 'message' => esc_html__('Message sent to live agent.', 'mxchat')
1951 - ];
1952 -
1953 - if ($testing_data !== null) {
1954 - $agent_response['testing_data'] = $testing_data;
1955 - }
1956 -
1957 - wp_send_json_success($agent_response);
1958 - } catch (\Exception $e) {
1959 - wp_send_json_error(esc_html__('Failed to send message to agent', 'mxchat'));
1960 - }
1961 - wp_die();
1962 - }
1963 - }
1964 -
1965 - // Step 1: Check for new PDF URL in the message
1966 - if (!isset($_POST['vision_processed']) && preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
1967 - $new_pdf_url = $matches[0];
1968 -
1969 - // Check if this is likely a PDF-related request
1970 - $pdf_keywords = ['pdf', 'document', 'read', 'analyze'];
1971 - $is_pdf_request = false;
1972 -
1973 - foreach ($pdf_keywords as $keyword) {
1974 - if (stripos($message, $keyword) !== false) {
1975 - $is_pdf_request = true;
1976 - break;
1977 - }
1978 - }
1979 -
1980 - // If it looks like a PDF request or we're waiting for a PDF URL
1981 - if ($is_pdf_request || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
1982 - // Validate HTTPS
1983 - if (wp_http_validate_url($new_pdf_url) && parse_url($new_pdf_url, PHP_URL_SCHEME) === 'https') {
1984 - // Extract filename from URL
1985 - $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
1986 -
1987 - // Clear previous PDF transients
1988 - $this->clear_pdf_transients($session_id);
1989 -
1990 - // Process new PDF using current_options
1991 - $max_pages = $current_options['pdf_max_pages'] ?? 69;
1992 - $embeddings = $this->fetch_and_split_pdf_pages($new_pdf_url, $max_pages);
1993 -
1994 - if ($embeddings === 'too_many_pages') {
1995 - $error_text = sprintf(
1996 - $current_options['pdf_intent_error_text'] ??
1997 - esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
1998 - $max_pages
1999 - );
2000 - $this->fallbackResponse['text'] = $error_text;
2001 - } elseif ($embeddings) {
2002 - // Store new PDF information
2003 - $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
2004 -
2005 - // If the filename is generic, create a more descriptive one
2006 - if (in_array($pdf_filename, ['results_download.php', 'download.php', 'view.php', 'pdf.php']) ||
2007 - strpos($pdf_filename, '.php') !== false) {
2008 - $pdf_filename = 'Document_' . date('Y-m-d_H-i') . '.pdf';
2009 - }
2010 -
2011 - set_transient('mxchat_pdf_url_' . $session_id, $new_pdf_url, HOUR_IN_SECONDS);
2012 - set_transient('mxchat_pdf_filename_' . $session_id, $pdf_filename, HOUR_IN_SECONDS);
2013 - set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
2014 - set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
2015 -
2016 - $success_text = $current_options['pdf_intent_success_text'] ??
2017 - esc_html__("I've processed the new PDF '{$pdf_filename}'. What questions do you have about it?", 'mxchat');
2018 -
2019 - $pdf_response = [
2020 - 'success' => true,
2021 - 'message' => $success_text,
2022 - 'data' => [
2023 - 'filename' => $pdf_filename
2024 - ]
2025 - ];
2026 -
2027 - if ($testing_data !== null) {
2028 - $pdf_response['testing_data'] = $testing_data;
2029 - }
2030 -
2031 - wp_send_json($pdf_response);
2032 - wp_die();
2033 - } else {
2034 - $error_text = $current_options['pdf_intent_error_text'] ??
2035 - esc_html__("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
2036 - // Surface the embedding provider's reason when that is why zero
2037 - // pages came back, rather than blaming the file (104a75).
2038 - $this->fallbackResponse['text'] = $this->mxchat_pdf_error_text_with_reason($error_text);
2039 - }
2040 -
2041 - $pdf_error_response = [
2042 - 'success' => false,
2043 - 'message' => $this->fallbackResponse['text']
2044 - ];
2045 -
2046 - if ($testing_data !== null) {
2047 - $pdf_error_response['testing_data'] = $testing_data;
2048 - }
2049 -
2050 - wp_send_json($pdf_error_response);
2051 - wp_die();
2052 - }
2053 - }
2054 - }
2055 -
2056 -
2057 - // Step 2: Detect intent and handle intent-based responses
2058 - $intent_result = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
2059 -
2060 - // Capture action analysis for testing panel after intent check
2061 - if ($testing_data !== null && isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
2062 - $testing_data['action_matches'] = $this->last_action_analysis;
2063 - }
2064 -
2065 - // Step 3: Handle the intent result appropriately
2066 - if ($intent_result !== false) {
2067 - // Intent was matched - ALWAYS send as JSON response, never streaming
2068 -
2069 - if (is_array($intent_result) && (isset($intent_result['text']) || isset($intent_result['html']))) {
2070 - // Intent returned a direct response array
2071 - $response_data = [
2072 - 'text' => $intent_result['text'] ?? '',
2073 - 'html' => $intent_result['html'] ?? '',
2074 - 'session_id' => $session_id
2075 - ];
2076 -
2077 - // IMPORTANT: Include chat_mode if present (for WhatsApp, Slack, etc.)
2078 - if (isset($intent_result['chat_mode'])) {
2079 - $response_data['chat_mode'] = $intent_result['chat_mode'];
2080 - }
2081 -
2082 - if ($testing_data !== null) {
2083 - $response_data['testing_data'] = $testing_data;
2084 - }
2085 -
2086 - wp_send_json($response_data);
2087 - wp_die();
2088 - } else if ($intent_result === true && (!empty($this->fallbackResponse['text']) || !empty($this->fallbackResponse['html']))) {
2089 - // Intent returned true and set fallbackResponse
2090 -
2091 - // SAVE TO TRANSCRIPT
2092 - if (!empty($this->fallbackResponse['text'])) {
2093 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
2094 - }
2095 - // Save action HTML (product cards, featured products, etc.) so it renders in transcripts
2096 - if (!empty($this->fallbackResponse['html'])) {
2097 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
2098 - }
2099 -
2100 - $response_data = [
2101 - 'text' => $this->fallbackResponse['text'] ?? '',
2102 - 'html' => $this->fallbackResponse['html'] ?? '',
2103 - 'session_id' => $session_id
2104 - ];
2105 -
2106 - if (isset($this->fallbackResponse['chat_mode'])) {
2107 - $response_data['chat_mode'] = $this->fallbackResponse['chat_mode'];
2108 - }
2109 -
2110 - if ($testing_data !== null) {
2111 - $response_data['testing_data'] = $testing_data;
2112 - }
2113 -
2114 - wp_send_json($response_data);
2115 - wp_die();
2116 - }
2117 - }
2118 -
2119 - // If we get here, no intent matched OR the intent didn't provide a usable response
2120 -
2121 - // Step 4: Generate AI response
2122 - // Get session start timestamp - when persistence is OFF, only include messages from this page load
2123 - $session_start_timestamp = isset($_POST['session_start_timestamp']) ? intval($_POST['session_start_timestamp']) : 0;
2124 - $conversation_history = $this->mxchat_fetch_conversation_history_for_ai($session_id, $session_start_timestamp);
2125 - $this->mxchat_increment_chat_count();
2126 -
2127 - // Generate embedding for the user's query - USE BOT-SPECIFIC API KEY
2128 - $api_key = $current_options['api_key'] ?? $this->options['api_key'];
2129 - $user_message_embedding = $this->mxchat_generate_embedding($message, $api_key);
2130 -
2131 - // Check if the embedding generation returned an error
2132 - if (is_array($user_message_embedding) && isset($user_message_embedding['error'])) {
2133 - $error_message = $user_message_embedding['error'];
2134 - $error_code = $user_message_embedding['error_code'] ?? 'embedding_error';
2135 -
2136 - // FIXED: Send error in appropriate format based on streaming mode
2137 - if ($is_streaming) {
2138 - echo "data: " . json_encode([
2139 - 'error' => true,
2140 - 'error_message' => $error_message,
2141 - 'error_code' => $error_code,
2142 - 'text' => $error_message,
2143 - 'message' => $error_message
2144 - ]) . "\n\n";
2145 - echo "data: [DONE]\n\n";
2146 - flush();
2147 - } else {
2148 - wp_send_json_error([
2149 - 'error_message' => $error_message,
2150 - 'error_code' => $error_code
2151 - ]);
2152 - }
2153 - wp_die();
2154 - }
2155 -
2156 - // Check if the embedding is valid
2157 - if (!is_array($user_message_embedding) || empty($user_message_embedding)) {
2158 - $error_message = esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat');
2159 -
2160 - // FIXED: Send error in appropriate format based on streaming mode
2161 - if ($is_streaming) {
2162 - echo "data: " . json_encode([
2163 - 'error' => true,
2164 - 'error_message' => $error_message,
2165 - 'error_code' => 'invalid_embedding',
2166 - 'text' => $error_message,
2167 - 'message' => $error_message
2168 - ]) . "\n\n";
2169 - echo "data: [DONE]\n\n";
2170 - flush();
2171 - } else {
2172 - wp_send_json_error([
2173 - 'error_message' => $error_message,
2174 - 'error_code' => 'invalid_embedding'
2175 - ]);
2176 - }
2177 - wp_die();
2178 - }
2179 -
2180 - // Build context with both knowledge base and PDF content if available
2181 - $context_content = "User asked: '{$message}'\n\n";
2182 -
2183 - // Add action instruction if present (add this right after the above line)
2184 - if (!empty($this->current_action_instruction)) {
2185 - $context_content .= "===== SPECIAL INSTRUCTION =====\n";
2186 - $context_content .= "IMPORTANT: " . $this->current_action_instruction . "\n";
2187 - $context_content .= "Respond naturally and conversationally while following this instruction.\n";
2188 - $context_content .= "===== END SPECIAL INSTRUCTION =====\n\n";
2189 -
2190 - // Clear the instruction after using it
2191 - $this->current_action_instruction = null;
2192 - }
2193 -
2194 -
2195 - // Add page context if available and contextual awareness is enabled using current_options
2196 - if ($page_context && isset($current_options['contextual_awareness_toggle']) && $current_options['contextual_awareness_toggle'] === 'on') {
2197 - $context_content .= "===== CURRENT PAGE CONTEXT =====\n";
2198 - $context_content .= "Page URL: " . $page_context['url'] . "\n";
2199 - $context_content .= "Page Title: " . $page_context['title'] . "\n";
2200 - $context_content .= "Page Content: " . $page_context['content'] . "\n";
2201 - $context_content .= "===== END CURRENT PAGE CONTEXT =====\n\n";
2202 - }
2203 -
2204 - // Get relevant content from knowledge base - PASS BOT_ID and MESSAGE for Vector Store
2205 - $relevant_content = $this->mxchat_find_relevant_content($user_message_embedding, $bot_id, $message);
2206 -
2207 - // NEW: Also extract URLs from system instructions (only if citation links enabled)
2208 - // Use fresh options to ensure we get the latest setting value
2209 - $fresh_options = get_option('mxchat_options', []);
2210 - $citation_links_enabled = isset($fresh_options['citation_links_toggle']) ? ($fresh_options['citation_links_toggle'] === 'on') : true;
2211 -
2212 - $system_instructions = $this->get_system_instructions($bot_id, $session_id);
2213 - if ($citation_links_enabled && !empty($system_instructions)) {
2214 - preg_match_all(
2215 - '#\bhttps?://[^\s<>"\']+#i',
2216 - $system_instructions,
2217 - $system_instruction_urls
2218 - );
2219 -
2220 - if (!empty($system_instruction_urls[0])) {
2221 - // Merge with existing valid URLs
2222 - $this->current_valid_urls = array_merge(
2223 - $this->current_valid_urls,
2224 - $system_instruction_urls[0]
2225 - );
2226 - // Remove duplicates
2227 - $this->current_valid_urls = array_unique($this->current_valid_urls);
2228 -
2229 - //error_log("Added " . count($system_instruction_urls[0]) . " URLs from system instructions");
2230 - }
2231 - }
2232 -
2233 -// ===== CAPTURE REAL SIMILARITY DATA FOR ADMINS =====
2234 -if ($testing_data !== null && $this->last_similarity_analysis !== null) {
2235 - // Update testing data with the REAL similarity analysis
2236 - $testing_data['top_matches'] = $this->last_similarity_analysis['top_matches'];
2237 - $testing_data['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
2238 - $testing_data['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'];
2239 - $testing_data['sources_used'] = $this->last_similarity_analysis['sources_used'] ?? 0;
2240 - $testing_data['total_chunks_used'] = $this->last_similarity_analysis['total_chunks_used'] ?? 0;
2241 -}
2242 -// ===== END SIMILARITY DATA CAPTURE =====
2243 -
2244 -// NEW: Add valid URLs to testing data for admin panel display (AFTER similarity data)
2245 -if ($testing_data !== null && !empty($this->current_valid_urls)) {
2246 - $testing_data['approved_urls'] = array_values($this->current_valid_urls);
2247 - //error_log("Added " . count($this->current_valid_urls) . " approved URLs to testing data");
2248 -}
2249 -
2250 - $kb_block = !empty($relevant_content)
2251 - ? "===== OFFICIAL KNOWLEDGE DATABASE CONTENT =====\n" . $relevant_content . "\n===== END OF OFFICIAL KNOWLEDGE DATABASE CONTENT =====\n\n"
2252 - . $this->mxchat_kb_currency_note($relevant_content)
2253 - : "===== NO RELEVANT CONTENT FOUND IN KNOWLEDGE DATABASE =====\n";
2254 -
2255 - // {context} placeholder (plan 59bc1b): when the resolved instructions
2256 - // carry the token, the KB block is injected at that spot by
2257 - // get_system_instructions() (every provider handler re-calls it) and is
2258 - // NOT appended here — otherwise the block would ride twice.
2259 - // $system_instructions above was resolved while context_kb_block was
2260 - // still null, so the literal token is still visible for this check.
2261 - if (!empty($system_instructions) && stripos($system_instructions, '{context}') !== false) {
2262 - $this->context_kb_block = $kb_block;
2263 - } else {
2264 - $context_content .= $kb_block;
2265 - }
2266 -
2267 - // NEW: Add approved URLs list to context for AI (only if citation links enabled)
2268 - if ($citation_links_enabled && !empty($this->current_valid_urls)) {
2269 - $context_content .= "===== APPROVED URLS FOR CITATIONS =====\n";
2270 - $context_content .= "You may ONLY use these exact URLs in your response:\n";
2271 - foreach ($this->current_valid_urls as $url) {
2272 - $context_content .= "- " . $url . "\n";
2273 - }
2274 - $context_content .= "\nCRITICAL: Do NOT create, modify, extend, or invent any other URLs. ";
2275 - $context_content .= "===== END APPROVED URLS =====\n\n";
2276 - }
2277 -
2278 - // Check for and include PDF content
2279 - $pdf_url = get_transient('mxchat_pdf_url_' . $session_id);
2280 - $pdf_embeddings = get_transient('mxchat_pdf_embeddings_' . $session_id);
2281 - $pdf_filename = get_transient('mxchat_pdf_filename_' . $session_id);
2282 - if ($pdf_url && $pdf_embeddings && get_transient('mxchat_include_pdf_in_context_' . $session_id)) {
2283 - $relevant_pdf_pages = $this->find_relevant_pdf_pages($user_message_embedding, $pdf_embeddings);
2284 - if (!empty($relevant_pdf_pages)) {
2285 - $context_content .= "Relevant content from PDF document '{$pdf_filename}':\n";
2286 - foreach ($relevant_pdf_pages as $page_data) {
2287 - $context_content .= "Page {$page_data['page_number']} of '{$pdf_filename}': {$page_data['text']}\n";
2288 - }
2289 - $context_content .= "\n";
2290 - }
2291 - }
2292 -
2293 - // Check for and include Word content
2294 - $word_url = get_transient('mxchat_word_url_' . $session_id);
2295 - $word_embeddings = get_transient('mxchat_word_embeddings_' . $session_id);
2296 - $word_filename = get_transient('mxchat_word_filename_' . $session_id);
2297 - if ($word_url && $word_embeddings && get_transient('mxchat_include_word_in_context_' . $session_id)) {
2298 - $relevant_word_chunks = $this->word_handler->mxchat_find_relevant_word_chunks($user_message_embedding, $word_embeddings);
2299 - if (!empty($relevant_word_chunks)) {
2300 - $context_content .= "Relevant content from Word document '{$word_filename}':\n";
2301 - foreach ($relevant_word_chunks as $chunk_data) {
2302 - $context_content .= "Section {$chunk_data['chunk_number']} of '{$word_filename}': {$chunk_data['text']}\n";
2303 - }
2304 - $context_content .= "\n";
2305 - }
2306 - }
2307 -
2308 - $context_content = apply_filters('mxchat_prepare_context', $context_content, $session_id);
2309 -
2310 - // Extract model from current options for bot-specific model support
2311 - $selected_model = isset($current_options['model']) ? $current_options['model'] : 'gpt-5.6-sol';
2312 -
2313 - // ===== Native function-calling fallback (plan-mxchat-20260617-a41dee) =====
2314 - // Intents already missed (we're past the intent router). If function
2315 - // calling is enabled and the active model is tool-capable, let the model
2316 - // SELECT and run registered callbacks as tools — independent of intents,
2317 - // works with zero Actions. The tool round is buffered; the final answer is
2318 - // emitted via the SAME envelopes the normal path uses. Default-off, so
2319 - // existing installs never enter this branch.
2320 - if ($this->mxchat_fc_should_run($selected_model)) {
2321 - $fc_outcome = $this->mxchat_fc_attempt(
2322 - $message,
2323 - $context_content,
2324 - $conversation_history,
2325 - $selected_model,
2326 - $current_options,
2327 - $session_id,
2328 - $user_id
2329 - );
2330 - if (is_array($fc_outcome) && !empty($fc_outcome['handled'])) {
2331 - $fc_text = isset($fc_outcome['text']) ? $fc_outcome['text'] : '';
2332 - if (!empty($this->current_valid_urls)) {
2333 - $fc_text = $this->validate_and_clean_urls($fc_text, $this->current_valid_urls, $session_id, $bot_id);
2334 - }
2335 - // plan-mxchat-20260617-48a57a — surface any UI element a tool
2336 - // produced (generated image / product card / image gallery) so the
2337 - // widget RENDERS it, instead of emitting only the model's text.
2338 - // The html was already saved to the transcript in
2339 - // mxchat_fc_execute_tool (or by the callback itself for self-saving
2340 - // core tools), so we persist ONLY the model's caption text here.
2341 - $fc_html = isset($this->fc_ui_html) ? $this->fc_ui_html : '';
2342 -
2343 - if ($fc_text !== '') {
2344 - // plan-mxchat-20260813-470f68 — the FC path is the ONLY exit
2345 - // for a tool-answered turn, and it stored no context at all,
2346 - // which is why Message Context was empty exactly when tools
2347 - // fired. Attach the trace here.
2348 - $this->mxchat_save_chat_message($session_id, 'bot', $fc_text, null, $this->mxchat_fc_attach_tool_trace(null));
2349 - }
2350 -
2351 - // A video-backed KB source queued during retrieval (03ba33) must
2352 - // surface on the FC path too — the FC envelopes below are the ONLY
2353 - // exit for this turn, so append it to the html channel and persist
2354 - // it (tool html was already saved in mxchat_fc_execute_tool; the
2355 - // video embed has no other save point on this path).
2356 - if (!empty($this->videoEmbedHtml)) {
2357 - $fc_html .= $this->videoEmbedHtml;
2358 - $this->mxchat_save_chat_message($session_id, 'bot', $this->videoEmbedHtml);
2359 - }
2360 -
2361 - if ($is_streaming) {
2362 - // The frontend SSE reader routes any event carrying text/html
2363 - // to handleNonStreamResponse(), which renders text + html in a
2364 - // single bot message — so emit one complete event (mirrors the
2365 - // intent path's text/html envelope).
2366 - $sse = array('session_id' => $session_id);
2367 - if ($fc_text !== '') $sse['text'] = $fc_text;
2368 - if ($fc_html !== '') $sse['html'] = $fc_html;
2369 - if ($fc_text === '' && $fc_html === '') $sse['text'] = $this->mxchat_fc_giveup_text();
2370 - echo "data: " . wp_json_encode($sse) . "\n\n";
2371 - echo "data: [DONE]\n\n";
2372 - flush();
2373 - } else {
2374 - $fc_response_data = array('text' => $fc_text, 'html' => $fc_html, 'session_id' => $session_id);
2375 - if ($testing_data !== null) {
2376 - $fc_response_data['testing_data'] = $testing_data;
2377 - }
2378 - wp_send_json($fc_response_data);
2379 - }
2380 - wp_die();
2381 - }
2382 - }
2383 - // ===== end function-calling fallback =====
2384 -
2385 - // Streaming + a queued video embed (03ba33): the provider handlers own the
2386 - // token stream and the [DONE] terminator, so the embed rides a dedicated
2387 - // append_html SSE event emitted BEFORE the stream starts. The client
2388 - // stashes it and appends it as its own bot bubble after [DONE] — old
2389 - // cached widget JS simply ignores the unknown key (no content/text/html/
2390 - // error field, so no branch matches). Transcript save happens after the
2391 - // stream completes, so history order matches the live order (text, then
2392 - // embed).
2393 - if ($is_streaming && !empty($this->videoEmbedHtml)) {
2394 - echo "data: " . wp_json_encode(array(
2395 - 'append_html' => $this->videoEmbedHtml,
2396 - 'session_id' => $session_id,
2397 - )) . "\n\n";
2398 - flush();
2399 - }
2400 -
2401 - $response = $this->mxchat_generate_response(
2402 - $context_content,
2403 - $current_options['api_key'] ?? $this->options['api_key'],
2404 - $current_options['xai_api_key'] ?? $this->options['xai_api_key'],
2405 - $current_options['claude_api_key'] ?? $this->options['claude_api_key'],
2406 - $current_options['deepseek_api_key'] ?? $this->options['deepseek_api_key'],
2407 - $current_options['gemini_api_key'] ?? $this->options['gemini_api_key'],
2408 - $current_options['openrouter_api_key'] ?? $this->options['openrouter_api_key'],
2409 - $conversation_history,
2410 - $is_streaming,
2411 - $session_id,
2412 - $testing_data,
2413 - $selected_model
2414 - );
2415 -
2416 - // Handle streaming vs non-streaming responses
2417 - if ($is_streaming) {
2418 - // Check if streaming actually happened or if it fell back to regular response
2419 - if ($response === true) {
2420 - // Persist the video embed AFTER the provider saved the streamed
2421 - // text, so history replays in the same order the visitor saw
2422 - // (text bubble, then embed bubble). See 03ba33.
2423 - if (!empty($this->videoEmbedHtml)) {
2424 - $this->mxchat_save_chat_message($session_id, 'bot', $this->videoEmbedHtml);
2425 - }
2426 - wp_die();
2427 - }
2428 - // If we get here, streaming fell back to regular response, continue
2429 - // But if there's an error, we need to send it as SSE format since headers are already set
2430 - if (is_array($response) && isset($response['error'])) {
2431 - $error_message = $response['error'];
2432 - $error_code = $response['error_code'] ?? 'api_error';
2433 - // Send error in SSE format that the client JS can handle
2434 - echo "data: " . json_encode([
2435 - 'error' => true,
2436 - 'error_message' => $error_message,
2437 - 'error_code' => $error_code,
2438 - 'text' => $error_message, // Also include as text for fallback handling
2439 - 'message' => $error_message
2440 - ]) . "\n\n";
2441 - echo "data: [DONE]\n\n";
2442 - flush();
2443 - wp_die();
2444 - }
2445 - }
2446 -
2447 - // Check if the response is an error array (non-streaming mode)
2448 - if (is_array($response) && isset($response['error'])) {
2449 - wp_send_json_error([
2450 - 'error_message' => $response['error'],
2451 - 'error_code' => $response['error_code'] ?? 'api_error'
2452 - ]);
2453 - wp_die();
2454 - }
2455 -
2456 - // DEBUG: Check what we have
2457 - //error_log("=== BEFORE URL VALIDATION ===");
2458 - //error_log("current_valid_urls is empty? " . (empty($this->current_valid_urls) ? 'YES' : 'NO'));
2459 - //error_log("current_valid_urls count: " . count($this->current_valid_urls));
2460 - //error_log("current_valid_urls content: " . print_r($this->current_valid_urls, true));
2461 -
2462 - // If we get here, the response is valid text - now validate URLs
2463 - if (!empty($this->current_valid_urls)) {
2464 - //error_log("CALLING validate_and_clean_urls");
2465 - $response = $this->validate_and_clean_urls($response, $this->current_valid_urls, $session_id, $bot_id);
2466 - } else {
2467 - //error_log("SKIPPING validation - current_valid_urls is empty");
2468 - }
2469 - // ===== END URL VALIDATION =====
2470 -
2471 - // Prepare RAG context data for storage (only include documents used for context)
2472 - $rag_context_for_storage = null;
2473 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
2474 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
2475 -
2476 - if ($has_rag_data || $has_action_data) {
2477 - $rag_context_for_storage = [];
2478 -
2479 - // Add RAG/source data if available
2480 - if ($has_rag_data) {
2481 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
2482 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
2483 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
2484 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
2485 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
2486 - $rag_context_for_storage['sources_used'] = $this->last_similarity_analysis['sources_used'] ?? 0;
2487 - $rag_context_for_storage['total_chunks_used'] = $this->last_similarity_analysis['total_chunks_used'] ?? 0;
2488 - }
2489 -
2490 - // Add action analysis data if available
2491 - if ($has_action_data) {
2492 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
2493 - }
2494 - }
2495 -
2496 - // Save the cleaned response with RAG context
2497 - $this->mxchat_save_chat_message($session_id, 'bot', $response, null, $this->mxchat_fc_attach_tool_trace($rag_context_for_storage));
2498 -
2499 - // Step 5: Save additional content if available
2500 - if (!empty($this->productCardHtml)) {
2501 - $this->mxchat_save_chat_message($session_id, 'bot', $this->productCardHtml);
2502 - }
2503 -
2504 - if (!empty($this->fallbackResponse['html'])) {
2505 - $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
2506 - }
2507 -
2508 - if (!empty($this->videoEmbedHtml)) {
2509 - $this->mxchat_save_chat_message($session_id, 'bot', $this->videoEmbedHtml);
2510 - }
2511 -
2512 - // Step 6: Return the response
2513 - // DEBUG: Check if newlines exist in the response
2514 - //error_log("=== MXCHAT NON-STREAMING RESPONSE DEBUG ===");
2515 - //error_log("Response has newlines: " . (strpos($response, "\n") !== false ? 'YES' : 'NO'));
2516 - //error_log("Response first 500 chars: " . substr($response, 0, 500));
2517 -
2518 - // Product cards and action html keep their existing either/or precedence;
2519 - // a queued video embed (03ba33) is APPENDED so it can coexist with both.
2520 - $additional_html = !empty($this->productCardHtml) ? $this->productCardHtml : ($this->fallbackResponse['html'] ?? '');
2521 - if (!empty($this->videoEmbedHtml)) {
2522 - $additional_html .= $this->videoEmbedHtml;
2523 - }
2524 -
2525 - $response_data = [
2526 - 'text' => $response,
2527 - 'html' => $additional_html,
2528 - 'session_id' => $session_id
2529 - ];
2530 -
2531 - // Include vectorstore error info for admin debugging (only visible to admins via testing_data)
2532 - if (!empty($this->last_vectorstore_error) && $testing_data !== null) {
2533 - $testing_data['vectorstore_error'] = $this->last_vectorstore_error;
2534 - }
2535 -
2536 - // Also pass it as a top-level field so JS can show a better error message to admins
2537 - if (!empty($this->last_vectorstore_error) && current_user_can('manage_options')) {
2538 - $response_data['vectorstore_error'] = $this->last_vectorstore_error;
2539 - }
2540 -
2541 - // Always add testing data for admins (no toggle needed)
2542 - if ($testing_data !== null) {
2543 - $response_data['testing_data'] = $testing_data;
2544 - }
2545 -
2546 - wp_send_json($response_data);
2547 - wp_die();
2548 -}
2549 -
2550 -/**
2551 - * Tell the model which currency the retrieved product prices are in — but ONLY on the
2552 - * stores where that is ambiguous.
2553 - *
2554 - * Two surfaces quote a price in the same reply and they legitimately disagree:
2555 - *
2556 - * - the PROSE comes from the knowledge base, which since plan 7403ec is pinned to the
2557 - * store's BASE currency and labelled with its ISO code ("Price: INR 1299.00");
2558 - * - the CARD comes from WooCommerce live at render time via get_price_html(), which is
2559 - * the DISPLAY price — a multi-currency plugin converts it to whatever currency the
2560 - * visitor is browsing in.
2561 - *
2562 - * So a shopper browsing an INR-base store in USD can get a card reading $15.59 directly
2563 - * above a sentence reading "it costs INR 1299.00". Both values are correct; together they
2564 - * read as a bug, and the bot has no way of knowing it should not present the base amount
2565 - * as the price this visitor pays. This note is that missing piece (plan eb5f81, option (a)
2566 - * — Maxwell's decision).
2567 - *
2568 - * Deliberately NOT conversion. Converting the indexed price means storing or fetching
2569 - * rates, and a stale rate quoting a wrong price to a shopper is the exact failure class
2570 - * 7403ec existed to remove. The card already does this correctly and live; defer to it.
2571 - *
2572 - * Three gates, cheapest first, and ALL of them must hold — on a single-currency store
2573 - * (the overwhelming majority) and on every non-product answer this returns '' and costs
2574 - * nothing:
2575 - * 1. WooCommerce is active at all;
2576 - * 2. base currency and display currency actually differ (get_woocommerce_currency()
2577 - * applies the 'woocommerce_currency' filter — that IS the hook every multi-currency
2578 - * plugin swaps, so this is the same value the card will be rendered in);
2579 - * 3. the retrieved text actually carries price lines PREFIXED WITH THE BASE CODE.
2580 - *
2581 - * Gate 3 is stricter than "does this look like a product" on purpose. Rows indexed before
2582 - * 7403ec carry a bare symbol and may not be base currency at all — that was the bug — so
2583 - * matching the code keeps this note's claim provably true of the very text it accompanies
2584 - * rather than an assertion about what the importer intended.
2585 - */
2586 -private function mxchat_kb_currency_note($relevant_content) {
2587 - if (!function_exists('get_woocommerce_currency')) {
2588 - return '';
2589 - }
2590 -
2591 - $base = get_option('woocommerce_currency');
2592 - $base = is_string($base) ? trim($base) : '';
2593 - if ($base === '') {
2594 - return '';
2595 - }
2596 -
2597 - $display = get_woocommerce_currency();
2598 - $display = is_string($display) ? trim($display) : '';
2599 - if ($display === '' || $display === $base) {
2600 - return '';
2601 - }
2602 -
2603 - // Matches the shapes mxchat_product_price_lines() emits: "Price:", "Sale Price:" and
2604 - // "Price Range:", each followed by the base currency code.
2605 - //
2606 - // NOT anchored to line start, deliberately. The indexer writes each price on its own
2607 - // line, but the retrieval path reassembles a source's chunks into a SINGLE line —
2608 - // "…test store. Price: INR 1299.00 (₹1299.00) SKU: …" — so a /^…/m anchor matches the
2609 - // stored row and never the text this method is actually handed. The word boundary is
2610 - // what keeps it honest: the code must immediately follow the label, so prose that
2611 - // merely contains the word "Price:" does not qualify.
2612 - $pattern = '/\b(?:Price|Sale Price|Price Range):\s*' . preg_quote($base, '/') . '\b/';
2613 - if (!preg_match($pattern, $relevant_content)) {
2614 - return '';
2615 - }
2616 -
2617 - return "===== PRICE CURRENCY NOTE =====\n"
2618 - . "Any price in the knowledge database content above is recorded in this store's base currency, "
2619 - . $base . ", and is labelled with that code.\n"
2620 - . "This visitor is browsing the store in " . $display . ". If a product card is shown alongside your reply, "
2621 - . "that card displays the price converted to " . $display . " — it, not the knowledge database, is the amount "
2622 - . "this visitor will actually pay.\n"
2623 - . "Therefore: quote knowledge database prices with their currency code (for example \"" . $base . " 1299.00\"), "
2624 - . "and say the product card shows the price in the visitor's own currency. Do NOT convert prices yourself, "
2625 - . "do NOT invent an exchange rate, and do NOT present the " . $base . " amount as though it were the "
2626 - . $display . " price.\n"
2627 - . "===== END PRICE CURRENCY NOTE =====\n\n";
2628 -}
2629 -
2630 -/**
2631 - * Get bot-specific options for multi-bot functionality
2632 - * Falls back to default options if bot_id is 'default' or multi-bot add-on is not active
2633 - */
2634 -// Also debug the bot options retrieval
2635 -private function get_bot_options($bot_id = 'default') {
2636 - //error_log("MXCHAT DEBUG: get_bot_options called for bot: " . $bot_id);
2637 -
2638 - // The admin Testing tab renders the real widget as bot_id "testing", which
2639 - // is not a registered multi-bot. It must resolve the DEFAULT bot's config
2640 - // so the Testing chat behaves exactly like the front-end (same precedent
2641 - // as the Actions enabled_bots check).
2642 - if ($bot_id === 'testing') {
2643 - $bot_id = 'default';
2644 - }
2645 -
2646 - if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
2647 - //error_log("MXCHAT DEBUG: Using default options (no multi-bot or bot is 'default')");
2648 - return array();
2649 - }
2650 -
2651 - $bot_options = apply_filters('mxchat_get_bot_options', array(), $bot_id);
2652 -
2653 - if (!empty($bot_options)) {
2654 - //error_log("MXCHAT DEBUG: Got bot-specific options from filter");
2655 - if (isset($bot_options['similarity_threshold'])) {
2656 - //error_log(" - similarity_threshold: " . $bot_options['similarity_threshold']);
2657 - }
2658 - }
2659 -
2660 - return is_array($bot_options) ? $bot_options : array();
2661 -}
2662 -
2663 -/**
2664 - * Get bot-specific Pinecone configuration
2665 - * Used in the knowledge retrieval functions
2666 - */
2667 -// Also add debugging to your get_bot_pinecone_config function
2668 -private function get_bot_pinecone_config($bot_id = 'default') {
2669 - //error_log("MXCHAT DEBUG: get_bot_pinecone_config called for bot: " . $bot_id);
2670 -
2671 - // Admin Testing tab bot → resolve the DEFAULT bot's backend. Without this,
2672 - // on a multi-bot + Pinecone site the filter below gets an unknown bot id
2673 - // with an EMPTY default, returns array(), and the dispatcher silently
2674 - // searches the WordPress DB while the front-end searches Pinecone — the
2675 - // Testing panel then reports similarity results from a different KB.
2676 - if ($bot_id === 'testing') {
2677 - $bot_id = 'default';
2678 - }
2679 -
2680 - // If default bot or multi-bot add-on not active, use default Pinecone config
2681 - if ($bot_id === 'default' || !class_exists('MxChat_Multi_Bot_Manager')) {
2682 - //error_log("MXCHAT DEBUG: Using default Pinecone config (no multi-bot or bot is 'default')");
2683 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
2684 - $config = array(
2685 - 'use_pinecone' => (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1'),
2686 - 'api_key' => $addon_options['mxchat_pinecone_api_key'] ?? '',
2687 - 'host' => $addon_options['mxchat_pinecone_host'] ?? '',
2688 - 'namespace' => $addon_options['mxchat_pinecone_namespace'] ?? ''
2689 - );
2690 - //error_log("MXCHAT DEBUG: Default config - use_pinecone: " . ($config['use_pinecone'] ? 'true' : 'false'));
2691 - return $config;
2692 - }
2693 -
2694 - //error_log("MXCHAT DEBUG: Calling filter 'mxchat_get_bot_pinecone_config' for bot: " . $bot_id);
2695 -
2696 - // Hook for multi-bot add-on to provide bot-specific Pinecone config
2697 - $bot_pinecone_config = apply_filters('mxchat_get_bot_pinecone_config', array(), $bot_id);
2698 -
2699 - if (!empty($bot_pinecone_config)) {
2700 - //error_log("MXCHAT DEBUG: Got bot-specific config from filter");
2701 - //error_log(" - use_pinecone: " . (isset($bot_pinecone_config['use_pinecone']) ? ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false') : 'not set'));
2702 - //error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'not set'));
2703 - //error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'not set'));
2704 - } else {
2705 - //error_log("MXCHAT DEBUG: Filter returned empty config!");
2706 - }
2707 -
2708 - return is_array($bot_pinecone_config) ? $bot_pinecone_config : array();
2709 -}
2710 -
2711 -
2712 -// Updated function to check intents and invoke the callback function
2713 -private function mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id) {
2714 - global $wpdb;
2715 - $chat_mode = MxChat_Session_Store::get($session_id, 'mode', 'ai');
2716 -
2717 - // Get the current bot_id
2718 - $current_bot_id = $this->get_current_bot_id($session_id);
2719 -
2720 - // Generate the user embedding
2721 - $user_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
2722 -
2723 - // Check if embedding generation returned an error
2724 - if (is_array($user_embedding) && isset($user_embedding['error'])) {
2725 - $error_message = $user_embedding['error'];
2726 - $error_code = $user_embedding['error_code'] ?? 'embedding_error';
2727 -
2728 - // FIXED: Send error in appropriate format based on streaming mode
2729 - if ($this->is_streaming) {
2730 - echo "data: " . json_encode([
2731 - 'error' => true,
2732 - 'error_message' => $error_message,
2733 - 'error_code' => $error_code,
2734 - 'text' => $error_message,
2735 - 'message' => $error_message
2736 - ]) . "\n\n";
2737 - echo "data: [DONE]\n\n";
2738 - flush();
2739 - } else {
2740 - wp_send_json_error([
2741 - 'error_message' => $error_message,
2742 - 'error_code' => $error_code
2743 - ]);
2744 - }
2745 - wp_die();
2746 - }
2747 -
2748 - // Check if embedding is valid
2749 - if (!is_array($user_embedding) || empty($user_embedding)) {
2750 - $error_message = esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat');
2751 -
2752 - // FIXED: Send error in appropriate format based on streaming mode
2753 - if ($this->is_streaming) {
2754 - echo "data: " . json_encode([
2755 - 'error' => true,
2756 - 'error_message' => $error_message,
2757 - 'error_code' => 'invalid_embedding',
2758 - 'text' => $error_message,
2759 - 'message' => $error_message
2760 - ]) . "\n\n";
2761 - echo "data: [DONE]\n\n";
2762 - flush();
2763 - } else {
2764 - wp_send_json_error([
2765 - 'error_message' => $error_message,
2766 - 'error_code' => 'invalid_embedding'
2767 - ]);
2768 - }
2769 - wp_die();
2770 - }
2771 -
2772 - // Fetch intents from the database
2773 - $table_name = $wpdb->prefix . 'mxchat_intents';
2774 - if ($chat_mode === 'agent') {
2775 - $query = $wpdb->prepare(
2776 - "SELECT * FROM $table_name WHERE callback_function = %s AND (enabled = 1 OR enabled IS NULL)",
2777 - 'mxchat_handle_switch_to_chatbot_intent'
2778 - );
2779 - $intents = $wpdb->get_results($query);
2780 - } else {
2781 - $intents = $wpdb->get_results("SELECT * FROM $table_name WHERE enabled = 1 OR enabled IS NULL");
2782 - }
2783 -
2784 - if (empty($intents)) {
2785 - return false;
2786 - }
2787 -
2788 - // Prefetch individual phrase vectors from wp_mxchat_intent_phrases (grouped by intent_id)
2789 - $phrases_table = $wpdb->prefix . 'mxchat_intent_phrases';
2790 - $phrases_by_intent = [];
2791 - if ($wpdb->get_var("SHOW TABLES LIKE '$phrases_table'") === $phrases_table) {
2792 - $all_phrases = $wpdb->get_results("SELECT intent_id, phrase, embedding_vector FROM $phrases_table");
2793 - foreach ($all_phrases as $p) {
2794 - $phrases_by_intent[$p->intent_id][] = $p;
2795 - }
2796 - }
2797 -
2798 - $highest_similarity = -INF;
2799 - $matched_intent = null;
2800 -
2801 - // Array to store action analysis for testing panel
2802 - $action_analysis = [];
2803 -
2804 - foreach ($intents as $intent) {
2805 - // Additional check for enabled state
2806 - $is_enabled = isset($intent->enabled) ? (bool)$intent->enabled : true;
2807 - if (!$is_enabled) {
2808 - continue;
2809 - }
2810 -
2811 - // Check if this action is enabled for the current bot
2812 - if (!$this->is_action_enabled_for_bot($intent, $current_bot_id)) {
2813 - continue;
2814 - }
2815 -
2816 - $best_similarity = -INF;
2817 - $matched_phrase_text = '';
2818 -
2819 - // Check legacy embedding vector (existing behavior)
2820 - $intent_embedding_serialized = $intent->embedding_vector;
2821 - $intent_embedding = $intent_embedding_serialized
2822 - ? unserialize($intent_embedding_serialized, ['allowed_classes' => false])
2823 - : null;
2824 -
2825 - if (is_array($intent_embedding) && !empty($intent_embedding)) {
2826 - $legacy_similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $intent_embedding);
2827 - if ($legacy_similarity > $best_similarity) {
2828 - $best_similarity = $legacy_similarity;
2829 - $matched_phrase_text = 'legacy';
2830 - }
2831 - }
2832 -
2833 - // Check individual phrase vectors
2834 - if (isset($phrases_by_intent[$intent->id])) {
2835 - foreach ($phrases_by_intent[$intent->id] as $phrase_row) {
2836 - $phrase_embedding = $phrase_row->embedding_vector
2837 - ? unserialize($phrase_row->embedding_vector, ['allowed_classes' => false])
2838 - : null;
2839 - if (!is_array($phrase_embedding)) {
2840 - continue;
2841 - }
2842 - $phrase_similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $phrase_embedding);
2843 - if ($phrase_similarity > $best_similarity) {
2844 - $best_similarity = $phrase_similarity;
2845 - $matched_phrase_text = $phrase_row->phrase;
2846 - }
2847 - }
2848 - }
2849 -
2850 - // Skip if no valid embedding was found at all
2851 - if ($best_similarity === -INF) {
2852 - continue;
2853 - }
2854 -
2855 - $similarity = $best_similarity;
2856 - $intent_threshold = isset($intent->similarity_threshold) ? $intent->similarity_threshold : 0.85;
2857 -
2858 - // Store action analysis data for testing panel
2859 - $action_analysis[] = [
2860 - 'intent_label' => $intent->intent_label,
2861 - 'callback_function' => $intent->callback_function,
2862 - 'similarity' => round($similarity, 4),
2863 - 'similarity_percentage' => round($similarity * 100, 2),
2864 - 'threshold' => $intent_threshold,
2865 - 'threshold_percentage' => round($intent_threshold * 100, 2),
2866 - 'above_threshold' => $similarity >= $intent_threshold,
2867 - 'matched_phrase' => $matched_phrase_text,
2868 - 'triggered' => false // Will be updated below if this intent is triggered
2869 - ];
2870 -
2871 - if ($similarity >= $intent_threshold && $similarity > $highest_similarity) {
2872 - $highest_similarity = $similarity;
2873 - $matched_intent = $intent;
2874 - }
2875 - }
2876 -
2877 - // Mark the triggered action if any
2878 - if ($matched_intent) {
2879 - foreach ($action_analysis as &$action) {
2880 - if ($action['intent_label'] === $matched_intent->intent_label) {
2881 - $action['triggered'] = true;
2882 - break;
2883 - }
2884 - }
2885 - }
2886 -
2887 - // Sort actions by similarity (highest first) and store for testing panel
2888 - usort($action_analysis, function($a, $b) {
2889 - return $b['similarity'] <=> $a['similarity'];
2890 - });
2891 -
2892 - // Store action analysis for testing panel capture
2893 - $this->last_action_analysis = $action_analysis;
2894 -
2895 - // Around line 715 in your mxchat_check_intent_and_invoke_callback function
2896 - if ($matched_intent) {
2897 - // If the callback is a method on this instance (core callback), call it directly
2898 - if (method_exists($this, $matched_intent->callback_function)) {
2899 - $callback_result = call_user_func(
2900 - [$this, $matched_intent->callback_function],
2901 - $message,
2902 - $user_id,
2903 - $session_id,
2904 - $matched_intent,
2905 - $user_context ?? null
2906 - );
2907 - } else {
2908 - // Otherwise, use apply_filters for add-on callbacks
2909 - $callback_result = apply_filters(
2910 - $matched_intent->callback_function,
2911 - false,
2912 - $message,
2913 - $user_id,
2914 - $session_id,
2915 - $matched_intent
2916 - );
2917 - }
2918 -
2919 - // Handle the callback result properly
2920 - if ($callback_result !== false) {
2921 - // If callback returned an array with chat_mode, use it directly
2922 - if (is_array($callback_result) && isset($callback_result['chat_mode'])) {
2923 - $this->fallbackResponse = $callback_result;
2924 - return $callback_result; // Return the full array
2925 - } else {
2926 - $this->fallbackResponse = $callback_result;
2927 - return true;
2928 - }
2929 - }
2930 - }
2931 -
2932 - return false;
2933 -}
2934 -
2935 -/**
2936 - * Check if an action is enabled for a specific bot
2937 - */
2938 -private function is_action_enabled_for_bot($intent, $bot_id) {
2939 - // If enabled_bots column doesn't exist or is null, assume it's enabled for all bots (backward compatibility)
2940 - if (!isset($intent->enabled_bots) || empty($intent->enabled_bots)) {
2941 - return true;
2942 - }
2943 -
2944 - $enabled_bots = json_decode($intent->enabled_bots, true);
2945 -
2946 - // If JSON decode fails or returns empty array, assume enabled for all (backward compatibility)
2947 - if (!is_array($enabled_bots) || empty($enabled_bots)) {
2948 - return true;
2949 - }
2950 -
2951 - // Admin testing tab uses bot_id "testing" — treat it as "default" so all
2952 - // default-bot actions are testable from the admin panel
2953 - if ($bot_id === 'testing') {
2954 - $bot_id = 'default';
2955 - }
2956 -
2957 - // Check if the current bot is in the enabled bots list
2958 - return in_array($bot_id, $enabled_bots);
2959 -}
2960 -
2961 -// Helper function to clear PDF and Word document related transients
2962 -private function clear_pdf_transients($session_id) {
2963 - // PDF transients
2964 - delete_transient('mxchat_pdf_url_' . $session_id);
2965 - delete_transient('mxchat_pdf_embeddings_' . $session_id);
2966 - delete_transient('mxchat_include_pdf_in_context_' . $session_id);
2967 - delete_transient('mxchat_waiting_for_pdf_url_' . $session_id);
2968 -
2969 - // Word document transients
2970 - delete_transient('mxchat_word_url_' . $session_id);
2971 - delete_transient('mxchat_word_filename_' . $session_id);
2972 - delete_transient('mxchat_word_embeddings_' . $session_id);
2973 - delete_transient('mxchat_include_word_in_context_' . $session_id);
2974 - delete_transient('mxchat_waiting_for_word_' . $session_id);
2975 -}
2976 -
2977 -
2978 -
2979 -//verified good
2980 -public function mxchat_handle_email_capture($message, $user_id, $session_id) {
2981 - // Get the user's original instruction/message
2982 - $user_instruction = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Please provide your email address.", 'mxchat'));
2983 -
2984 - // Set instruction for AI - just pass along what the user wanted to say
2985 - $this->current_action_instruction = $user_instruction;
2986 -
2987 - // Set the transient to track email capture flow
2988 - set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
2989 -
2990 - // Return false to let the AI generate the response
2991 - return false;
2992 -}
2993 -
2994 -public function mxchat_generate_image($message, $user_id, $session_id) {
2995 - //error_log("Starting image generation for message: " . $message);
2996 -
2997 - // Prepare a prompt for OpenAI image generation
2998 - $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
2999 -
3000 - // Opt-in routing: when 'custom_provider_for_images' is on, route image gen
3001 - // through the configured Custom (OpenAI-compatible) /images/generations route.
3002 - if (!empty($this->options['custom_provider_for_images']) && $this->options['custom_provider_for_images'] === 'on') {
3003 - $image_response = $this->mxchat_generate_custom_image($prompt);
3004 - } else {
3005 - // Use the existing OpenAI API key
3006 - $openai_api_key = sanitize_text_field($this->options['api_key']);
3007 - // Call OpenAI GPT Image to generate an image
3008 - $image_response = $this->mxchat_generate_openai_image($prompt, $openai_api_key);
3009 - }
3010 -
3011 - // Check if the response contains an image URL
3012 - if (isset($image_response['imageUrl'])) {
3013 - $image_url = esc_url_raw($image_response['imageUrl']);
3014 -
3015 - // Construct the HTML with a CSS class instead of inline styles
3016 - $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
3017 - $response_text = esc_html__('Here is the image I generated:', 'mxchat');
3018 -
3019 - // Save the bot message with both text and HTML
3020 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
3021 - $this->mxchat_save_chat_message($session_id, 'bot', $response_html);
3022 -
3023 - // Set the fallback response for the chat handler
3024 - $this->fallbackResponse = [
3025 - 'text' => $response_text,
3026 - 'html' => $response_html,
3027 - 'images' => [$image_url]
3028 - ];
3029 -
3030 - // For debugging/verification - Use json_encode to verify what's being set
3031 - //error_log("Image generation successful - fallbackResponse set: " . json_encode($this->fallbackResponse));
3032 -
3033 - // Return the response directly instead of relying on the property
3034 - return $this->fallbackResponse;
3035 - } else {
3036 - $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
3037 -
3038 - // Save the error message
3039 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
3040 -
3041 - // Set the fallback response for the chat handler
3042 - $this->fallbackResponse = [
3043 - 'text' => $response_text,
3044 - 'html' => '',
3045 - 'images' => []
3046 - ];
3047 -
3048 - //error_log("DALL-E image generation error: " . esc_html($image_response['error'] ?? 'Unknown error.'));
3049 - //error_log("Error fallbackResponse set: " . json_encode($this->fallbackResponse));
3050 -
3051 - // Return the response directly instead of relying on the property
3052 - return $this->fallbackResponse;
3053 - }
3054 -}
3055 -
3056 -public function mxchat_generate_gemini_image($message, $user_id, $session_id) {
3057 - $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
3058 -
3059 - $gemini_api_key = sanitize_text_field($this->options['gemini_api_key'] ?? '');
3060 - if (empty($gemini_api_key)) {
3061 - $response_text = esc_html__("Gemini API key is not configured.", 'mxchat');
3062 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
3063 - return ['text' => $response_text, 'html' => '', 'images' => []];
3064 - }
3065 -
3066 - $image_response = $this->mxchat_generate_imagen_image($prompt, $gemini_api_key);
3067 -
3068 - if (isset($image_response['imageUrl'])) {
3069 - $image_url = esc_url_raw($image_response['imageUrl']);
3070 -
3071 - $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
3072 - $response_text = esc_html__('Here is the image I generated:', 'mxchat');
3073 -
3074 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
3075 - $this->mxchat_save_chat_message($session_id, 'bot', $response_html);
3076 -
3077 - $this->fallbackResponse = [
3078 - 'text' => $response_text,
3079 - 'html' => $response_html,
3080 - 'images' => [$image_url]
3081 - ];
3082 -
3083 - return $this->fallbackResponse;
3084 - } else {
3085 - $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
3086 -
3087 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
3088 -
3089 - $this->fallbackResponse = [
3090 - 'text' => $response_text,
3091 - 'html' => '',
3092 - 'images' => []
3093 - ];
3094 -
3095 - return $this->fallbackResponse;
3096 - }
3097 -}
3098 -
3099 -private function mxchat_save_generated_image($base64_data, $mime_type = 'image/png', $prefix = 'mxchat-generated') {
3100 - // Map the real mime type to a matching file extension so the saved file's
3101 - // extension always agrees with its bytes. A mismatch (e.g. Imagen returning
3102 - // webp bytes that were written into a ".png" file) makes the browser refuse
3103 - // to render the image even though the file saved successfully and the bot
3104 - // reported success — that was the Gemini/Imagen "image never renders" bug.
3105 - // OpenAI + custom-provider paths pass 'image/png' explicitly, so they are
3106 - // unaffected; this only matters for providers that return another type.
3107 - $mime_to_ext = [
3108 - 'image/jpeg' => 'jpg',
3109 - 'image/jpg' => 'jpg',
3110 - 'image/png' => 'png',
3111 - 'image/webp' => 'webp',
3112 - 'image/gif' => 'gif',
3113 - ];
3114 - $mime_type = strtolower(trim((string) $mime_type));
3115 - if (isset($mime_to_ext[$mime_type])) {
3116 - $extension = $mime_to_ext[$mime_type];
3117 - } else {
3118 - // Unknown/unsupported type: fall back to png and normalize the stored
3119 - // mime so the attachment record and the file extension stay consistent.
3120 - $extension = 'png';
3121 - $mime_type = 'image/png';
3122 - }
3123 - $filename = sanitize_file_name($prefix . '-' . wp_generate_uuid4() . '.' . $extension);
3124 - $decoded = base64_decode($base64_data);
3125 -
3126 - if ($decoded === false) {
3127 - return new \WP_Error('decode_failed', esc_html__('Failed to decode image data.', 'mxchat'));
3128 - }
3129 -
3130 - $upload = wp_upload_bits($filename, null, $decoded);
3131 -
3132 - if (!empty($upload['error'])) {
3133 - return new \WP_Error('upload_failed', $upload['error']);
3134 - }
3135 -
3136 - $attach_id = wp_insert_attachment([
3137 - 'post_mime_type' => $mime_type,
3138 - 'post_title' => $prefix,
3139 - 'post_content' => '',
3140 - 'post_status' => 'inherit',
3141 - ], $upload['file']);
3142 -
3143 - if (is_wp_error($attach_id)) {
3144 - return $attach_id;
3145 - }
3146 -
3147 - require_once ABSPATH . 'wp-admin/includes/image.php';
3148 - $metadata = wp_generate_attachment_metadata($attach_id, $upload['file']);
3149 - wp_update_attachment_metadata($attach_id, $metadata);
3150 -
3151 - return esc_url_raw(wp_get_attachment_url($attach_id));
3152 -}
3153 -
3154 -private function mxchat_generate_openai_image($prompt, $api_key, $model = 'gpt-image-1', $timeout = 60) {
3155 - $api_url = 'https://api.openai.com/v1/images/generations';
3156 - $body = json_encode([
3157 - 'prompt' => sanitize_text_field($prompt),
3158 - 'n' => 1,
3159 - 'size' => '1024x1024',
3160 - 'quality' => 'medium',
3161 - 'output_format' => 'png',
3162 - 'model' => sanitize_text_field($model),
3163 - ]);
3164 -
3165 - $args = [
3166 - 'body' => $body,
3167 - 'headers' => [
3168 - 'Content-Type' => 'application/json',
3169 - 'Authorization' => 'Bearer ' . sanitize_text_field($api_key),
3170 - ],
3171 - 'method' => 'POST',
3172 - 'timeout' => absint($timeout),
3173 - ];
3174 -
3175 - $response = wp_remote_post($api_url, $args);
3176 -
3177 - if (is_wp_error($response)) {
3178 - return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
3179 - }
3180 -
3181 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3182 -
3183 - $b64 = $response_body['data'][0]['b64_json'] ?? $response_body['data'][0]['b64'] ?? null;
3184 - if ($b64) {
3185 - $saved_url = $this->mxchat_save_generated_image($b64, 'image/png', 'mxchat-openai');
3186 - if (is_wp_error($saved_url)) {
3187 - return ['error' => $saved_url->get_error_message()];
3188 - }
3189 - return ['imageUrl' => $saved_url];
3190 - } else {
3191 - return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
3192 - }
3193 -}
3194 -
3195 -/**
3196 - * Generate an image via a Custom (OpenAI-compatible) provider's /images/generations route.
3197 - * Only called when the opt-in 'custom_provider_for_images' setting is on.
3198 - */
3199 -private function mxchat_generate_custom_image($prompt, $timeout = 90) {
3200 - $cfg = $this->mxchat_resolve_custom_provider();
3201 - if (empty($cfg['base_url'])) {
3202 - return ['error' => esc_html__('Custom provider Base URL is not configured.', 'mxchat')];
3203 - }
3204 - $url = $cfg['base_url'] . '/images/generations';
3205 - if (!empty($cfg['api_version'])) {
3206 - $url .= (strpos($url, '?') === false ? '?' : '&') . 'api-version=' . rawurlencode($cfg['api_version']);
3207 - }
3208 - $body = wp_json_encode([
3209 - 'prompt' => sanitize_text_field($prompt),
3210 - 'n' => 1,
3211 - 'size' => '1024x1024',
3212 - 'model' => $cfg['model'],
3213 - ]);
3214 - $response = wp_remote_post($url, [
3215 - 'headers' => $this->mxchat_custom_provider_assoc_headers($cfg),
3216 - 'body' => $body,
3217 - 'method' => 'POST',
3218 - 'timeout' => absint($timeout),
3219 - ]);
3220 - if (is_wp_error($response)) {
3221 - return ['error' => esc_html__('Error generating image (custom provider): ', 'mxchat') . $response->get_error_message()];
3222 - }
3223 - $resp = json_decode(wp_remote_retrieve_body($response), true);
3224 - // Try b64 first (matches OpenAI shape), then url-based fallback.
3225 - $b64 = $resp['data'][0]['b64_json'] ?? $resp['data'][0]['b64'] ?? null;
3226 - if ($b64) {
3227 - $saved = $this->mxchat_save_generated_image($b64, 'image/png', 'mxchat-custom');
3228 - if (is_wp_error($saved)) {
3229 - return ['error' => $saved->get_error_message()];
3230 - }
3231 - return ['imageUrl' => $saved];
3232 - }
3233 - $remote_url = $resp['data'][0]['url'] ?? null;
3234 - if ($remote_url) {
3235 - return ['imageUrl' => esc_url_raw($remote_url)];
3236 - }
3237 - $err_msg = $this->extract_provider_error($resp, esc_html__('Custom provider did not return an image.', 'mxchat'));
3238 - return ['error' => esc_html($err_msg)];
3239 -}
3240 -
3241 -private function mxchat_generate_imagen_image($prompt, $api_key, $timeout = 60) {
3242 - $api_url = 'https://generativelanguage.googleapis.com/v1beta/models/imagen-4.0-generate-001:predict';
3243 -
3244 - $body = json_encode([
3245 - 'instances' => [['prompt' => sanitize_text_field($prompt)]],
3246 - 'parameters' => [
3247 - 'sampleCount' => 1,
3248 - 'aspectRatio' => '1:1',
3249 - ],
3250 - ]);
3251 -
3252 - $args = [
3253 - 'body' => $body,
3254 - 'headers' => [
3255 - 'Content-Type' => 'application/json',
3256 - 'x-goog-api-key' => sanitize_text_field($api_key),
3257 - ],
3258 - 'method' => 'POST',
3259 - 'timeout' => absint($timeout),
3260 - ];
3261 -
3262 - $response = wp_remote_post($api_url, $args);
3263 -
3264 - if (is_wp_error($response)) {
3265 - return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
3266 - }
3267 -
3268 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
3269 -
3270 - $b64 = $response_body['predictions'][0]['bytesBase64Encoded'] ?? $response_body['predictions'][0]['imageBytes'] ?? null;
3271 - if ($b64) {
3272 - $mime = $response_body['predictions'][0]['mimeType'] ?? 'image/png';
3273 - $saved_url = $this->mxchat_save_generated_image($b64, $mime, 'mxchat-gemini');
3274 - if (is_wp_error($saved_url)) {
3275 - return ['error' => $saved_url->get_error_message()];
3276 - }
3277 - return ['imageUrl' => $saved_url];
3278 - } else {
3279 - return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
3280 - }
3281 -}
3282 -
3283 -/**
3284 - * Handle web search requests.
3285 - *
3286 - * Sends the refined search query to the Brave Search API and uses the
3287 - * results to generate a conversational response with the AI model.
3288 - *
3289 - * @since 1.0.0
3290 - * @param string $message The user's search query.
3291 - * @param string $user_id The user identifier.
3292 - * @param string $session_id The current session ID.
3293 - * @return array Response array containing text with embedded HTML links
3294 - */
3295 -public function mxchat_handle_search_request($message, $user_id, $session_id) {
3296 - // Step 1: Interpret and refine the search query
3297 - $refined_search_query = $this->mxchat_interpret_search_query($message);
3298 - if (empty($refined_search_query)) {
3299 - return array(
3300 - 'text' => esc_html__('I apologize, but could you please rephrase your search request?', 'mxchat'),
3301 - 'html' => ''
3302 - );
3303 - }
3304 -
3305 - // Retrieve and validate API settings
3306 - $options = get_option('mxchat_options');
3307 - $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
3308 - $results_count = isset($options['brave_results_count']) ? absint($options['brave_results_count']) : 5;
3309 -
3310 - if (empty($api_key)) {
3311 - return array(
3312 - 'text' => esc_html__('Search functionality is temporarily unavailable. Please try again later.', 'mxchat'),
3313 - 'html' => ''
3314 - );
3315 - }
3316 -
3317 - // Build the API request URL
3318 - $api_url = add_query_arg(
3319 - array(
3320 - 'q' => rawurlencode($refined_search_query),
3321 - 'count' => $results_count,
3322 - 'text_decorations' => 'true',
3323 - 'rich_data' => 'true',
3324 - ),
3325 - 'https://api.search.brave.com/res/v1/web/search'
3326 - );
3327 -
3328 - // Attempt to retrieve cached results first
3329 - $transient_key = 'mxchat_search_' . md5($refined_search_query);
3330 - $results = get_transient($transient_key);
3331 -
3332 - if (false === $results) {
3333 - // SECURITY FIX: Changed to wp_safe_remote_get
3334 - $response = wp_safe_remote_get(
3335 - $api_url,
3336 - array(
3337 - 'headers' => array(
3338 - 'Accept' => 'application/json',
3339 - 'Accept-Encoding' => 'gzip',
3340 - 'X-Subscription-Token'=> $api_key,
3341 - ),
3342 - 'timeout' => 10,
3343 - )
3344 - );
3345 -
3346 - if (is_wp_error($response)) {
3347 - return array(
3348 - 'text' => esc_html__('I encountered an error while searching. Please try again.', 'mxchat'),
3349 - 'html' => ''
3350 - );
3351 - }
3352 -
3353 - $results = json_decode(wp_remote_retrieve_body($response), true);
3354 -
3355 - if (json_last_error() !== JSON_ERROR_NONE) {
3356 - return array(
3357 - 'text' => esc_html__('I received an invalid response from the search service.', 'mxchat'),
3358 - 'html' => ''
3359 - );
3360 - }
3361 -
3362 - // Cache results for one hour
3363 - set_transient($transient_key, $results, HOUR_IN_SECONDS);
3364 - }
3365 -
3366 - // Process results
3367 - if (!empty($results['web']['results']) && is_array($results['web']['results'])) {
3368 - // Create a more straightforward summary with HTML links
3369 - $search_results_text = '';
3370 -
3371 - // Add a simple intro
3372 - $search_results_text .= sprintf(
3373 - esc_html__("Here's what I found about '%s':", 'mxchat'),
3374 - esc_html($refined_search_query)
3375 - );
3376 -
3377 - // Add the top results with HTML links
3378 - foreach (array_slice($results['web']['results'], 0, 5) as $result) {
3379 - $title = isset($result['title']) ? wp_strip_all_tags($result['title']) : '';
3380 - $url = isset($result['url']) ? esc_url($result['url']) : '';
3381 - $description = isset($result['description']) ? wp_strip_all_tags($result['description']) : '';
3382 -
3383 - // Add a line break after the intro
3384 - $search_results_text .= '<br><br>';
3385 -
3386 - // Add title as a link
3387 - $search_results_text .= sprintf(
3388 - '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a><br>',
3389 - $url,
3390 - $title
3391 - );
3392 -
3393 - // Add a condensed description
3394 - $search_results_text .= sprintf("%s", $description);
3395 - }
3396 -
3397 - // Save to chat history
3398 - $this->mxchat_save_chat_message($session_id, 'bot', $search_results_text);
3399 -
3400 - // Return the formatted text with embedded HTML links
3401 - return array(
3402 - 'text' => $search_results_text,
3403 - 'html' => ''
3404 - );
3405 - } else {
3406 - return array(
3407 - 'text' => sprintf(
3408 - esc_html__('I searched for "%s" but couldn\'t find any relevant results. Would you like to try different search terms?', 'mxchat'),
3409 - esc_html($refined_search_query)
3410 - ),
3411 - 'html' => ''
3412 - );
3413 - }
3414 -}
3415 -
3416 -//very good
3417 -/**
3418 - * Handle image search requests from the chatbot
3419 - *
3420 - * @param string $message The user's search query
3421 - * @param int $user_id The user's ID
3422 - * @param string $session_id The chat session ID
3423 - * @return array Response array with text and HTML content
3424 - */
3425 -public function mxchat_handle_image_search_request($message, $user_id, $session_id) {
3426 - // Step 1: Interpret the search query using the user's selected AI model
3427 - $refined_search_query = $this->mxchat_interpret_search_query($message);
3428 -
3429 - // If no query was interpreted, return a fallback message
3430 - if (empty($refined_search_query)) {
3431 - return array(
3432 - 'text' => __("I'm sorry, I couldn't interpret your search query. Please specify what you'd like to see images of.", 'mxchat'),
3433 - 'html' => "",
3434 - );
3435 - }
3436 -
3437 - // Brave API URL
3438 - $api_url = 'https://api.search.brave.com/res/v1/images/search';
3439 -
3440 - // Retrieve Brave API settings
3441 - $options = get_option('mxchat_options');
3442 - $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
3443 -
3444 - if (empty($api_key)) {
3445 - return array(
3446 - 'text' => __("API key is not configured. Please set it in the Brave Search Settings.", 'mxchat'),
3447 - 'html' => "",
3448 - );
3449 - }
3450 -
3451 - $image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
3452 - $safe_search = isset($options['brave_safe_search']) ? sanitize_text_field($options['brave_safe_search']) : 'strict';
3453 -
3454 - // Append query parameters based on settings
3455 - $api_url = add_query_arg([
3456 - 'q' => rawurlencode($refined_search_query),
3457 - 'count' => $image_count,
3458 - 'safesearch' => $safe_search,
3459 - ], $api_url);
3460 -
3461 - // Implement caching
3462 - $transient_key = 'mxchat_image_search_' . md5($refined_search_query);
3463 - $body = get_transient($transient_key);
3464 -
3465 - if (false === $body) {
3466 - $args = [
3467 - 'headers' => [
3468 - 'Accept' => 'application/json',
3469 - 'Accept-Encoding' => 'gzip',
3470 - 'X-Subscription-Token' => $api_key,
3471 - ],
3472 - 'timeout' => 10,
3473 - ];
3474 -
3475 - // SECURITY FIX: Changed to wp_safe_remote_get
3476 - $response = wp_safe_remote_get($api_url, $args);
3477 -
3478 - if (is_wp_error($response)) {
3479 - return array(
3480 - 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
3481 - 'html' => "",
3482 - );
3483 - }
3484 -
3485 - $body = json_decode(wp_remote_retrieve_body($response), true);
3486 - set_transient($transient_key, $body, HOUR_IN_SECONDS);
3487 - }
3488 -
3489 - // Process the API response
3490 - if (isset($body['results']) && is_array($body['results']) && count($body['results']) > 0) {
3491 - $html_output = '<div class="mxchat-image-gallery">';
3492 -
3493 - // Get the configured image count (1-6)
3494 - $display_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
3495 - $display_count = min($display_count, count($body['results'])); // Make sure we don't exceed available images
3496 -
3497 - // Use only the requested number of images
3498 - for ($i = 0; $i < $display_count; $i++) {
3499 - $image = $body['results'][$i];
3500 - $image_url = isset($image['url']) ? esc_url($image['url']) : '';
3501 - $thumbnail_url = isset($image['thumbnail']['src']) ? esc_url($image['thumbnail']['src']) : '';
3502 - $title = isset($image['title']) ? esc_html($image['title']) : esc_html__('Image', 'mxchat');
3503 -
3504 - if ($image_url && $thumbnail_url) {
3505 - $html_output .= '<div class="mxchat-image-item">';
3506 - $html_output .= '<strong class="mxchat-image-title">' . $title . '</strong>';
3507 - $html_output .= '<a href="' . $image_url . '" target="_blank" rel="noopener noreferrer" class="mxchat-image-link">';
3508 - $html_output .= '<img src="' . $thumbnail_url . '" alt="' . $title . '" class="mxchat-image-thumbnail">';
3509 - $html_output .= '</a></div>';
3510 - }
3511 - }
3512 -
3513 - $html_output .= '</div>';
3514 -
3515 - // Create response text
3516 - $response_text = sprintf(__("Here are some images of %s:", 'mxchat'), $refined_search_query);
3517 -
3518 - // Save both response text and HTML to chat history
3519 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
3520 - $this->mxchat_save_chat_message($session_id, 'bot', $html_output);
3521 -
3522 - // Return the combined response
3523 - return array(
3524 - 'text' => $response_text,
3525 - 'html' => $html_output,
3526 - );
3527 - } else {
3528 - $response_text = __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat');
3529 -
3530 - // Save the error message to chat history
3531 - $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
3532 -
3533 - return array(
3534 - 'text' => $response_text,
3535 - 'html' => "",
3536 - );
3537 - }
3538 -}
3539 -
3540 -/**
3541 - * Interpret the search query using the user's selected AI model
3542 - *
3543 - * @param string $user_query The original query from the user
3544 - * @return string The refined search query
3545 - */
3546 -public function mxchat_interpret_search_query($user_query) {
3547 - $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');
3548 -
3549 - // Get options and determine the selected model
3550 - $options = $this->options ?? get_option('mxchat_options');
3551 - $selected_model = isset($options['model']) ? $options['model'] : 'gpt-5.6-sol';
3552 -
3553 - // Custom (OpenAI-compatible) provider routes by model id, not prefix.
3554 - if ($selected_model === 'custom-provider') {
3555 - return $this->interpret_query_with_custom($user_query, $system_prompt);
3556 - }
3557 -
3558 - // Extract model prefix to determine the provider
3559 - $model_parts = explode('-', $selected_model);
3560 - $provider = strtolower($model_parts[0]);
3561 -
3562 - // Determine which API key to use based on the provider
3563 - switch ($provider) {
3564 - case 'gemini':
3565 - $api_key = isset($options['gemini_api_key']) ? sanitize_text_field($options['gemini_api_key']) : '';
3566 - if (empty($api_key)) {
3567 - return sanitize_text_field($user_query); // Default to original query if API key missing
3568 - }
3569 - return $this->interpret_query_with_gemini($user_query, $system_prompt, $api_key, $selected_model);
3570 -
3571 - case 'claude':
3572 - $api_key = isset($options['claude_api_key']) ? sanitize_text_field($options['claude_api_key']) : '';
3573 - if (empty($api_key)) {
3574 - return sanitize_text_field($user_query);
3575 - }
3576 - return $this->interpret_query_with_claude($user_query, $system_prompt, $api_key, $selected_model);
3577 -
3578 - case 'grok':
3579 - $api_key = isset($options['xai_api_key']) ? sanitize_text_field($options['xai_api_key']) : '';
3580 - if (empty($api_key)) {
3581 - return sanitize_text_field($user_query);
3582 - }
3583 - return $this->interpret_query_with_xai($user_query, $system_prompt, $api_key, $selected_model);
3584 -
3585 - case 'deepseek':
3586 - $api_key = isset($options['deepseek_api_key']) ? sanitize_text_field($options['deepseek_api_key']) : '';
3587 - if (empty($api_key)) {
3588 - return sanitize_text_field($user_query);
3589 - }
3590 - return $this->interpret_query_with_deepseek($user_query, $system_prompt, $api_key, $selected_model);
3591 -
3592 - case 'gpt':
3593 - default:
3594 - // Default to OpenAI for custom models or unrecognized prefixes
3595 - $api_key = isset($options['api_key']) ? sanitize_text_field($options['api_key']) : '';
3596 - if (empty($api_key)) {
3597 - return sanitize_text_field($user_query);
3598 - }
3599 - return $this->interpret_query_with_openai($user_query, $system_prompt, $api_key, $selected_model);
3600 - }
3601 -}
3602 -
3603 -/**
3604 - * Interpret query against the configured Custom (OpenAI-compatible) provider.
3605 - * Uses the same base URL + auth scheme as the chat dispatcher.
3606 - */
3607 -private function interpret_query_with_custom($user_query, $system_prompt) {
3608 - $cfg = $this->mxchat_resolve_custom_provider();
3609 - if (empty($cfg['base_url'])) {
3610 - return sanitize_text_field($user_query);
3611 - }
3612 - // plan-mxchat-20260715-7124f4: a custom OpenAI-compatible endpoint pointed at
3613 - // a gpt-5-class model rejects temperature!=1 and the legacy max_tokens key.
3614 - // Byte-identical for ordinary custom models (temperature kept, max_tokens
3615 - // used); only gpt-5-class custom models change (best-effort — custom
3616 - // endpoints vary).
3617 - $token_key = $this->mxchat_openai_token_param_for($cfg['model']);
3618 - $payload = [
3619 - 'model' => $cfg['model'],
3620 - 'messages' => [
3621 - ['role' => 'system', 'content' => $system_prompt],
3622 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
3623 - ],
3624 - $token_key => 20,
3625 - ];
3626 - if ($this->mxchat_openai_supports_temperature_for($cfg['model'])) {
3627 - $payload['temperature'] = 0.2;
3628 - }
3629 - $args = [
3630 - 'headers' => $this->mxchat_custom_provider_assoc_headers($cfg),
3631 - 'body' => wp_json_encode($payload),
3632 - 'method' => 'POST',
3633 - 'timeout' => 15,
3634 - ];
3635 - $response = wp_remote_post($cfg['chat_url'], $args);
3636 - if (is_wp_error($response)) {
3637 - return sanitize_text_field($user_query);
3638 - }
3639 - $body = json_decode(wp_remote_retrieve_body($response), true);
3640 - return isset($body['choices'][0]['message']['content'])
3641 - ? sanitize_text_field(trim($body['choices'][0]['message']['content']))
3642 - : sanitize_text_field($user_query);
3643 -}
3644 -
3645 -/**
3646 - * Convert the colon-style header list returned by mxchat_resolve_custom_provider
3647 - * into the assoc-array form wp_remote_post expects.
3648 - */
3649 -private function mxchat_custom_provider_assoc_headers($cfg) {
3650 - $headers = ['Content-Type' => 'application/json'];
3651 - if (!empty($cfg['api_key'])) {
3652 - if (($cfg['auth_scheme'] ?? 'bearer') === 'api-key') {
3653 - $headers['api-key'] = $cfg['api_key'];
3654 - } else {
3655 - $headers['Authorization'] = 'Bearer ' . $cfg['api_key'];
3656 - }
3657 - }
3658 - return $headers;
3659 -}
3660 -
3661 -/**
3662 - * Interpret query using OpenAI models
3663 - */
3664 -private function interpret_query_with_openai($user_query, $system_prompt, $api_key, $model = 'gpt-5.6-sol') {
3665 - $url = 'https://api.openai.com/v1/chat/completions';
3666 - // plan-mxchat-20260715-7124f4: the default chat model is a gpt-5-family id
3667 - // and every gpt-5* rejects both a non-default temperature and the legacy
3668 - // max_tokens key (400). This call swallowed the 400 and silently degraded to
3669 - // the raw query on every gpt-5 install, quietly disabling product/image
3670 - // search-query interpretation. Derive capability from the core catalog
3671 - // (dcb71c) so this tracks future model adds; strpos fallback for a
3672 - // partial-upgrade window where the catalog method isn't loaded.
3673 - $token_key = $this->mxchat_openai_token_param_for($model);
3674 - $payload = [
3675 - 'model' => $model,
3676 - 'messages' => [
3677 - ['role' => 'system', 'content' => $system_prompt],
3678 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
3679 - ],
3680 - $token_key => 20,
3681 - ];
3682 - if ($this->mxchat_openai_supports_temperature_for($model)) {
3683 - $payload['temperature'] = 0.2;
3684 - }
3685 - $args = [
3686 - 'headers' => [
3687 - 'Authorization' => 'Bearer ' . $api_key,
3688 - 'Content-Type' => 'application/json',
3689 - ],
3690 - 'body' => wp_json_encode($payload),
3691 - 'method' => 'POST',
3692 - 'timeout' => 15,
3693 - ];
3694 -
3695 - $response = wp_remote_post($url, $args);
3696 - if (is_wp_error($response)) {
3697 - return sanitize_text_field($user_query);
3698 - }
3699 -
3700 - $body = json_decode(wp_remote_retrieve_body($response), true);
3701 - return isset($body['choices'][0]['message']['content'])
3702 - ? sanitize_text_field(trim($body['choices'][0]['message']['content']))
3703 - : sanitize_text_field($user_query);
3704 -}
3705 -
3706 -/**
3707 - * Anthropic removed temperature/top_p/top_k starting with Opus 4.7 (the API
3708 - * returns 400 if sent) — add new flagship model ids here. (We don't send
3709 - * top_p/top_k in any Claude body, so the list only needs to gate temperature
3710 - * stripping. We never send a `thinking` param either, which is required for
3711 - * claude-fable-5: it rejects an explicit thinking "disabled" — omit only.)
3712 - */
3713 -private function mxchat_claude_omits_temperature($model) {
3714 - // plan-mxchat-20260714-dcb71c: derive from the core model catalog (single
3715 - // source of truth). Every caller here passes a Claude model, so
3716 - // !supports_temperature() reproduces the old 4-id in_array() result exactly.
3717 - // Frozen list kept as fallback for a partial-upgrade window where the
3718 - // catalog method isn't loaded.
3719 - if (class_exists('MxChat_Model_Catalog') && method_exists('MxChat_Model_Catalog', 'supports_temperature')) {
3720 - return !MxChat_Model_Catalog::supports_temperature($model);
3721 - }
3722 - $no_temp = array('claude-opus-5', 'claude-opus-4-7', 'claude-opus-4-8', 'claude-fable-5', 'claude-sonnet-5');
3723 - return in_array($model, $no_temp, true);
3724 -}
3725 -
3726 -/**
3727 - * plan-mxchat-20260715-7124f4: OpenAI completion-token key for this model,
3728 - * sourced from the core catalog (gpt-5* → max_completion_tokens; else
3729 - * max_tokens). strpos fallback for a partial-upgrade window where the catalog
3730 - * method isn't loaded.
3731 - *
3732 - * @param string $model OpenAI(-compatible) model id.
3733 - * @return string 'max_completion_tokens' | 'max_tokens'
3734 - */
3735 -private function mxchat_openai_token_param_for($model) {
3736 - if (class_exists('MxChat_Model_Catalog') && method_exists('MxChat_Model_Catalog', 'openai_token_param')) {
3737 - return MxChat_Model_Catalog::openai_token_param($model);
3738 - }
3739 - return strpos((string) $model, 'gpt-5') === 0 ? 'max_completion_tokens' : 'max_tokens';
3740 -}
3741 -
3742 -/**
3743 - * plan-mxchat-20260715-7124f4: whether a NON-default temperature may be sent to
3744 - * this OpenAI(-compatible) model. gpt-5* accept only the default (1) — sending
3745 - * any other value 400s. Sourced from the core catalog; strpos fallback for a
3746 - * partial-upgrade window.
3747 - *
3748 - * @param string $model OpenAI(-compatible) model id.
3749 - * @return bool
3750 - */
3751 -private function mxchat_openai_supports_temperature_for($model) {
3752 - if (class_exists('MxChat_Model_Catalog') && method_exists('MxChat_Model_Catalog', 'supports_temperature')) {
3753 - return MxChat_Model_Catalog::supports_temperature($model);
3754 - }
3755 - return strpos((string) $model, 'gpt-5') !== 0;
3756 -}
3757 -
3758 -/**
3759 - * plan-mxchat-20260714-dcb71c: per-surface reasoning_effort, sourced from the
3760 - * core model catalog so a model add propagates automatically. The fallback is
3761 - * the frozen pre-dcb71c inline ladder, used only if the catalog method is
3762 - * unavailable (a partial-upgrade window). Byte-identical to the old inline
3763 - * blocks by construction — proven by the dcb71c equivalence harness.
3764 - *
3765 - * @param string $model Chat model id.
3766 - * @param string $context 'chat' | 'websearch'.
3767 - * @return string|null Effort to send, or null to omit the param.
3768 - */
3769 -private function mxchat_reasoning_effort_for($model, $context) {
3770 - if (class_exists('MxChat_Model_Catalog') && method_exists('MxChat_Model_Catalog', 'reasoning_effort_for')) {
3771 - return MxChat_Model_Catalog::reasoning_effort_for($model, $context);
3772 - }
3773 - return $this->mxchat_reasoning_effort_fallback($model, $context);
3774 -}
3775 -
3776 -private function mxchat_reasoning_effort_fallback($model, $context) {
3777 - if (strpos($model, 'gpt-5') !== 0) {
3778 - return null;
3779 - }
3780 - if ($context === 'websearch') {
3781 - $no_reasoning_web = array('gpt-5.2', 'gpt-5.3-chat-latest', 'gpt-5.4-mini', 'gpt-5.4-nano');
3782 - if (in_array($model, $no_reasoning_web, true)) return null;
3783 - if ($model === 'gpt-5.1-2025-11-13') return 'low';
3784 - if ($model === 'gpt-5.5') return 'low';
3785 - if ($model === 'gpt-5.4') return 'low';
3786 - if (in_array($model, array('gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'), true)) return 'low';
3787 - return null;
3788 - }
3789 - // 'chat'
3790 - // gpt-5.1/5.3-chat-latest stay listed after their 2026-08-10 retirement:
3791 - // unmigrated bot-level / add-on-saved ids must keep routing correctly
3792 - // until every surface is swept (plan e46b8f).
3793 - $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');
3794 - if (in_array($model, $no_reasoning_models, true)) return null;
3795 - if ($model === 'gpt-5.1-2025-11-13') return 'low';
3796 - if ($model === 'gpt-5.5') return 'none';
3797 - if ($model === 'gpt-5.4') return 'none';
3798 - if (in_array($model, array('gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna'), true)) return 'low';
3799 - return 'minimal';
3800 -}
3801 -
3802 -/**
3803 - * plan-mxchat-20260813-25b972: does this non-200 provider response reject the
3804 - * reasoning_effort VALUE we sent? Supported values are per-model (some
3805 - * generations take 'minimal', newer ones bottom out at 'none'), so a stale
3806 - * catalog entry manifests as this specific 400. Callers strip the param and
3807 - * retry ONCE — value-support drift degrades to one wasted round-trip instead
3808 - * of a hard outage.
3809 - *
3810 - * @param int $status HTTP status of the failed attempt.
3811 - * @param string $body Raw response body (error JSON).
3812 - * @return bool
3813 - */
3814 -private function mxchat_is_reasoning_effort_rejection($status, $body) {
3815 - if ((int) $status !== 400 || !is_string($body) || $body === '') {
3816 - return false;
3817 - }
3818 - $decoded = json_decode($body, true);
3819 - $msg = isset($decoded['error']['message']) && is_string($decoded['error']['message'])
3820 - ? $decoded['error']['message']
3821 - : '';
3822 - return $msg !== '' && preg_match('/Unsupported value:.*reasoning_effort/i', $msg) === 1;
3823 -}
3824 -
3825 -/**
3826 - * Wrap a system prompt as Anthropic content blocks with a prompt-cache
3827 - * breakpoint on the last block (plan 1ff43b). Cache reads bill at 0.1x base
3828 - * input; the 5-minute write costs 1.25x, so a prefix reused once already pays
3829 - * for itself — and the system prompt is ~47% of billed input on a typical
3830 - * install. The breakpoint is SKIPPED when the owner's prompt embeds the
3831 - * per-query {context} KB block (context_kb_block non-null): that prefix
3832 - * changes every message, and paying the write premium on a never-reused
3833 - * prefix is a net loss. Below the model's minimum cacheable prefix the API
3834 - * silently ignores the marker — no error, no surcharge.
3835 - */
3836 -private function mxchat_anthropic_system_blocks($system_prompt) {
3837 - $system_prompt = (string) $system_prompt;
3838 - if (trim($system_prompt) === '') {
3839 - // Preserve legacy behavior for empty prompts — an empty text BLOCK
3840 - // would be rejected by the API where an empty string is tolerated.
3841 - return $system_prompt;
3842 - }
3843 - $block = array('type' => 'text', 'text' => $system_prompt);
3844 - if ($this->context_kb_block === null) {
3845 - $block['cache_control'] = array('type' => 'ephemeral');
3846 - }
3847 - return array($block);
3848 -}
3849 -
3850 -/**
3851 - * Interpret query using Claude models
3852 - */
3853 -private function interpret_query_with_claude($user_query, $system_prompt, $api_key, $model) {
3854 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
3855 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
3856 - if ($model === 'claude-opus-4-20250514') { $model = 'claude-opus-4-8'; }
3857 - elseif ($model === 'claude-sonnet-4-20250514') { $model = 'claude-sonnet-4-6'; }
3858 - $url = 'https://api.anthropic.com/v1/messages';
3859 -
3860 - $payload = [
3861 - 'model' => $model,
3862 - 'system' => $this->mxchat_anthropic_system_blocks($system_prompt),
3863 - 'messages' => [
3864 - ['role' => 'user', 'content' => sanitize_text_field($user_query)]
3865 - ],
3866 - 'max_tokens' => 20,
3867 - 'temperature' => 0.2,
3868 - ];
3869 - if ($this->mxchat_claude_omits_temperature($model)) { unset($payload['temperature']); }
3870 -
3871 - $args = [
3872 - 'headers' => [
3873 - 'Content-Type' => 'application/json',
3874 - 'x-api-key' => $api_key,
3875 - 'anthropic-version' => '2023-06-01',
3876 - ],
3877 - 'body' => wp_json_encode($payload),
3878 - 'method' => 'POST',
3879 - 'timeout' => 15,
3880 - ];
3881 -
3882 - $response = wp_remote_post($url, $args);
3883 - if (is_wp_error($response)) {
3884 - return sanitize_text_field($user_query);
3885 - }
3886 -
3887 - $body = json_decode(wp_remote_retrieve_body($response), true);
3888 - // claude-fable-5 prepends a thinking block to content — take the first
3889 - // TEXT block, not content[0].
3890 - foreach ((array) ($body['content'] ?? array()) as $block) {
3891 - if (isset($block['type'], $block['text']) && $block['type'] === 'text' && trim($block['text']) !== '') {
3892 - return sanitize_text_field(trim($block['text']));
3893 - }
3894 - }
3895 -
3896 - return sanitize_text_field($user_query);
3897 -}
3898 -
3899 -/**
3900 - * Interpret query using Gemini models
3901 - */
3902 -private function interpret_query_with_gemini($user_query, $system_prompt, $api_key, $model) {
3903 - if ($model === 'gemini-3-pro-preview') {
3904 - $model = 'gemini-3.1-pro-preview';
3905 - }
3906 - // Use v1beta for preview models, v1 for stable models
3907 - $api_version = (strpos($model, 'preview') !== false || strpos($model, 'exp') !== false) ? 'v1beta' : 'v1';
3908 -
3909 - $url = "https://generativelanguage.googleapis.com/{$api_version}/models/{$model}:generateContent?key=" . urlencode($api_key);
3910 -
3911 - $args = [
3912 - 'headers' => [
3913 - 'Content-Type' => 'application/json',
3914 - ],
3915 - 'body' => wp_json_encode([
3916 - 'contents' => [
3917 - [
3918 - 'role' => 'user',
3919 - 'parts' => [
3920 - ['text' => $system_prompt . "\n\nQuery: " . sanitize_text_field($user_query)]
3921 - ]
3922 - ]
3923 - ],
3924 - 'generationConfig' => [
3925 - 'temperature' => 0.2,
3926 - 'maxOutputTokens' => 20,
3927 - ],
3928 - ]),
3929 - 'method' => 'POST',
3930 - 'timeout' => 15,
3931 - ];
3932 -
3933 - $response = wp_remote_post($url, $args);
3934 - if (is_wp_error($response)) {
3935 - return sanitize_text_field($user_query);
3936 - }
3937 -
3938 - $body = json_decode(wp_remote_retrieve_body($response), true);
3939 - if (!empty($body['candidates'][0]['content']['parts'][0]['text'])) {
3940 - return sanitize_text_field(trim($body['candidates'][0]['content']['parts'][0]['text']));
3941 - }
3942 -
3943 - return sanitize_text_field($user_query);
3944 -}
3945 -
3946 -/**
3947 - * Interpret query using X.AI (Grok) models
3948 - */
3949 -private function interpret_query_with_xai($user_query, $system_prompt, $api_key, $model) {
3950 - $url = 'https://api.xai.com/v1/chat/completions';
3951 -
3952 - $args = [
3953 - 'headers' => [
3954 - 'Content-Type' => 'application/json',
3955 - 'Authorization' => 'Bearer ' . $api_key,
3956 - ],
3957 - 'body' => wp_json_encode([
3958 - 'model' => $model,
3959 - 'messages' => [
3960 - ['role' => 'system', 'content' => $system_prompt],
3961 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
3962 - ],
3963 - 'temperature' => 0.2,
3964 - 'max_tokens' => 20,
3965 - ]),
3966 - 'method' => 'POST',
3967 - 'timeout' => 15,
3968 - ];
3969 -
3970 - $response = wp_remote_post($url, $args);
3971 - if (is_wp_error($response)) {
3972 - return sanitize_text_field($user_query);
3973 - }
3974 -
3975 - $body = json_decode(wp_remote_retrieve_body($response), true);
3976 - if (isset($body['choices'][0]['message']['content'])) {
3977 - return sanitize_text_field(trim($body['choices'][0]['message']['content']));
3978 - }
3979 -
3980 - return sanitize_text_field($user_query);
3981 -}
3982 -
3983 -/**
3984 - * Interpret query using DeepSeek models
3985 - */
3986 -private function interpret_query_with_deepseek($user_query, $system_prompt, $api_key, $model) {
3987 - $url = 'https://api.deepseek.com/v1/chat/completions';
3988 -
3989 - $args = [
3990 - 'headers' => [
3991 - 'Content-Type' => 'application/json',
3992 - 'Authorization' => 'Bearer ' . $api_key,
3993 - ],
3994 - 'body' => wp_json_encode([
3995 - 'model' => $model,
3996 - 'messages' => [
3997 - ['role' => 'system', 'content' => $system_prompt],
3998 - ['role' => 'user', 'content' => sanitize_text_field($user_query)],
3999 - ],
4000 - 'temperature' => 0.2,
4001 - 'max_tokens' => 20,
4002 - // DeepSeek V4 defaults to thinking mode ON (temperature ignored,
4003 - // reasoning burns the 20-token budget); keep the legacy
4004 - // deepseek-chat semantics = non-thinking.
4005 - 'thinking' => ['type' => 'disabled'],
4006 - ]),
4007 - 'method' => 'POST',
4008 - 'timeout' => 15,
4009 - ];
4010 -
4011 - $response = wp_remote_post($url, $args);
4012 - if (is_wp_error($response)) {
4013 - return sanitize_text_field($user_query);
4014 - }
4015 -
4016 - $body = json_decode(wp_remote_retrieve_body($response), true);
4017 - if (isset($body['choices'][0]['message']['content'])) {
4018 - return sanitize_text_field(trim($body['choices'][0]['message']['content']));
4019 - }
4020 -
4021 - return sanitize_text_field($user_query);
4022 -}
4023 -
4024 -//very good
4025 -private function add_email_to_loops($email) {
4026 - // Sanitize the email
4027 - $email = sanitize_email($email);
4028 -
4029 - // Retrieve and sanitize options
4030 - $api_key = isset($this->options['loops_api_key']) ? sanitize_text_field($this->options['loops_api_key']) : '';
4031 - $mailing_list_id = isset($this->options['loops_mailing_list']) ? sanitize_text_field($this->options['loops_mailing_list']) : '';
4032 -
4033 - // Check for missing API key or mailing list ID
4034 - if (empty($api_key) || empty($mailing_list_id)) {
4035 - //error_log(esc_html__('Loops API key or mailing list ID is missing.', 'mxchat'));
4036 - return;
4037 - }
4038 -
4039 - $data = array(
4040 - 'email' => $email,
4041 - 'subscribed' => true,
4042 - 'source' => __('MxChat AI Chatbot', 'mxchat'),
4043 - 'mailingLists' => array($mailing_list_id => true),
4044 - );
4045 -
4046 - $url = 'https://app.loops.so/api/v1/contacts/create';
4047 - $args = array(
4048 - 'body' => wp_json_encode($data),
4049 - 'headers' => array(
4050 - 'Authorization' => 'Bearer ' . $api_key,
4051 - 'Content-Type' => 'application/json',
4052 - ),
4053 - 'method' => 'POST',
4054 - 'timeout' => 45,
4055 - );
4056 -
4057 - $response = wp_remote_post($url, $args);
4058 -
4059 - // Handle errors in the API request
4060 - if (is_wp_error($response)) {
4061 - //error_log(esc_html__('Error adding email to Loops: ', 'mxchat') . $response->get_error_message());
4062 - return;
4063 - }
4064 -
4065 - // Check for non-200 HTTP responses
4066 - $response_code = wp_remote_retrieve_response_code($response);
4067 - if ($response_code != 200) {
4068 - $response_body = wp_remote_retrieve_body($response);
4069 - //error_log(esc_html__('Loops API responded with code ', 'mxchat') . $response_code . ': ' . $response_body);
4070 - }
4071 -}
4072 -
4073 -public function mxchat_handle_pdf_discussion($message, $user_id, $session_id) {
4074 - // Get the maximum number of pages allowed from admin settings
4075 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
4076 -
4077 - // Retrieve options for dynamic texts
4078 - $trigger_text = $this->options['pdf_intent_trigger_text'] ?? __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
4079 - $success_text = $this->options['pdf_intent_success_text'] ?? __("I've processed the PDF. What questions do you have about it?", 'mxchat');
4080 - $error_text = $this->options['pdf_intent_error_text'] ?? __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
4081 -
4082 - // Check for explicit request for new PDF
4083 - $new_pdf_requested = stripos($message, 'new') !== false ||
4084 - stripos($message, 'another') !== false ||
4085 - stripos($message, 'different') !== false;
4086 -
4087 - // If user mentions adding/reading a PDF, set waiting flag
4088 - if (stripos($message, 'pdf') !== false ||
4089 - stripos($message, 'document') !== false ||
4090 - stripos($message, 'read') !== false) {
4091 - set_transient('mxchat_waiting_for_pdf_url_' . $session_id, true, HOUR_IN_SECONDS);
4092 - $this->fallbackResponse['text'] = $trigger_text;
4093 - return;
4094 - }
4095 -
4096 - // If we're waiting for a URL or user requested new PDF
4097 - if ($new_pdf_requested || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
4098 - if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
4099 - // Process URL... (rest of your existing URL processing code)
4100 - } else {
4101 - $this->fallbackResponse['text'] = $trigger_text;
4102 - }
4103 - return;
4104 - }
4105 -
4106 - // Default to proceeding with conversation if no specific PDF action is needed
4107 - $this->fallbackResponse['text'] = '';
4108 -}
4109 -
4110 -
4111 -/**
4112 - * Enhanced fetch_and_split_pdf_pages with SSRF protection
4113 - */
4114 -private function fetch_and_split_pdf_pages($pdf_source, $max_pages) {
4115 - // Reset the per-call embedding-failure reason (104a75) — callers read it via
4116 - // get_last_pdf_embedding_error() when zero pages come back.
4117 - $this->last_pdf_embedding_error = null;
4118 -
4119 - // CLEAR DEBUG LOGGING
4120 - //error_log("=== MXCHAT PDF PROCESSING START ===");
4121 - //error_log("PDF Source: " . $pdf_source);
4122 - //error_log("Max Pages: " . $max_pages);
4123 - //error_log("Session ID: " . ($this->session_id ?? 'not set'));
4124 -
4125 - // Check if Advanced Claude Toolbar is available and enabled
4126 - $claude_available = function_exists('mxchatACT_is_advanced_claude_enabled');
4127 - $claude_enabled = $claude_available ? mxchatACT_is_advanced_claude_enabled() : false;
4128 -
4129 - //error_log("Claude Function Available: " . ($claude_available ? 'YES' : 'NO'));
4130 - //error_log("Claude Enabled: " . ($claude_enabled ? 'YES' : 'NO'));
4131 -
4132 - if ($claude_available && $claude_enabled) {
4133 - //error_log("🚀 ATTEMPTING CLAUDE PROCESSING...");
4134 -
4135 - // Attempt Claude processing first
4136 - $claude_result = apply_filters('mxchat_process_pdf_advanced', false, $pdf_source, $max_pages, $this->session_id);
4137 -
4138 - if ($claude_result !== false && is_array($claude_result) && !empty($claude_result)) {
4139 - //error_log("✅ CLAUDE PROCESSING SUCCESSFUL!");
4140 - //error_log("Claude returned " . count($claude_result) . " processed pages");
4141 -
4142 - // Log first page details for verification
4143 - if (isset($claude_result[0])) {
4144 - $first_page = $claude_result[0];
4145 - //error_log("First page enhanced: " . (isset($first_page['enhanced']) && $first_page['enhanced'] ? 'YES' : 'NO'));
4146 - //error_log("Processing method: " . ($first_page['processing_method'] ?? 'not set'));
4147 - //error_log("First page text preview: " . substr($first_page['text'] ?? '', 0, 100) . "...");
4148 - }
4149 -
4150 - //error_log("=== MXCHAT PDF PROCESSING END (CLAUDE) ===");
4151 - return $claude_result;
4152 - } else {
4153 - //error_log("❌ CLAUDE PROCESSING FAILED or returned invalid result");
4154 - //error_log("Claude result type: " . gettype($claude_result));
4155 - if (is_array($claude_result)) {
4156 - //error_log("Claude result count: " . count($claude_result));
4157 - }
4158 - }
4159 - }
4160 -
4161 - // Fallback to basic processing
4162 - //error_log("🔄 FALLING BACK TO BASIC PDF PROCESSING...");
4163 -
4164 - $upload_dir = wp_upload_dir();
4165 - $temp_file = null;
4166 -
4167 - try {
4168 - // Your existing basic processing code here...
4169 - // (I'll include the key parts with debug logging)
4170 -
4171 - if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
4172 - //error_log("Downloading PDF from URL...");
4173 -
4174 - // SECURITY FIX: Validate URL before processing
4175 - if (!$this->mxchat_is_safe_pdf_url($pdf_source)) {
4176 - //error_log("❌ SECURITY: Blocked unsafe PDF URL");
4177 - return false;
4178 - }
4179 -
4180 - $temp_file = wp_tempnam($pdf_source);
4181 -
4182 - // SECURITY FIX: Changed from wp_remote_get to wp_safe_remote_get
4183 - // Route through the shared MXChat crawler identity (plan bae78f/b6d93c) so
4184 - // every remote-content fetch presents one honest, versioned, filterable,
4185 - // allowlistable User-Agent. function_exists guard keeps the front-end/nopriv
4186 - // path safe if the helper (in the always-loaded main file) is ever unavailable.
4187 - $response = wp_safe_remote_get($pdf_source, [
4188 - 'timeout' => 60,
4189 - 'headers' => ['User-Agent' => function_exists('mxchat_ingest_user_agent') ? mxchat_ingest_user_agent() : 'MxChat PDF Processor']
4190 - ]);
4191 -
4192 - if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
4193 - $error_message = is_wp_error($response) ? $response->get_error_message() : 'HTTP ' . wp_remote_retrieve_response_code($response);
4194 - //error_log("❌ BASIC PROCESSING: Failed to download PDF: " . $error_message);
4195 - return false;
4196 - }
4197 -
4198 - global $wp_filesystem;
4199 - if (empty($wp_filesystem)) {
4200 - require_once ABSPATH . 'wp-admin/includes/file.php';
4201 - WP_Filesystem();
4202 - }
4203 - $wp_filesystem->put_contents($temp_file, wp_remote_retrieve_body($response), FS_CHMOD_FILE);
4204 - //error_log("✅ PDF downloaded successfully");
4205 - } else {
4206 - $temp_file = $pdf_source;
4207 - //error_log("Using local PDF file: " . $temp_file);
4208 - }
4209 -
4210 - // Parse PDF
4211 - //error_log("Parsing PDF with basic parser...");
4212 - mxchat_load_pdf_parser();
4213 - $parser = new \Smalot\PdfParser\Parser();
4214 - $pdf = $parser->parseFile($temp_file);
4215 - $pages = $pdf->getPages();
4216 -
4217 - //error_log("PDF contains " . count($pages) . " pages");
4218 -
4219 - if (count($pages) > $max_pages) {
4220 - //error_log("❌ BASIC PROCESSING: Too many pages (" . count($pages) . " > " . $max_pages . ")");
4221 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file) {
4222 - unlink($temp_file);
4223 - }
4224 - return 'too_many_pages';
4225 - }
4226 -
4227 - $embeddings = [];
4228 - $processed_pages = 0;
4229 - $skipped_pages = 0;
4230 -
4231 - foreach ($pages as $page_number => $page) {
4232 - $text = $page->getText();
4233 - $text = MxChat_Utils::normalize_pdf_rtl($text, 'chat_pdf page ' . ($page_number + 1));
4234 -
4235 - if (empty(trim($text))) {
4236 - //error_log("Skipping empty page: " . ($page_number + 1));
4237 - continue;
4238 - }
4239 -
4240 - $text = $this->mxchat_clean_text($text);
4241 -
4242 - $embedding = $this->mxchat_generate_embedding(
4243 - __("Page ", 'mxchat') . ($page_number + 1) . ": " . $text,
4244 - $this->options['api_key']
4245 - );
4246 -
4247 - // The embedding failure contract is an ARRAY ['error','error_code'] — which is
4248 - // TRUTHY. A bare `if ($embedding)` therefore stored error arrays AS the page's
4249 - // vector, poisoning cosine similarity for the rest of the session (104a75).
4250 - // Accept only a real vector: an array with no 'error' key.
4251 - if (is_array($embedding) && !isset($embedding['error'])) {
4252 - $embeddings[] = [
4253 - 'page_number' => $page_number + 1,
4254 - 'embedding' => $embedding,
4255 - 'text' => $text,
4256 - 'enhanced' => false, // CLEARLY MARK AS BASIC
4257 - 'processing_method' => 'basic_pdf_parser'
4258 - ];
4259 - $processed_pages++;
4260 - } else {
4261 - $skipped_pages++;
4262 - // Keep the FIRST failure reason so the callers can surface it instead of
4263 - // the generic "couldn't process the PDF" text.
4264 - if ($this->last_pdf_embedding_error === null && is_array($embedding) && isset($embedding['error'])) {
4265 - $this->last_pdf_embedding_error = (string) $embedding['error'];
4266 - }
4267 - }
4268 - }
4269 -
4270 - if ($skipped_pages > 0 && class_exists('MxChat_Admin')) {
4271 - MxChat_Admin::mxchat_log_debug(
4272 - 'embedding_error',
4273 - sprintf(
4274 - /* translators: 1: skipped page count, 2: successfully embedded page count */
4275 - __('PDF chat: %1$d page(s) skipped because embedding failed; %2$d page(s) stored.', 'mxchat'),
4276 - $skipped_pages,
4277 - $processed_pages
4278 - ),
4279 - array(
4280 - 'first_error' => $this->last_pdf_embedding_error,
4281 - 'skipped' => $skipped_pages,
4282 - 'stored' => $processed_pages,
4283 - )
4284 - );
4285 - }
4286 -
4287 - //error_log("✅ BASIC PROCESSING COMPLETE: " . $processed_pages . " pages processed");
4288 -
4289 - // Cleanup
4290 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
4291 - unlink($temp_file);
4292 - }
4293 -
4294 - //error_log("=== MXCHAT PDF PROCESSING END (BASIC) ===");
4295 - return $embeddings;
4296 -
4297 - } catch (\Exception $e) {
4298 - //error_log("❌ BASIC PROCESSING ERROR: " . $e->getMessage());
4299 - if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
4300 - unlink($temp_file);
4301 - }
4302 - //error_log("=== MXCHAT PDF PROCESSING END (ERROR) ===");
4303 - return false;
4304 - }
4305 -}
4306 -
4307 -/**
4308 - * Append the embedding provider's own failure reason to a generic PDF error string,
4309 - * when the most recent split captured one (104a75). Mirrors the 46b596/4a7c0a rule:
4310 - * never discard a diagnosis the layer below already produced. Returns $base_text
4311 - * unchanged when no reason was captured, so the healthy/unsupported-file wording
4312 - * is byte-identical to before.
4313 - */
4314 -private function mxchat_pdf_error_text_with_reason($base_text) {
4315 - if (empty($this->last_pdf_embedding_error)) {
4316 - return $base_text;
4317 - }
4318 -
4319 - return $base_text . ' ' . sprintf(
4320 - /* translators: %s: error reason reported by the embedding provider */
4321 - __('(%s)', 'mxchat'),
4322 - $this->last_pdf_embedding_error
4323 - );
4324 -}
4325 -
4326 -
4327 -/**
4328 - * Validate PDF URL for security
4329 - * Prevents SSRF attacks by blocking dangerous URLs
4330 - */
4331 -
4332 -private function mxchat_is_safe_pdf_url($url) {
4333 - // Use WordPress core function for comprehensive validation
4334 - // This blocks localhost, private IPs, and reserved IP ranges
4335 - $validated_url = wp_http_validate_url($url);
4336 -
4337 - if ($validated_url === false) {
4338 - return false;
4339 - }
4340 -
4341 - // Additional check: only allow HTTP/HTTPS schemes
4342 - $parsed = parse_url($url);
4343 - if (!isset($parsed['scheme']) || !in_array($parsed['scheme'], ['http', 'https'], true)) {
4344 - return false;
4345 - }
4346 -
4347 - return true;
4348 -}
4349 -
4350 -
4351 -private function mxchat_clean_text($text) {
4352 - // Remove excessive whitespace
4353 - $text = preg_replace('/\s+/', ' ', $text);
4354 -
4355 - // Remove control characters except newlines and tabs
4356 - $text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text);
4357 -
4358 - // Normalize line endings
4359 - $text = str_replace(["\r\n", "\r"], "\n", $text);
4360 -
4361 - // Trim whitespace
4362 - $text = trim($text);
4363 -
4364 - return $text;
4365 -}
4366 -
4367 -private function find_relevant_pdf_pages($query_embedding, $embeddings) {
4368 - //error_log(esc_html__("find_relevant_pdf_pages called.", 'mxchat'));
4369 -
4370 - $most_relevant = null;
4371 - $highest_similarity = -INF;
4372 -
4373 - foreach ($embeddings as $page_data) {
4374 - $similarity = $this->mxchat_calculate_cosine_similarity($query_embedding, $page_data['embedding']);
4375 -
4376 - if ($similarity > $highest_similarity) {
4377 - $highest_similarity = $similarity;
4378 - $most_relevant = $page_data['page_number'];
4379 - }
4380 - }
4381 -
4382 - if (!is_null($most_relevant)) {
4383 - $page_numbers = range(max(1, $most_relevant - 1), min(count($embeddings), $most_relevant + 1));
4384 - return array_filter($embeddings, function ($page) use ($page_numbers) {
4385 - return in_array($page['page_number'], $page_numbers);
4386 - });
4387 - }
4388 -
4389 - return [];
4390 -}
4391 -
4392 -
4393 -public function handle_pdf_upload() {
4394 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce(wp_unslash((string) $_POST['nonce']))) {
4395 - wp_send_json_error(array('message' => esc_html__('Invalid nonce.', 'mxchat')), 403);
4396 - }
4397 -
4398 - if (!isset($_FILES['pdf_file']) || !isset($_POST['session_id'])) {
4399 - wp_send_json_error(esc_html__('Missing required parameters.', 'mxchat'));
4400 - return;
4401 - }
4402 -
4403 - // SECURITY FIX: Check if PDF uploads are enabled in settings
4404 - $options = get_option('mxchat_options', array());
4405 - $show_pdf_button = isset($options['show_pdf_upload_button']) ? $options['show_pdf_upload_button'] : 'on';
4406 -
4407 - if ($show_pdf_button !== 'on') {
4408 - wp_send_json_error(esc_html__('PDF uploads are currently disabled.', 'mxchat'));
4409 - return;
4410 - }
4411 -
4412 - $file = $_FILES['pdf_file'];
4413 - $session_id = MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id']));
4414 - $original_filename = sanitize_text_field($file['name']);
4415 -
4416 - // Update session owner if it changed (e.g. IP changed due to network switch)
4417 - $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
4418 - $session_owner = MxChat_Session_Store::get($session_id, 'owner');
4419 -
4420 - if (!$session_owner || $session_owner !== $current_user_identifier) {
4421 - MxChat_Session_Store::set($session_id, 'owner', $current_user_identifier);
4422 - }
4423 -
4424 - $file_type = wp_check_filetype($file['name'], ['pdf' => 'application/pdf']);
4425 - if ($file_type['type'] !== 'application/pdf') {
4426 - wp_send_json_error(esc_html__('Invalid file type. Only PDF files are allowed.', 'mxchat'));
4427 - return;
4428 - }
4429 -
4430 - $upload_dir = wp_upload_dir();
4431 -
4432 - // SECURITY FIX: Generate random filename without exposing session_id
4433 - $random_string = wp_generate_password(20, false, false); // 20 char alphanumeric string
4434 - $pdf_filename = 'mxchat_' . $random_string . '_' . time() . '.pdf';
4435 - $pdf_path = $upload_dir['path'] . '/' . $pdf_filename;
4436 -
4437 - if (!move_uploaded_file($file['tmp_name'], $pdf_path)) {
4438 - wp_send_json_error(esc_html__('Failed to upload file.', 'mxchat'));
4439 - return;
4440 - }
4441 -
4442 - $this->clear_pdf_transients($session_id);
4443 -
4444 - $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
4445 - $embeddings = $this->fetch_and_split_pdf_pages($pdf_path, $max_pages);
4446 -
4447 - if ($embeddings === 'too_many_pages') {
4448 - unlink($pdf_path);
4449 - $error_message = sprintf(
4450 - $this->options['pdf_intent_error_text'] ??
4451 - esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
4452 - $max_pages
4453 - );
4454 - wp_send_json_error($error_message);
4455 - return;
4456 - }
4457 -
4458 - if ($embeddings === false || empty($embeddings)) {
4459 - unlink($pdf_path);
4460 - $error_message = $this->options['pdf_intent_error_text'] ??
4461 - esc_html__('The uploaded PDF appears to be empty or contains unsupported content.', 'mxchat');
4462 - // Zero pages can also mean every embedding call failed — say so instead of
4463 - // blaming the file (104a75).
4464 - wp_send_json_error($this->mxchat_pdf_error_text_with_reason($error_message));
4465 - return;
4466 - }
4467 -
4468 - if (!empty($embeddings)) {
4469 - // Store the mapping between session and the random filename
4470 - set_transient('mxchat_pdf_url_' . $session_id, $pdf_path, HOUR_IN_SECONDS);
4471 - set_transient('mxchat_pdf_filename_' . $session_id, $original_filename, HOUR_IN_SECONDS);
4472 - set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
4473 - set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
4474 -
4475 - $success_message = $this->options['pdf_intent_success_text'] ??
4476 - esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat');
4477 -
4478 - wp_send_json_success([
4479 - 'message' => $success_message,
4480 - 'filename' => $original_filename
4481 - ]);
4482 - return;
4483 - }
4484 -
4485 - unlink($pdf_path);
4486 - $error_message = $this->options['pdf_intent_error_text'] ??
4487 - esc_html__('Sorry, I couldn\'t process the PDF. Please ensure it\'s a valid file.', 'mxchat');
4488 - wp_send_json_error($error_message);
4489 - return;
4490 -}
4491 -public function handle_pdf_remove() {
4492 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce(wp_unslash((string) $_POST['nonce']))) {
4493 - wp_send_json_error(array('message' => esc_html__('Invalid nonce.', 'mxchat')), 403);
4494 - }
4495 -
4496 - if (empty($_POST['session_id'])) {
4497 - wp_send_json_error(esc_html__('Session ID missing.', 'mxchat'));
4498 - wp_die();
4499 - }
4500 -
4501 - $session_id = MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id']));
4502 - if ($session_id === '') {
4503 - wp_send_json_error(esc_html__('Session ID missing.', 'mxchat'));
4504 - wp_die();
4505 - }
4506 -
4507 - // Session-ownership bookkeeping (plan-mxchat-20260731-d42bec).
4508 - //
4509 - // Be clear about what this does and does not do. It mirrors the history
4510 - // endpoint's rule exactly, as directed, INCLUDING its changed-IP tolerance:
4511 - // possession of the session id IS the credential, so a mismatched identifier
4512 - // re-owns the session instead of being refused. That means this does NOT
4513 - // refuse a caller who supplies someone else's session id — it keeps the two
4514 - // endpoints agreeing about who owns a session, and records the owner so a
4515 - // future stricter policy has trustworthy data to enforce against.
4516 - //
4517 - // What actually protects another visitor's upload here is that session ids
4518 - // are 128-bit CSPRNG values (plan-0c17b5) and therefore not guessable. If we
4519 - // ever want a real boundary on this endpoint, it has to be decided for the
4520 - // history endpoint at the same time.
4521 - $current_user_identifier = MxChat_User::mxchat_get_user_identifier();
4522 - $session_owner = MxChat_Session_Store::get($session_id, 'owner');
4523 - if (!$session_owner || $session_owner !== $current_user_identifier) {
4524 - MxChat_Session_Store::set($session_id, 'owner', $current_user_identifier);
4525 - }
4526 -
4527 - $pdf_path = get_transient('mxchat_pdf_url_' . $session_id);
4528 -
4529 - if ($pdf_path && file_exists($pdf_path)) {
4530 - unlink($pdf_path);
4531 - }
4532 -
4533 - $this->clear_pdf_transients($session_id);
4534 -
4535 - wp_send_json_success([
4536 - 'message' => esc_html__('PDF removed successfully.', 'mxchat')
4537 - ]);
4538 - wp_die();
4539 -}
4540 -
4541 -
4542 -function mxchat_fetch_new_messages() {
4543 - $session_id = MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id']));
4544 - $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
4545 - $persistence_enabled = $_POST['persistence_enabled'] === 'true';
4546 - $initial_timestamp = isset($_POST['initial_timestamp']) ? intval($_POST['initial_timestamp']) : 0;
4547 -
4548 - if (empty($session_id)) {
4549 - //error_log(esc_html__('Fetch new messages error: Session ID missing.', 'mxchat'));
4550 - wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
4551 - wp_die();
4552 - }
4553 -
4554 - $history = MxChat_Utils::get_session_history($session_id);
4555 -
4556 - //error_log("MxChat WhatsApp DEBUG: Fetch new messages for session {$session_id}");
4557 - //error_log("MxChat WhatsApp DEBUG: last_seen_id = " . var_export($last_seen_id, true));
4558 - //error_log("MxChat WhatsApp DEBUG: History count = " . count($history));
4559 -
4560 - // Second-resolution timestamps since 3.2.19 (839c4c): floor the client's
4561 - // millisecond cutoff to the second boundary and compare inclusively —
4562 - // same reasoning as the persistence-off filter in the AI context build.
4563 - $initial_cutoff = (int) floor($initial_timestamp / 1000) * 1000;
4564 -
4565 - $new_messages = array_filter($history, function ($message) use ($last_seen_id, $persistence_enabled, $initial_cutoff) {
4566 - //error_log("MxChat WhatsApp DEBUG: Checking message - ID: " . ($message['id'] ?? 'NO_ID') . ", Role: " . ($message['role'] ?? 'NO_ROLE'));
4567 -
4568 - // If persistence is enabled, show all new messages
4569 - if ($persistence_enabled) {
4570 - $has_id = !empty($message['id']);
4571 - $is_agent = $message['role'] === 'agent';
4572 -
4573 - // Ids are integers since 3.2.19 (839c4c). Empty / 'NaN' /
4574 - // 'undefined' / any non-numeric bookmark — including a legacy
4575 - // uniqid() a mid-upgrade client still holds, which strcmp would
4576 - // wrongly outrank every integer id — replays all agent messages.
4577 - if (empty($last_seen_id) || !ctype_digit($last_seen_id)) {
4578 - $is_newer = true;
4579 - } else {
4580 - $is_newer = (int) ($message['id'] ?? 0) > (int) $last_seen_id;
4581 - }
4582 -
4583 - //error_log("MxChat WhatsApp DEBUG: has_id={$has_id}, is_newer={$is_newer}, is_agent={$is_agent}");
4584 -
4585 - return $has_id && $is_newer && $is_agent;
4586 - }
4587 -
4588 - // If persistence is disabled, only show messages after initial timestamp
4589 - return !empty($message['id']) &&
4590 - $message['role'] === 'agent' &&
4591 - $message['timestamp'] >= $initial_cutoff;
4592 - });
4593 -
4594 - //error_log("MxChat WhatsApp DEBUG: Filtered messages count = " . count($new_messages));
4595 -
4596 - // Include current chat mode so frontend can detect agent→AI transitions
4597 - $chat_mode = MxChat_Session_Store::get($session_id, 'mode', 'ai');
4598 -
4599 - wp_send_json_success([
4600 - 'new_messages' => array_values($new_messages),
4601 - 'chat_mode' => $chat_mode
4602 - ]);
4603 - wp_die();
4604 -}
4605 -public function mxchat_live_agent_handover($message, $user_id, $session_id) {
4606 - // First check if live agents are available.
4607 - // Outside the SLACK availability schedule this behaves exactly like the
4608 - // manual toggle being off — same away message, same stay-in-AI-mode path
4609 - // (plans 8ccaa2 + 99d7a4: each channel owns its own schedule). The schedule
4610 - // normally stops the tool being offered at all; this is the backstop for
4611 - // any path that calls the handover directly.
4612 - $live_agent_available = $this->options['live_agent_status'] ?? 'off';
4613 - $within_hours = !class_exists('MxChat_Live_Agent_Schedule')
4614 - || MxChat_Live_Agent_Schedule::is_within_hours('slack');
4615 - if ($live_agent_available !== 'on' || !$within_hours) {
4616 - $away_message = $this->options['live_agent_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
4617 - $this->fallbackResponse = [
4618 - 'text' => $away_message,
4619 - 'html' => '',
4620 - 'images' => [],
4621 - 'chat_mode' => 'ai'
4622 - ];
4623 - wp_send_json([
4624 - 'text' => $away_message,
4625 - 'html' => '',
4626 - 'chat_mode' => 'ai',
4627 - 'session_id' => $session_id
4628 - ]);
4629 - wp_die();
4630 - }
4631 -
4632 - $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
4633 -
4634 - if (empty($slack_bot_token)) {
4635 - return false;
4636 - }
4637 -
4638 - // Check if channel already exists for this session
4639 - $channel_id = MxChat_Session_Store::get($session_id, 'channel', '');
4640 -
4641 - // Shared-channel mode (plan 9f7756): when a shared handoff channel is
4642 - // configured and this session doesn't already own a per-conversation
4643 - // channel, the handoff posts into the shared channel as a new thread
4644 - // (or into the session's existing thread on a re-handover). Any failure
4645 - // to reach the shared channel falls back to per-conversation creation
4646 - // below, so a misconfigured channel never drops a handoff.
4647 - $shared_channel_setting = trim($this->options['live_agent_shared_channel'] ?? '');
4648 - $shared_thread_ts = get_option("mxchat_thread_{$session_id}", '');
4649 - $use_shared_channel = ($shared_channel_setting !== '' && empty($channel_id));
4650 -
4651 - if (empty($channel_id) && !$use_shared_channel) {
4652 - $channel_id = $this->mxchat_create_conversation_channel($session_id);
4653 - if (empty($channel_id)) {
4654 - return false; // Failed to create channel
4655 - }
4656 - }
4657 -
4658 - // Get recent chat history
4659 - $history = MxChat_Utils::get_session_history($session_id);
4660 - $recent_history = array_slice($history, -5);
4661 -
4662 - // Format conversation context
4663 - $conversation_context = "";
4664 - if (!empty($recent_history)) {
4665 - $conversation_context = "*Recent Conversation:*\n";
4666 - foreach ($recent_history as $hist_message) {
4667 - $role_display = $hist_message['role'] === 'user' ? 'User' : 'AI';
4668 - $conversation_context .= ">{$role_display}: {$hist_message['content']}\n";
4669 - }
4670 - $conversation_context .= "\n";
4671 - }
4672 -
4673 - MxChat_Session_Store::set($session_id, 'mode', 'agent');
4674 -
4675 - // Send message to channel
4676 - $channel_message = "🔔 *New Live Agent Request*\n\n";
4677 - $channel_message .= "*Session ID:* `{$session_id}`\n";
4678 - $channel_message .= "*User ID:* `{$user_id}`\n";
4679 -
4680 - // Surface the captured visitor identity so the agent knows who they're talking to —
4681 - // guest User IDs are 0, but the pre-chat gate / login / transcript often has name+email (plan-e2195b).
4682 - $visitor = $this->mxchat_get_visitor_identity($session_id);
4683 - if (!empty($visitor['name']) && !empty($visitor['email'])) {
4684 - $channel_message .= "*Visitor:* {$visitor['name']} <{$visitor['email']}>\n";
4685 - } elseif (!empty($visitor['email'])) {
4686 - $channel_message .= "*Visitor:* <{$visitor['email']}>\n";
4687 - } elseif (!empty($visitor['name'])) {
4688 - $channel_message .= "*Visitor:* {$visitor['name']}\n";
4689 - }
4690 - $channel_message .= "\n";
4691 -
4692 - if (!empty($conversation_context)) {
4693 - $channel_message .= $conversation_context;
4694 - }
4695 -
4696 - $channel_message .= "*Current Message:*\n{$message}\n\n";
4697 - if ($use_shared_channel) {
4698 - $channel_message .= "_Reply in this thread - replies here go to the user. `!endchat` in this thread ends the chat._";
4699 - } else {
4700 - $channel_message .= "_Reply directly in this channel - all messages will go to the user_";
4701 - }
4702 -
4703 - if ($use_shared_channel) {
4704 - $posted = $this->mxchat_post_shared_handoff($session_id, $channel_message, $shared_thread_ts);
4705 - if (!$posted) {
4706 - // Shared channel unreachable (wrong name/ID, bot not invited,
4707 - // archived...). Fall back to the per-conversation flow so the
4708 - // visitor still reaches an agent; the settings page surfaces the
4709 - // recorded error to the admin.
4710 - $use_shared_channel = false;
4711 - $channel_id = $this->mxchat_create_conversation_channel($session_id);
4712 - if (empty($channel_id)) {
4713 - return false;
4714 - }
4715 - $channel_message = str_replace(
4716 - "_Reply in this thread - replies here go to the user. `!endchat` in this thread ends the chat._",
4717 - "_Reply directly in this channel - all messages will go to the user_",
4718 - $channel_message
4719 - );
4720 - }
4721 - }
4722 -
4723 - if (!$use_shared_channel) {
4724 - $handoff_post = wp_remote_post('https://slack.com/api/chat.postMessage', [
4725 - 'headers' => [
4726 - 'Content-Type' => 'application/json',
4727 - 'Authorization' => 'Bearer ' . $slack_bot_token
4728 - ],
4729 - 'body' => json_encode([
4730 - 'channel' => $channel_id,
4731 - 'text' => $channel_message,
4732 - 'mrkdwn' => true
4733 - ])
4734 - ]);
4735 - // Re-handover edge (plan 7458a7): the stored mxchat_channel_ may point
4736 - // at a channel archived by the auto-archive toggle (or deleted by an
4737 - // admin). Slack answers is_archived / channel_not_found — clear the
4738 - // stale option, mint a fresh channel, and re-post ONCE so the handoff
4739 - // is never silently dropped.
4740 - if (!is_wp_error($handoff_post)) {
4741 - $handoff_data = json_decode(wp_remote_retrieve_body($handoff_post), true);
4742 - $handoff_err = isset($handoff_data['error']) ? $handoff_data['error'] : '';
4743 - if (isset($handoff_data['ok']) && !$handoff_data['ok'] && in_array($handoff_err, array('is_archived', 'channel_not_found'), true)) {
4744 - MxChat_Session_Store::delete($session_id, 'channel');
4745 - $channel_id = $this->mxchat_create_conversation_channel($session_id);
4746 - if (!empty($channel_id)) {
4747 - wp_remote_post('https://slack.com/api/chat.postMessage', [
4748 - 'headers' => [
4749 - 'Content-Type' => 'application/json',
4750 - 'Authorization' => 'Bearer ' . $slack_bot_token
4751 - ],
4752 - 'body' => json_encode([
4753 - 'channel' => $channel_id,
4754 - 'text' => $channel_message,
4755 - 'mrkdwn' => true
4756 - ])
4757 - ]);
4758 - }
4759 - }
4760 - }
4761 - }
4762 -
4763 - $success_message = $this->options['live_agent_notification_message'] ?? 'Live agent has been notified.';
4764 - $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
4765 -
4766 - $this->fallbackResponse = [
4767 - 'text' => $success_message,
4768 - 'html' => '',
4769 - 'images' => [],
4770 - 'chat_mode' => 'agent'
4771 - ];
4772 -
4773 - wp_send_json([
4774 - 'success' => true,
4775 - 'text' => $success_message,
4776 - 'html' => '',
4777 - 'chat_mode' => 'agent',
4778 - 'session_id' => $session_id,
4779 - 'fallbackResponse' => $this->fallbackResponse
4780 - ]);
4781 - wp_die();
4782 -}
4783 -
4784 -/**
4785 - * Archive a session's per-conversation chat- channel after !endchat / session
4786 - * cleanup (plan 7458a7). HARD GUARDS, in order: the toggle must be on
4787 - * (default off = zero change for existing installs); a session with
4788 - * mxchat_thread_ set is a 9f7756 SHARED-channel session and is never
4789 - * archived; only the channel this session owns via mxchat_channel_ is
4790 - * archived, and only when it matches the channel the caller is acting on.
4791 - * Best-effort by design — a failed archive is logged and never blocks the
4792 - * mode flip or cleanup.
4793 - *
4794 - * @param string $session_id
4795 - * @param string $event_channel_id Channel the caller is acting on.
4796 - */
4797 -private function mxchat_maybe_archive_conversation_channel($session_id, $event_channel_id) {
4798 - $toggle = $this->options['live_agent_archive_on_end_toggle'] ?? 'off';
4799 - if ($toggle !== 'on') {
4800 - return;
4801 - }
4802 - if (get_option("mxchat_thread_{$session_id}", '') !== '') {
4803 - return; // shared-channel session — the shared channel is NEVER archived
4804 - }
4805 - $owned_channel = MxChat_Session_Store::get($session_id, 'channel', '');
4806 - if ($owned_channel === '' || $owned_channel !== $event_channel_id) {
4807 - return;
4808 - }
4809 - $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
4810 - if (empty($slack_bot_token)) {
4811 - return;
4812 - }
4813 - $response = wp_remote_post('https://slack.com/api/conversations.archive', [
4814 - 'headers' => [
4815 - 'Content-Type' => 'application/json',
4816 - 'Authorization' => 'Bearer ' . $slack_bot_token
4817 - ],
4818 - 'body' => json_encode(['channel' => $owned_channel])
4819 - ]);
4820 - if (is_wp_error($response)) {
4821 - error_log('MxChat: conversations.archive request failed: ' . $response->get_error_message());
4822 - return;
4823 - }
4824 - $data = json_decode(wp_remote_retrieve_body($response), true);
4825 - if (empty($data['ok'])) {
4826 - error_log('MxChat: conversations.archive returned error: ' . (isset($data['error']) ? $data['error'] : 'unknown'));
4827 - }
4828 -}
4829 -
4830 -/**
4831 - * Create a dedicated per-conversation Slack channel for a session and invite
4832 - * the configured agents. Extracted from mxchat_live_agent_handover so the
4833 - * shared-channel mode (plan 9f7756) can reuse it as its fallback path.
4834 - *
4835 - * @param string $session_id
4836 - * @return string Channel ID, or '' on failure.
4837 - */
4838 -private function mxchat_create_conversation_channel($session_id) {
4839 - $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
4840 - if (empty($slack_bot_token)) {
4841 - return '';
4842 - }
4843 -
4844 - $channel_id = '';
4845 - $channel_name = $this->generate_channel_name($session_id);
4846 -
4847 - $response = wp_remote_post('https://slack.com/api/conversations.create', [
4848 - 'headers' => [
4849 - 'Content-Type' => 'application/json',
4850 - 'Authorization' => 'Bearer ' . $slack_bot_token
4851 - ],
4852 - 'body' => json_encode([
4853 - 'name' => $channel_name,
4854 - 'is_private' => false // Public channel - anyone in workspace can join
4855 - ])
4856 - ]);
4857 -
4858 - if (!is_wp_error($response)) {
4859 - $response_data = json_decode(wp_remote_retrieve_body($response), true);
4860 -
4861 - if (isset($response_data['ok']) && $response_data['ok']) {
4862 - $channel_id = $response_data['channel']['id'];
4863 - MxChat_Session_Store::set($session_id, 'channel', $channel_id);
4864 -
4865 - // Auto-invite agents to the channel
4866 - $agent_user_ids = $this->options['live_agent_user_ids'] ?? '';
4867 -
4868 - if (!empty($agent_user_ids)) {
4869 - // Parse user IDs (one per line)
4870 - $user_ids = array_filter(array_map('trim', explode("\n", $agent_user_ids)));
4871 -
4872 - foreach ($user_ids as $user_id_to_invite) {
4873 - wp_remote_post('https://slack.com/api/conversations.invite', [
4874 - 'headers' => [
4875 - 'Content-Type' => 'application/json',
4876 - 'Authorization' => 'Bearer ' . $slack_bot_token
4877 - ],
4878 - 'body' => json_encode([
4879 - 'channel' => $channel_id,
4880 - 'users' => $user_id_to_invite
4881 - ])
4882 - ]);
4883 - }
4884 - }
4885 - }
4886 - }
4887 -
4888 - return $channel_id;
4889 -}
4890 -
4891 -/**
4892 - * Post a handoff (or a re-handover) into the configured shared channel.
4893 - * First post per session becomes the conversation's thread root; its ts is
4894 - * stored in mxchat_thread_{session} and every later message rides that
4895 - * thread. Records the Slack error for the settings page on failure so the
4896 - * caller can fall back to per-conversation creation.
4897 - *
4898 - * @param string $session_id
4899 - * @param string $text Fully-built handoff message.
4900 - * @param string $thread_ts Existing thread root for this session, '' if none.
4901 - * @return bool True when the message reached the shared channel.
4902 - */
4903 -private function mxchat_post_shared_handoff($session_id, $text, $thread_ts = '') {
4904 - $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
4905 - $configured = trim($this->options['live_agent_shared_channel'] ?? '');
4906 - if (empty($slack_bot_token) || $configured === '') {
4907 - return false;
4908 - }
4909 -
4910 - // Posting by #name works once the bot is a member; the response carries
4911 - // the real channel ID, cached so the inbound webhook and user-relay
4912 - // don't depend on how the admin wrote the setting.
4913 - $cache = get_option('mxchat_slack_shared_channel_id', array());
4914 - $target = (is_array($cache) && ($cache['configured'] ?? '') === $configured && !empty($cache['id']))
4915 - ? $cache['id']
4916 - : ltrim($configured, '#');
4917 -
4918 - $body = [
4919 - 'channel' => $target,
4920 - 'text' => $text,
4921 - 'mrkdwn' => true
4922 - ];
4923 - if ($thread_ts !== '') {
4924 - $body['thread_ts'] = $thread_ts;
4925 - }
4926 -
4927 - $response = wp_remote_post('https://slack.com/api/chat.postMessage', [
4928 - 'headers' => [
4929 - 'Content-Type' => 'application/json',
4930 - 'Authorization' => 'Bearer ' . $slack_bot_token
4931 - ],
4932 - 'body' => json_encode($body)
4933 - ]);
4934 -
4935 - if (is_wp_error($response)) {
4936 - update_option('mxchat_slack_shared_channel_error', array(
4937 - 'error' => $response->get_error_message(),
4938 - 'configured' => $configured,
4939 - 'time' => time(),
4940 - ), false);
4941 - return false;
4942 - }
4943 -
4944 - $data = json_decode(wp_remote_retrieve_body($response), true);
4945 - if (empty($data['ok'])) {
4946 - update_option('mxchat_slack_shared_channel_error', array(
4947 - 'error' => $data['error'] ?? 'unknown_error',
4948 - 'configured' => $configured,
4949 - 'time' => time(),
4950 - ), false);
4951 - return false;
4952 - }
4953 -
4954 - delete_option('mxchat_slack_shared_channel_error');
4955 -
4956 - if (!empty($data['channel'])) {
4957 - update_option('mxchat_slack_shared_channel_id', array(
4958 - 'configured' => $configured,
4959 - 'id' => $data['channel'],
4960 - ), false);
4961 - }
4962 - if ($thread_ts === '' && !empty($data['ts'])) {
4963 - update_option("mxchat_thread_{$session_id}", $data['ts'], 'no');
4964 - }
4965 -
4966 - return true;
4967 -}
4968 -
4969 -private function generate_channel_name($session_id) {
4970 - $email = null;
4971 - $name = null;
4972 -
4973 - // 1. First priority: Check if user is logged in and get their info
4974 - if (is_user_logged_in()) {
4975 - $current_user = wp_get_current_user();
4976 - if (!empty($current_user->user_email)) {
4977 - $email = $current_user->user_email;
4978 - //error_log("[DEBUG] Using logged-in user email for channel: {$email}");
4979 - }
4980 - if (!empty($current_user->display_name)) {
4981 - $name = $current_user->display_name;
4982 - //error_log("[DEBUG] Using logged-in user name for channel: {$name}");
4983 - }
4984 - }
4985 -
4986 - // 2. Second priority: Check for saved email/name from "require email to chat" option
4987 - if (empty($email)) {
4988 - $saved_email = MxChat_Session_Store::get($session_id, 'email');
4989 - if (!empty($saved_email)) {
4990 - $email = $saved_email;
4991 - }
4992 - }
4993 -
4994 - if (empty($name)) {
4995 - $saved_name = MxChat_Session_Store::get($session_id, 'name');
4996 - if (!empty($saved_name)) {
4997 - $name = $saved_name;
4998 - }
4999 - }
5000 -
5001 - // 3. Third priority: Check existing chat transcript for email/name
5002 - if (empty($email) || empty($name)) {
5003 - global $wpdb;
5004 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
5005 - $existing_data = $wpdb->get_row($wpdb->prepare(
5006 - "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",
5007 - $session_id
5008 - ));
5009 -
5010 - if ($existing_data) {
5011 - if (empty($email) && !empty($existing_data->user_email)) {
5012 - $email = $existing_data->user_email;
5013 - //error_log("[DEBUG] Using email from chat transcript for channel: {$email}");
5014 - }
5015 - if (empty($name) && !empty($existing_data->user_name)) {
5016 - $name = $existing_data->user_name;
5017 - //error_log("[DEBUG] Using name from chat transcript for channel: {$name}");
5018 - }
5019 - }
5020 - }
5021 -
5022 - // 4. Generate channel name based on priority: Name > Email > Session ID
5023 - $channel_name = '';
5024 -
5025 - if (!empty($name)) {
5026 - // Convert name to valid Slack channel name
5027 - $base_name = strtolower(trim($name));
5028 - // Replace spaces and invalid characters
5029 - $base_name = preg_replace('/[^a-z0-9\s]/', '', $base_name);
5030 - $base_name = preg_replace('/\s+/', '-', $base_name);
5031 - $base_name = trim($base_name, '-');
5032 -
5033 - // Get last 4 characters of session ID for uniqueness
5034 - $session_suffix = substr($session_id, -4);
5035 - $channel_name = 'chat-' . $base_name . '-' . strtolower($session_suffix);
5036 -
5037 - // Slack channel names have a 21 character limit
5038 - if (strlen($channel_name) > 21) {
5039 - // Calculate available space for name (21 - 'chat-' - '-' - session_suffix)
5040 - $available_space = 21 - 5 - 1 - strlen($session_suffix); // 'chat-' = 5, '-' = 1
5041 - $truncated_name = substr($base_name, 0, $available_space);
5042 - $truncated_name = rtrim($truncated_name, '-'); // Remove trailing hyphen
5043 - $channel_name = 'chat-' . $truncated_name . '-' . strtolower($session_suffix);
5044 - }
5045 -
5046 - //error_log("[DEBUG] Using name for channel: {$channel_name} (from name: {$name})");
5047 -
5048 - } elseif (!empty($email)) {
5049 - // Convert email to valid Slack channel name (your existing logic)
5050 - $channel_name = 'chat-' . strtolower(str_replace(['@', '.', '+', '_'], ['-at-', '-', '-plus-', '-'], $email));
5051 - // Remove any remaining invalid characters
5052 - $channel_name = preg_replace('/[^a-z0-9\-]/', '', $channel_name);
5053 - // Ensure it doesn't end with a hyphen
5054 - $channel_name = rtrim($channel_name, '-');
5055 - // Slack channel names have a 21 character limit, so truncate if needed
5056 - if (strlen($channel_name) > 21) {
5057 - $channel_name = substr($channel_name, 0, 21);
5058 - $channel_name = rtrim($channel_name, '-'); // Remove trailing hyphen if truncation created one
5059 - }
5060 -
5061 - //error_log("[DEBUG] Using email for channel: {$channel_name} (from email: {$email})");
5062 -
5063 - } else {
5064 - // Fallback to session ID if no name or email found
5065 - $channel_name = 'chat-' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $session_id));
5066 - //error_log("[DEBUG] No name or email found, using session ID for channel: {$channel_name}");
5067 - }
5068 -
5069 - // Final validation - ensure channel name meets Slack requirements
5070 - if (strlen($channel_name) > 21) {
5071 - $channel_name = substr($channel_name, 0, 21);
5072 - $channel_name = rtrim($channel_name, '-');
5073 - }
5074 -
5075 - //error_log("[DEBUG] Generated channel name: {$channel_name}");
5076 - return $channel_name;
5077 -}
5078 -
5079 -/**
5080 - * Telegram Live Agent Handover
5081 - * Creates a forum topic in the Telegram group and notifies agents
5082 - */
5083 -public function mxchat_telegram_live_agent_handover($message, $user_id, $session_id) {
5084 - // Check if Telegram agents are available. Telegram has its OWN availability
5085 - // schedule, independent of Slack's (plan 99d7a4 — each Integrations tab
5086 - // owns its scheduler). Backstop only; the tool is normally withheld
5087 - // off-hours.
5088 - $telegram_available = $this->options['telegram_status'] ?? 'off';
5089 - $within_hours = !class_exists('MxChat_Live_Agent_Schedule')
5090 - || MxChat_Live_Agent_Schedule::is_within_hours('telegram');
5091 - if ($telegram_available !== 'on' || !$within_hours) {
5092 - $away_message = $this->options['telegram_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
5093 - $this->fallbackResponse = [
5094 - 'text' => $away_message,
5095 - 'html' => '',
5096 - 'images' => [],
5097 - 'chat_mode' => 'ai'
5098 - ];
5099 - wp_send_json([
5100 - 'text' => $away_message,
5101 - 'html' => '',
5102 - 'chat_mode' => 'ai',
5103 - 'session_id' => $session_id
5104 - ]);
5105 - wp_die();
5106 - }
5107 -
5108 - $telegram_bot_token = $this->options['telegram_bot_token'] ?? '';
5109 - $telegram_group_id = $this->options['telegram_group_id'] ?? '';
5110 -
5111 - if (empty($telegram_bot_token) || empty($telegram_group_id)) {
5112 - return false;
5113 - }
5114 -
5115 - // Check if topic already exists for this session
5116 - $topic_id = get_option("mxchat_telegram_topic_{$session_id}", '');
5117 -
5118 - if (empty($topic_id)) {
5119 - // Generate topic name
5120 - $topic_name = $this->generate_telegram_topic_name($session_id);
5121 -
5122 - // Random icon color (Telegram forum topic colors)
5123 - $icon_colors = [0x6FB9F0, 0xFFD67E, 0xCB86DB, 0x8EEE98, 0xFF93B2, 0xFB6F5F];
5124 - $icon_color = $icon_colors[array_rand($icon_colors)];
5125 -
5126 - // Create forum topic
5127 - $response = wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/createForumTopic", [
5128 - 'headers' => ['Content-Type' => 'application/json'],
5129 - 'body' => json_encode([
5130 - 'chat_id' => $telegram_group_id,
5131 - 'name' => $topic_name,
5132 - 'icon_color' => $icon_color
5133 - ])
5134 - ]);
5135 -
5136 - if (!is_wp_error($response)) {
5137 - $response_body = wp_remote_retrieve_body($response);
5138 - $response_data = json_decode($response_body, true);
5139 -
5140 - if (isset($response_data['ok']) && $response_data['ok']) {
5141 - $topic_id = $response_data['result']['message_thread_id'];
5142 - update_option("mxchat_telegram_topic_{$session_id}", $topic_id);
5143 - update_option("mxchat_telegram_group_{$session_id}", $telegram_group_id);
5144 - }
5145 - }
5146 -
5147 - if (empty($topic_id)) {
5148 - return false; // Failed to create topic
5149 - }
5150 - }
5151 -
5152 - // Get recent chat history
5153 - $history = MxChat_Utils::get_session_history($session_id);
5154 - $recent_history = array_slice($history, -5);
5155 -
5156 - // Format conversation context for Telegram (HTML format)
5157 - $conversation_context = "";
5158 - if (!empty($recent_history)) {
5159 - $conversation_context = "<b>Recent Conversation:</b>\n";
5160 - foreach ($recent_history as $hist_message) {
5161 - $role_display = $hist_message['role'] === 'user' ? '👤 User' : '🤖 AI';
5162 - $escaped_content = htmlspecialchars($hist_message['content'], ENT_QUOTES, 'UTF-8');
5163 - $conversation_context .= "{$role_display}: {$escaped_content}\n";
5164 - }
5165 - $conversation_context .= "\n";
5166 - }
5167 -
5168 - // Get user info
5169 - $user_email = MxChat_Session_Store::get($session_id, 'email', 'Not provided');
5170 - $user_name = MxChat_Session_Store::get($session_id, 'name', 'Anonymous');
5171 -
5172 - // Update session mode
5173 - MxChat_Session_Store::set($session_id, 'mode', 'agent');
5174 -
5175 - // Send initial message to topic
5176 - $escaped_message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
5177 - $topic_message = "🔔 <b>New Live Agent Request</b>\n\n";
5178 - $topic_message .= "<b>Session ID:</b> <code>{$session_id}</code>\n";
5179 - $topic_message .= "<b>User:</b> {$user_name}\n";
5180 - $topic_message .= "<b>Email:</b> {$user_email}\n\n";
5181 -
5182 - if (!empty($conversation_context)) {
5183 - $topic_message .= $conversation_context;
5184 - }
5185 -
5186 - $topic_message .= "<b>Current Message:</b>\n{$escaped_message}\n\n";
5187 - $topic_message .= "<i>Reply in this topic - messages will be sent to the user</i>\n";
5188 - $topic_message .= "<i>Type #close, #end, #disconnect, or #done to end the session</i>";
5189 -
5190 - wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/sendMessage", [
5191 - 'headers' => ['Content-Type' => 'application/json'],
5192 - 'body' => json_encode([
5193 - 'chat_id' => $telegram_group_id,
5194 - 'message_thread_id' => $topic_id,
5195 - 'text' => $topic_message,
5196 - 'parse_mode' => 'HTML'
5197 - ])
5198 - ]);
5199 -
5200 - $success_message = $this->options['telegram_notification_message'] ?? "I've notified a support agent. Please allow a moment for them to respond.";
5201 - $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
5202 -
5203 - $this->fallbackResponse = [
5204 - 'text' => $success_message,
5205 - 'html' => '',
5206 - 'images' => [],
5207 - 'chat_mode' => 'agent'
5208 - ];
5209 -
5210 - wp_send_json([
5211 - 'success' => true,
5212 - 'text' => $success_message,
5213 - 'html' => '',
5214 - 'chat_mode' => 'agent',
5215 - 'session_id' => $session_id,
5216 - 'fallbackResponse' => $this->fallbackResponse
5217 - ]);
5218 - wp_die();
5219 -}
5220 -
5221 -/**
5222 - * Generate topic name for Telegram forum
5223 - */
5224 -private function generate_telegram_topic_name($session_id) {
5225 - $name = null;
5226 - $email = null;
5227 -
5228 - // Check logged in user
5229 - if (is_user_logged_in()) {
5230 - $current_user = wp_get_current_user();
5231 - if (!empty($current_user->display_name)) {
5232 - $name = $current_user->display_name;
5233 - }
5234 - if (!empty($current_user->user_email)) {
5235 - $email = $current_user->user_email;
5236 - }
5237 - }
5238 -
5239 - // Check session data
5240 - if (empty($name)) {
5241 - $name = MxChat_Session_Store::get($session_id, 'name');
5242 - }
5243 - if (empty($email)) {
5244 - $email = MxChat_Session_Store::get($session_id, 'email');
5245 - }
5246 -
5247 - // Generate topic name
5248 - $session_suffix = substr($session_id, -6);
5249 -
5250 - if (!empty($name)) {
5251 - // Clean name for topic (max 128 chars in Telegram)
5252 - $clean_name = preg_replace('/[^\p{L}\p{N}\s\-]/u', '', $name);
5253 - $clean_name = trim($clean_name);
5254 - if (strlen($clean_name) > 50) {
5255 - $clean_name = substr($clean_name, 0, 50);
5256 - }
5257 - return "Chat - {$clean_name} ({$session_suffix})";
5258 - } elseif (!empty($email)) {
5259 - // Use email prefix
5260 - $email_prefix = explode('@', $email)[0];
5261 - if (strlen($email_prefix) > 30) {
5262 - $email_prefix = substr($email_prefix, 0, 30);
5263 - }
5264 - return "Chat - {$email_prefix} ({$session_suffix})";
5265 - }
5266 -
5267 - return "Chat - {$session_suffix}";
5268 -}
5269 -
5270 -/**
5271 - * Send user message to Telegram agent
5272 - */
5273 -public function mxchat_send_user_message_to_telegram_agent($message, $user_id, $session_id) {
5274 - $telegram_bot_token = $this->options['telegram_bot_token'] ?? '';
5275 - $topic_id = get_option("mxchat_telegram_topic_{$session_id}", '');
5276 - $group_id = get_option("mxchat_telegram_group_{$session_id}", '');
5277 -
5278 - if (empty($telegram_bot_token) || empty($topic_id) || empty($group_id)) {
5279 - return false;
5280 - }
5281 -
5282 - $escaped_message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
5283 - $user_message = "👤 <b>User:</b> {$escaped_message}";
5284 -
5285 - $response = wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/sendMessage", [
5286 - 'headers' => ['Content-Type' => 'application/json'],
5287 - 'body' => json_encode([
5288 - 'chat_id' => $group_id,
5289 - 'message_thread_id' => $topic_id,
5290 - 'text' => $user_message,
5291 - 'parse_mode' => 'HTML'
5292 - ])
5293 - ]);
5294 -
5295 - return !is_wp_error($response);
5296 -}
5297 -
5298 -/**
5299 - * Handle incoming Telegram webhook
5300 - */
5301 -public function handle_telegram_webhook(WP_REST_Request $request) {
5302 - $body = $request->get_body();
5303 - $data = json_decode($body, true);
5304 -
5305 - //error_log('[MxChat Telegram DEBUG] Webhook received: ' . $body);
5306 -
5307 - // Handle message events from forum topics
5308 - if (isset($data['message'])) {
5309 - $message_data = $data['message'];
5310 -
5311 - // Skip if not from a forum topic
5312 - if (!isset($message_data['message_thread_id'])) {
5313 - //error_log('[MxChat Telegram DEBUG] Skipped: No message_thread_id (not a forum topic message)');
5314 - return new WP_REST_Response(['ok' => true]);
5315 - }
5316 -
5317 - // Skip bot messages
5318 - if (isset($message_data['from']['is_bot']) && $message_data['from']['is_bot']) {
5319 - //error_log('[MxChat Telegram DEBUG] Skipped: Message from bot');
5320 - return new WP_REST_Response(['ok' => true]);
5321 - }
5322 -
5323 - $chat_id = $message_data['chat']['id'] ?? '';
5324 - $topic_id = $message_data['message_thread_id'];
5325 - $message_text = $message_data['text'] ?? '';
5326 - $message_id = $message_data['message_id'] ?? '';
5327 - $from = $message_data['from'] ?? [];
5328 - $agent_name = trim(($from['first_name'] ?? '') . ' ' . ($from['last_name'] ?? ''));
5329 - if (empty($agent_name)) {
5330 - $agent_name = $from['username'] ?? 'Agent';
5331 - }
5332 -
5333 - //error_log("[MxChat Telegram DEBUG] Parsed: chat_id={$chat_id}, topic_id={$topic_id}, agent={$agent_name}, text={$message_text}");
5334 -
5335 - // Skip empty messages
5336 - if (empty($message_text)) {
5337 - //error_log('[MxChat Telegram DEBUG] Skipped: Empty message text');
5338 - return new WP_REST_Response(['ok' => true]);
5339 - }
5340 -
5341 - // Find session ID by topic ID - cast to string for comparison
5342 - global $wpdb;
5343 - $topic_id_str = strval($topic_id);
5344 - $session_option = $wpdb->get_var(
5345 - $wpdb->prepare(
5346 - "SELECT option_name FROM {$wpdb->options}
5347 - WHERE option_name LIKE %s
5348 - AND option_value = %s",
5349 - 'mxchat_telegram_topic_%',
5350 - $topic_id_str
5351 - )
5352 - );
5353 -
5354 - //error_log("[MxChat Telegram DEBUG] Looking for topic_id={$topic_id_str} in options, found: " . ($session_option ?: 'NULL'));
5355 -
5356 - if ($session_option) {
5357 - $session_id = str_replace('mxchat_telegram_topic_', '', $session_option);
5358 - //error_log("[MxChat Telegram DEBUG] Session ID: {$session_id}");
5359 -
5360 - // Verify the group ID matches
5361 - $stored_group_id = get_option("mxchat_telegram_group_{$session_id}", '');
5362 - //error_log("[MxChat Telegram DEBUG] Stored group_id={$stored_group_id}, received chat_id={$chat_id}");
5363 -
5364 - if (strval($stored_group_id) != strval($chat_id)) {
5365 - //error_log('[MxChat Telegram DEBUG] Skipped: Group ID mismatch');
5366 - return new WP_REST_Response(['ok' => true]);
5367 - }
5368 -
5369 - // Check for closure commands
5370 - $lower_text = strtolower(trim($message_text));
5371 - if (in_array($lower_text, ['#close', '#end', '#disconnect', '#done'])) {
5372 - //error_log("[MxChat Telegram DEBUG] Closure command received: {$lower_text}");
5373 - // End the live agent session
5374 - MxChat_Session_Store::set($session_id, 'mode', 'ai');
5375 -
5376 - // Save disconnect message
5377 - $disconnect_message = "Live agent session ended. You're now chatting with the AI assistant.";
5378 - $this->mxchat_save_chat_message($session_id, 'bot', $disconnect_message);
5379 -
5380 - // Notify in Telegram
5381 - $telegram_bot_token = $this->options['telegram_bot_token'] ?? '';
5382 - if (!empty($telegram_bot_token)) {
5383 - wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/sendMessage", [
5384 - 'headers' => ['Content-Type' => 'application/json'],
5385 - 'body' => json_encode([
5386 - 'chat_id' => $chat_id,
5387 - 'message_thread_id' => $topic_id,
5388 - 'text' => "✅ Session closed. User returned to AI chatbot.",
5389 - 'parse_mode' => 'HTML'
5390 - ])
5391 - ]);
5392 -
5393 - // Optionally close the topic
5394 - wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/closeForumTopic", [
5395 - 'headers' => ['Content-Type' => 'application/json'],
5396 - 'body' => json_encode([
5397 - 'chat_id' => $chat_id,
5398 - 'message_thread_id' => $topic_id
5399 - ])
5400 - ]);
5401 - }
5402 -
5403 - return new WP_REST_Response(['ok' => true]);
5404 - }
5405 -
5406 - // Deduplicate messages
5407 - $message_key = md5($session_id . $message_id . $message_text);
5408 - $processed_messages = get_transient('mxchat_telegram_messages_' . $session_id) ?: [];
5409 -
5410 - if (in_array($message_key, $processed_messages)) {
5411 - //error_log('[MxChat Telegram DEBUG] Skipped: Duplicate message');
5412 - return new WP_REST_Response(['ok' => true]);
5413 - }
5414 -
5415 - $processed_messages[] = $message_key;
5416 - if (count($processed_messages) > 50) {
5417 - $processed_messages = array_slice($processed_messages, -50);
5418 - }
5419 - set_transient('mxchat_telegram_messages_' . $session_id, $processed_messages, HOUR_IN_SECONDS);
5420 -
5421 - // Save the agent message - format with agent name prefix for proper parsing
5422 - $formatted_message = "Agent: {$agent_name} - {$message_text}";
5423 - //error_log("[MxChat Telegram DEBUG] Saving agent message: {$formatted_message}");
5424 -
5425 - $this->mxchat_save_chat_message($session_id, 'agent', $formatted_message);
5426 -
5427 - // Verify the message was saved to history
5428 - $history = MxChat_Utils::get_session_history($session_id);
5429 - $last_message = end($history);
5430 - //error_log("[MxChat Telegram DEBUG] History after save - count: " . count($history) . ", last message role: " . ($last_message['role'] ?? 'none'));
5431 -
5432 - // Send confirmation back to Telegram
5433 - $telegram_bot_token = $this->options['telegram_bot_token'] ?? '';
5434 - if (!empty($telegram_bot_token)) {
5435 - $confirm_key = 'mxchat_telegram_confirm_' . $message_key;
5436 - if (!get_transient($confirm_key)) {
5437 - wp_remote_post("https://api.telegram.org/bot{$telegram_bot_token}/sendMessage", [
5438 - 'headers' => ['Content-Type' => 'application/json'],
5439 - 'body' => json_encode([
5440 - 'chat_id' => $chat_id,
5441 - 'message_thread_id' => $topic_id,
5442 - 'text' => "✅ <i>Message sent to user</i>",
5443 - 'parse_mode' => 'HTML',
5444 - 'reply_to_message_id' => $message_id
5445 - ])
5446 - ]);
5447 - set_transient($confirm_key, true, 300);
5448 - }
5449 - }
5450 - } else {
5451 - //error_log("[MxChat Telegram DEBUG] No session found for topic_id={$topic_id}");
5452 - }
5453 - } else {
5454 - //error_log('[MxChat Telegram DEBUG] No message in webhook data');
5455 - }
5456 -
5457 - return new WP_REST_Response(['ok' => true]);
5458 -}
5459 -
5460 -public function mxchat_send_user_message_to_agent($message, $user_id, $session_id) {
5461 - // Check if this is a Telegram agent session
5462 - $telegram_topic_id = get_option("mxchat_telegram_topic_{$session_id}", '');
5463 - if (!empty($telegram_topic_id)) {
5464 - return $this->mxchat_send_user_message_to_telegram_agent($message, $user_id, $session_id);
5465 - }
5466 -
5467 - // Otherwise, try Slack
5468 - $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
5469 -
5470 - // Shared-channel session: the conversation lives in a thread of the
5471 - // shared channel (plan 9f7756); relay user messages into that thread.
5472 - $thread_ts = get_option("mxchat_thread_{$session_id}", '');
5473 - if (!empty($thread_ts)) {
5474 - $cache = get_option('mxchat_slack_shared_channel_id', array());
5475 - $channel_id = is_array($cache) ? ($cache['id'] ?? '') : '';
5476 - } else {
5477 - $channel_id = MxChat_Session_Store::get($session_id, 'channel', '');
5478 - }
5479 -
5480 - if (empty($slack_bot_token) || empty($channel_id)) {
5481 - return false;
5482 - }
5483 -
5484 - $user_message = "💬 *User:* {$message}";
5485 -
5486 - $body = [
5487 - 'channel' => $channel_id,
5488 - 'text' => $user_message,
5489 - 'mrkdwn' => true
5490 - ];
5491 - if (!empty($thread_ts)) {
5492 - $body['thread_ts'] = $thread_ts;
5493 - }
5494 -
5495 - $response = wp_remote_post('https://slack.com/api/chat.postMessage', [
5496 - 'headers' => [
5497 - 'Content-Type' => 'application/json',
5498 - 'Authorization' => 'Bearer ' . $slack_bot_token
5499 - ],
5500 - 'body' => json_encode($body)
5501 - ]);
5502 -
5503 - return !is_wp_error($response);
5504 -}
5505 -public function handle_slack_interaction(WP_REST_Request $request) {
5506 - //error_log('Received Slack interaction');
5507 -
5508 - $payload = json_decode($request->get_param('payload'), true);
5509 - //error_log('Payload: ' . print_r($payload, true));
5510 -
5511 - // Handle button click
5512 - if ($payload['type'] === 'block_actions' && $payload['actions'][0]['action_id'] === 'reply_to_user') {
5513 - $session_id = $payload['actions'][0]['value'];
5514 - $trigger_id = $payload['trigger_id'];
5515 -
5516 - // Get Bot Token from settings
5517 - $slack_token = $this->options['live_agent_bot_token'] ?? '';
5518 -
5519 - if (empty($slack_token)) {
5520 - //error_log('Slack Bot Token not configured');
5521 - return new WP_REST_Response(['error' => esc_html__('Bot token not configured', 'mxchat')], 400);
5522 - }
5523 - $response = wp_remote_post('https://slack.com/api/views.open', [
5524 - 'headers' => [
5525 - 'Content-Type' => 'application/json',
5526 - 'Authorization' => 'Bearer ' . $slack_token
5527 - ],
5528 - 'body' => json_encode([
5529 - 'trigger_id' => $trigger_id,
5530 - 'view' => [
5531 - 'type' => 'modal',
5532 - 'callback_id' => 'reply_modal',
5533 - 'title' => [
5534 - 'type' => 'plain_text',
5535 - 'text' => __('Reply to User', 'mxchat')
5536 - ],
5537 - 'submit' => [
5538 - 'type' => 'plain_text',
5539 - 'text' => __('Send', 'mxchat')
5540 - ],
5541 - 'close' => [
5542 - 'type' => 'plain_text',
5543 - 'text' => __('Cancel', 'mxchat')
5544 - ],
5545 - 'blocks' => [
5546 - [
5547 - 'type' => 'input',
5548 - 'block_id' => 'reply_block',
5549 - 'label' => [
5550 - 'type' => 'plain_text',
5551 - 'text' => sprintf(__('Reply to session: %s', 'mxchat'), $session_id)
5552 - ],
5553 - 'element' => [
5554 - 'type' => 'plain_text_input',
5555 - 'action_id' => 'message',
5556 - 'multiline' => true,
5557 - 'placeholder' => [
5558 - 'type' => 'plain_text',
5559 - 'text' => __('Type your message here...', 'mxchat')
5560 - ]
5561 - ]
5562 - ]
5563 - ],
5564 - 'private_metadata' => $session_id
5565 - ]
5566 - ])
5567 - ]);
5568 -
5569 - //error_log('Views.open response: ' . print_r($response, true));
5570 -
5571 - // Return immediate acknowledgment
5572 - return new WP_REST_Response(['ok' => true]);
5573 - }
5574 -
5575 - // Handle modal submission
5576 -// Handle modal submission
5577 -if ($payload['type'] === 'view_submission') {
5578 - $session_id = $payload['view']['private_metadata'];
5579 - $message = $payload['view']['state']['values']['reply_block']['message']['value'];
5580 -
5581 - // Save the message (keep the message_id but don't include in response)
5582 - $this->mxchat_save_chat_message($session_id, 'agent', $message);
5583 -
5584 - // Keep the original response format for Slack
5585 - return new WP_REST_Response([
5586 - 'response_action' => 'clear'
5587 - ]);
5588 -}
5589 -
5590 - // Default acknowledgment
5591 - return new WP_REST_Response(['ok' => true]);
5592 -}
5593 -public function mxchat_handle_agent_response(WP_REST_Request $request) {
5594 - //error_log('Received agent response request');
5595 - //error_log('Request data: ' . print_r($request->get_params(), true));
5596 - // //error_log('Raw body: ' . file_get_contents('php://input'));
5597 -
5598 - // Get the data from Slack's slash command format
5599 - $command_text = $request->get_param('text');
5600 - // //error_log('Command text: ' . $command_text);
5601 -
5602 - if (empty($command_text)) {
5603 - //error_log(esc_html__('Agent response error: No command text received', 'mxchat'));
5604 - return new WP_REST_Response([
5605 - 'error' => esc_html__('Command text is required. Format: /reply session_id message', 'mxchat')
5606 - ], 400);
5607 - }
5608 -
5609 - // Split the command text into session_id and message
5610 - $parts = explode(' ', $command_text, 2);
5611 - if (count($parts) !== 2) {
5612 - //error_log('Agent response error: Invalid command format');
5613 - return new WP_REST_Response([
5614 - 'error' => esc_html__('Invalid format. Use: /reply session_id message', 'mxchat')
5615 - ], 400);
5616 - }
5617 -
5618 - $session_id = sanitize_text_field($parts[0]);
5619 - $message = sanitize_text_field($parts[1]);
5620 -
5621 - //error_log("Processing agent response - Session ID: $session_id, Message: $message");
5622 -
5623 - // Save the message
5624 - $message_id = $this->mxchat_save_chat_message($session_id, 'agent', $message);
5625 -
5626 - if (!$message_id) {
5627 - // //error_log('Failed to save agent message');
5628 - return new WP_REST_Response([
5629 - 'error' => esc_html__('Failed to save message', 'mxchat')
5630 - ], 500);
5631 - }
5632 -
5633 - // Return success response in Slack's expected format
5634 - return new WP_REST_Response([
5635 - 'response_type' => 'in_channel',
5636 - 'text' => esc_html__("Message sent successfully to session $session_id", 'mxchat')
5637 - ], 200);
5638 -}
5639 -public function mxchat_handle_switch_to_chatbot_intent($message, $user_id, $session_id) {
5640 - // Update mode to AI
5641 - MxChat_Session_Store::set($session_id, 'mode', 'ai');
5642 -
5643 - // Clear any existing PDF context to start fresh
5644 - $this->clear_pdf_transients($session_id);
5645 -
5646 - // Set the response with explicit chat_mode
5647 - $this->fallbackResponse = [
5648 - 'text' => esc_html__('You are now chatting with the AI chatbot.', 'mxchat'),
5649 - 'html' => '',
5650 - 'images' => [],
5651 - 'chat_mode' => 'ai' // Ensure this is set
5652 - ];
5653 -
5654 - // Return the complete response array instead of just true
5655 - return $this->fallbackResponse;
5656 -}
5657 -
5658 -/**
5659 - * Normalize Slack mrkdwn before relaying an agent's message to the web visitor.
5660 - * Slack's Events API auto-wraps URLs as <https://url> or <https://url|Label>, wraps
5661 - * mentions as <@U…>/<#C…|name>, and HTML-escapes &, <, >. Relayed raw, the visitor
5662 - * sees a broken/doubled link with a trailing > (plan-e2195b). Unwrap links FIRST, then
5663 - * unescape entities LAST so extracted URLs (which can contain &amp;) are not corrupted.
5664 - */
5665 -private function normalize_slack_text($text) {
5666 - if (!is_string($text) || $text === '') {
5667 - return $text;
5668 - }
5669 -
5670 - $text = preg_replace_callback('/<([^>|]+)(?:\|([^>]*))?>/', function ($m) {
5671 - $target = $m[1];
5672 - $label = isset($m[2]) ? $m[2] : '';
5673 -
5674 - // User/channel mentions: <@U…> or <#C…|name> — prefer the human label, else drop the id.
5675 - if (isset($target[0]) && ($target[0] === '@' || $target[0] === '#')) {
5676 - return $label !== '' ? $label : '';
5677 - }
5678 - // mailto:/tel: — strip the scheme for display.
5679 - if (stripos($target, 'mailto:') === 0) {
5680 - $addr = substr($target, 7);
5681 - return ($label !== '' && $label !== $addr) ? "{$label} ({$addr})" : $addr;
5682 - }
5683 - if (stripos($target, 'tel:') === 0) {
5684 - $num = substr($target, 4);
5685 - return ($label !== '' && $label !== $num) ? "{$label} ({$num})" : $num;
5686 - }
5687 - // Regular URL: <url|Label> -> "Label (url)"; bare <url> -> "url".
5688 - if ($label !== '' && $label !== $target) {
5689 - return "{$label} ({$target})";
5690 - }
5691 - return $target;
5692 - }, $text);
5693 -
5694 - // Entity-unescape LAST (after link extraction) so &amp; inside URLs is repaired too.
5695 - $text = str_replace(array('&amp;', '&lt;', '&gt;'), array('&', '<', '>'), $text);
5696 -
5697 - return $text;
5698 -}
5699 -
5700 -/**
5701 - * Resolve the visitor's name + email for a session, mirroring generate_channel_name()'s
5702 - * priority order: logged-in user, then the pre-chat gate capture (session store name/email),
5703 - * then the chat transcript. Returns ['name' => ..., 'email' => ...] (either may be ''). plan-e2195b.
5704 - */
5705 -private function mxchat_get_visitor_identity($session_id) {
5706 - $email = '';
5707 - $name = '';
5708 -
5709 - if (is_user_logged_in()) {
5710 - $current_user = wp_get_current_user();
5711 - if (!empty($current_user->user_email)) { $email = $current_user->user_email; }
5712 - if (!empty($current_user->display_name)) { $name = $current_user->display_name; }
5713 - }
5714 -
5715 - if (empty($email)) {
5716 - $saved_email = MxChat_Session_Store::get($session_id, 'email', '');
5717 - if (!empty($saved_email)) { $email = $saved_email; }
5718 - }
5719 - if (empty($name)) {
5720 - $saved_name = MxChat_Session_Store::get($session_id, 'name', '');
5721 - if (!empty($saved_name)) { $name = $saved_name; }
5722 - }
5723 -
5724 - if (empty($email) || empty($name)) {
5725 - global $wpdb;
5726 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
5727 - $existing_data = $wpdb->get_row($wpdb->prepare(
5728 - "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",
5729 - $session_id
5730 - ));
5731 - if ($existing_data) {
5732 - if (empty($email) && !empty($existing_data->user_email)) { $email = $existing_data->user_email; }
5733 - if (empty($name) && !empty($existing_data->user_name)) { $name = $existing_data->user_name; }
5734 - }
5735 - }
5736 -
5737 - return array('name' => $name, 'email' => $email);
5738 -}
5739 -
5740 -public function handle_slack_messages(WP_REST_Request $request) {
5741 - // Log the incoming request for debugging
5742 - //error_log('Slack events request received: ' . $request->get_body());
5743 -
5744 - $body = $request->get_body();
5745 - $data = json_decode($body, true);
5746 -
5747 - // Handle Slack URL verification
5748 - if (isset($data['type']) && $data['type'] === 'url_verification') {
5749 - //error_log('Slack URL verification challenge: ' . $data['challenge']);
5750 - return new WP_REST_Response($data['challenge'], 200, ['Content-Type' => 'text/plain']);
5751 - }
5752 -
5753 - // IMPORTANT: Handle Slack's event deduplication
5754 - if (isset($data['event_id'])) {
5755 - $event_id = $data['event_id'];
5756 - $processed_events = get_transient('mxchat_slack_events') ?: [];
5757 -
5758 - // Check if we've already processed this event
5759 - if (in_array($event_id, $processed_events)) {
5760 - //error_log("Duplicate event detected: $event_id");
5761 - return new WP_REST_Response(['ok' => true]);
5762 - }
5763 -
5764 - // Add this event to processed list
5765 - $processed_events[] = $event_id;
5766 - // Keep only last 100 events to prevent memory issues
5767 - if (count($processed_events) > 100) {
5768 - $processed_events = array_slice($processed_events, -100);
5769 - }
5770 - // Store for 1 hour
5771 - set_transient('mxchat_slack_events', $processed_events, HOUR_IN_SECONDS);
5772 - }
5773 -
5774 - // Handle message events
5775 - if (isset($data['event']) && $data['event']['type'] === 'message') {
5776 - $event = $data['event'];
5777 -
5778 - // Skip bot messages and messages with subtypes (like bot_message)
5779 - if (isset($event['bot_id']) || isset($event['subtype'])) {
5780 - return new WP_REST_Response(['ok' => true]);
5781 - }
5782 -
5783 - // Threaded replies: in shared-channel mode every conversation lives in
5784 - // a thread rooted at its handoff message — route those to their session
5785 - // by thread root (plan 9f7756). Any other threaded reply (e.g. under a
5786 - // per-conversation channel's confirmation message) finds no session and
5787 - // is skipped, exactly as before.
5788 - if (isset($event['thread_ts']) && $event['thread_ts'] !== $event['ts']) {
5789 - return $this->mxchat_route_shared_thread_reply($event);
5790 - }
5791 -
5792 - $channel_id = $event['channel'];
5793 - $message_text = $event['text'] ?? '';
5794 - $message_ts = $event['ts'] ?? '';
5795 -
5796 - // Find the session that owns this channel. Channel state lives in the
5797 - // sessions table since b64b77 — the migration moves the legacy
5798 - // mxchat_channel_ option rows there and DELETES them, so the old
5799 - // wp_options lookup found nothing and every per-conversation agent
5800 - // reply (including !endchat) was silently dropped (plan 71e4b6). The
5801 - // legacy query remains only as a fallback for installs mid-migration
5802 - // whose channel row has not moved yet.
5803 - $session_id = MxChat_Session_Store::find_by_channel($channel_id);
5804 -
5805 - if ($session_id === '') {
5806 - global $wpdb;
5807 - $session_option = $wpdb->get_var(
5808 - $wpdb->prepare(
5809 - "SELECT option_name FROM {$wpdb->options}
5810 - WHERE option_name LIKE 'mxchat_channel_%'
5811 - AND option_value = %s",
5812 - $channel_id
5813 - )
5814 - );
5815 - if ($session_option) {
5816 - $session_id = str_replace('mxchat_channel_', '', $session_option);
5817 - }
5818 - }
5819 -
5820 - if ($session_id !== '') {
5821 -
5822 - // Create a unique key for this specific message
5823 - $message_key = md5($session_id . $message_ts . $message_text);
5824 - $processed_messages = get_transient('mxchat_processed_messages_' . $session_id) ?: [];
5825 -
5826 - // Check if we've already processed this exact message
5827 - if (in_array($message_key, $processed_messages)) {
5828 - //error_log("Duplicate message detected for session $session_id");
5829 - return new WP_REST_Response(['ok' => true]);
5830 - }
5831 -
5832 - // Add to processed messages
5833 - $processed_messages[] = $message_key;
5834 - // Keep only last 50 messages per session
5835 - if (count($processed_messages) > 50) {
5836 - $processed_messages = array_slice($processed_messages, -50);
5837 - }
5838 - set_transient('mxchat_processed_messages_' . $session_id, $processed_messages, HOUR_IN_SECONDS);
5839 -
5840 - $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
5841 -
5842 - // Handle agent ending the chat — transfer back to AI
5843 - // Format: "!endchat" or "!endchat <custom message to user>"
5844 - if (preg_match('/^!endchat\b/i', trim($message_text))) {
5845 - MxChat_Session_Store::set($session_id, 'mode', 'ai');
5846 -
5847 - // Extract custom message after !endchat, or use empty string
5848 - $custom_message = trim(preg_replace('/^!endchat\s*/i', '', trim($message_text)));
5849 -
5850 - // Send the agent's custom farewell message if provided
5851 - if (!empty($custom_message)) {
5852 - $this->mxchat_save_chat_message($session_id, 'agent', $this->normalize_slack_text($custom_message));
5853 - }
5854 -
5855 - // Confirm in Slack channel
5856 - if (!empty($slack_bot_token)) {
5857 - wp_remote_post('https://slack.com/api/chat.postMessage', [
5858 - 'headers' => [
5859 - 'Content-Type' => 'application/json',
5860 - 'Authorization' => 'Bearer ' . $slack_bot_token
5861 - ],
5862 - 'body' => json_encode([
5863 - 'channel' => $channel_id,
5864 - 'text' => "✅ *Chat ended.* User has been transferred back to AI mode.",
5865 - 'mrkdwn' => true
5866 - ])
5867 - ]);
5868 - }
5869 -
5870 - // Auto-archive the ended conversation's channel (plan 7458a7).
5871 - // Toggle-gated, best-effort — never blocks the mode flip.
5872 - $this->mxchat_maybe_archive_conversation_channel($session_id, $channel_id);
5873 -
5874 - return new WP_REST_Response(['ok' => true]);
5875 - }
5876 -
5877 - // Save the agent message (normalize Slack link/entity formatting first — plan-e2195b)
5878 - $this->mxchat_save_chat_message($session_id, 'agent', $this->normalize_slack_text($message_text));
5879 -
5880 - // Send confirmation back to Slack (only once)
5881 - if (!empty($slack_bot_token)) {
5882 - // Use a transient to prevent duplicate confirmations
5883 - $confirm_key = 'mxchat_confirm_' . $message_key;
5884 - if (!get_transient($confirm_key)) {
5885 - wp_remote_post('https://slack.com/api/chat.postMessage', [
5886 - 'headers' => [
5887 - 'Content-Type' => 'application/json',
5888 - 'Authorization' => 'Bearer ' . $slack_bot_token
5889 - ],
5890 - 'body' => json_encode([
5891 - 'channel' => $channel_id,
5892 - 'text' => "✅ _Message sent to user_",
5893 - 'thread_ts' => $event['ts'] // Reply in thread
5894 - ])
5895 - ]);
5896 - // Set transient to prevent duplicate confirmations
5897 - set_transient($confirm_key, true, 300); // 5 minutes
5898 - }
5899 - }
5900 - }
5901 - }
5902 -
5903 - return new WP_REST_Response(['ok' => true]);
5904 -}
5905 -
5906 -/**
5907 - * Route an agent's threaded Slack reply to the session whose shared-channel
5908 - * conversation is rooted at that thread (plan 9f7756). Sessions are keyed by
5909 - * the thread root ts stored in mxchat_thread_{session}, so two visitors in
5910 - * the same shared channel can never cross-wire. Unknown threads are ignored.
5911 - *
5912 - * @param array $event Slack message event (has thread_ts !== ts).
5913 - * @return WP_REST_Response
5914 - */
5915 -private function mxchat_route_shared_thread_reply($event) {
5916 - $thread_root = $event['thread_ts'] ?? '';
5917 - $message_text = $event['text'] ?? '';
5918 - $message_ts = $event['ts'] ?? '';
5919 - $channel_id = $event['channel'] ?? '';
5920 -
5921 - if ($thread_root === '') {
5922 - return new WP_REST_Response(['ok' => true]);
5923 - }
5924 -
5925 - // Find the session owning this thread root (same reverse-lookup shape as
5926 - // the per-conversation channel mapping).
5927 - global $wpdb;
5928 - $session_option = $wpdb->get_var(
5929 - $wpdb->prepare(
5930 - "SELECT option_name FROM {$wpdb->options}
5931 - WHERE option_name LIKE 'mxchat_thread_%'
5932 - AND option_value = %s",
5933 - $thread_root
5934 - )
5935 - );
5936 -
5937 - if (!$session_option) {
5938 - // Not a shared-channel conversation thread (e.g. a reply under a
5939 - // per-conversation confirmation) — ignore, as before.
5940 - return new WP_REST_Response(['ok' => true]);
5941 - }
5942 -
5943 - $session_id = str_replace('mxchat_thread_', '', $session_option);
5944 -
5945 - // Per-message dedupe — same transient pattern as the top-level handler.
5946 - $message_key = md5($session_id . $message_ts . $message_text);
5947 - $processed_messages = get_transient('mxchat_processed_messages_' . $session_id) ?: [];
5948 - if (in_array($message_key, $processed_messages)) {
5949 - return new WP_REST_Response(['ok' => true]);
5950 - }
5951 - $processed_messages[] = $message_key;
5952 - if (count($processed_messages) > 50) {
5953 - $processed_messages = array_slice($processed_messages, -50);
5954 - }
5955 - set_transient('mxchat_processed_messages_' . $session_id, $processed_messages, HOUR_IN_SECONDS);
5956 -
5957 - $slack_bot_token = $this->options['live_agent_bot_token'] ?? '';
5958 -
5959 - // Agent ending the chat from inside the thread — same command contract as
5960 - // per-conversation channels: "!endchat" or "!endchat <farewell>".
5961 - if (preg_match('/^!endchat\b/i', trim($message_text))) {
5962 - MxChat_Session_Store::set($session_id, 'mode', 'ai');
5963 -
5964 - $custom_message = trim(preg_replace('/^!endchat\s*/i', '', trim($message_text)));
5965 - if (!empty($custom_message)) {
5966 - $this->mxchat_save_chat_message($session_id, 'agent', $this->normalize_slack_text($custom_message));
5967 - }
5968 -
5969 - if (!empty($slack_bot_token) && $channel_id !== '') {
5970 - wp_remote_post('https://slack.com/api/chat.postMessage', [
5971 - 'headers' => [
5972 - 'Content-Type' => 'application/json',
5973 - 'Authorization' => 'Bearer ' . $slack_bot_token
5974 - ],
5975 - 'body' => json_encode([
5976 - 'channel' => $channel_id,
5977 - 'text' => "✅ *Chat ended.* User has been transferred back to AI mode.",
5978 - 'thread_ts' => $thread_root,
5979 - 'mrkdwn' => true
5980 - ])
5981 - ]);
5982 - }
5983 -
5984 - return new WP_REST_Response(['ok' => true]);
5985 - }
5986 -
5987 - // Save the agent message for the widget (normalized like the channel path).
5988 - $this->mxchat_save_chat_message($session_id, 'agent', $this->normalize_slack_text($message_text));
5989 -
5990 - // Confirmation stays inside the conversation's thread.
5991 - if (!empty($slack_bot_token) && $channel_id !== '') {
5992 - $confirm_key = 'mxchat_confirm_' . $message_key;
5993 - if (!get_transient($confirm_key)) {
5994 - wp_remote_post('https://slack.com/api/chat.postMessage', [
5995 - 'headers' => [
5996 - 'Content-Type' => 'application/json',
5997 - 'Authorization' => 'Bearer ' . $slack_bot_token
5998 - ],
5999 - 'body' => json_encode([
6000 - 'channel' => $channel_id,
6001 - 'text' => "✅ _Message sent to user_",
6002 - 'thread_ts' => $thread_root
6003 - ])
6004 - ]);
6005 - set_transient($confirm_key, true, 300);
6006 - }
6007 - }
6008 -
6009 - return new WP_REST_Response(['ok' => true]);
6010 -}
6011 -
6012 -// For the word upload handler
6013 -public function mxchat_handle_word_upload() {
6014 - // Delegate to word handler
6015 - $this->word_handler->mxchat_handle_word_upload();
6016 -}
6017 -
6018 -// For the word removal handler
6019 -public function mxchat_handle_word_remove() {
6020 - // Delegate to word handler
6021 - $this->word_handler->mxchat_handle_word_remove();
6022 -}
6023 -
6024 -// For the word status check
6025 -public function mxchat_check_word_status() {
6026 - // Delegate to word handler
6027 - $this->word_handler->mxchat_check_word_status();
6028 -}
6029 -
6030 -
6031 -private function mxchat_get_user_identifier() {
6032 - return MxChat_User::mxchat_get_user_identifier();
6033 -}
6034 -
6035 -private function mxchat_generate_embedding($text, $api_key) {
6036 - try {
6037 - // Get options and selected model
6038 - $options = get_option('mxchat_options');
6039 - $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
6040 -
6041 - // Contract checks live HERE — the widget surfaces these exact strings
6042 - // and codes. Transport lives in MxChat_Utils::generate_query_embedding()
6043 - // (single provider-routing implementation for query + index, 876edb).
6044 - // The custom-provider branch skips them: Utils routes custom-first and
6045 - // its own checks map back through mxchat_map_embedding_error().
6046 - if (empty($options['custom_provider_for_embeddings']) || $options['custom_provider_for_embeddings'] !== 'on') {
6047 - if (strpos($selected_model, 'voyage') === 0) {
6048 - // Check if Voyage API key is missing
6049 - if (empty($options['voyage_api_key'] ?? '')) {
6050 - return [
6051 - 'error' => esc_html__('Voyage AI API key is not configured', 'mxchat'),
6052 - 'error_code' => 'missing_voyage_api_key'
6053 - ];
6054 - }
6055 - } elseif (strpos($selected_model, 'gemini-embedding') === 0) {
6056 - // Check if Gemini API key is missing
6057 - if (empty($options['gemini_api_key'] ?? '')) {
6058 - return [
6059 - 'error' => esc_html__('Google Gemini API key is not configured', 'mxchat'),
6060 - 'error_code' => 'missing_gemini_api_key'
6061 - ];
6062 - }
6063 - } else {
6064 - // OpenAI uses the caller-passed (per-bot) key
6065 - if (empty($api_key)) {
6066 - return [
6067 - 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
6068 - 'error_code' => 'missing_openai_api_key'
6069 - ];
6070 - }
6071 - }
6072 -
6073 - // Check if text is empty
6074 - if (empty($text)) {
6075 - return [
6076 - 'error' => esc_html__('No text provided for embedding generation', 'mxchat'),
6077 - 'error_code' => 'empty_embedding_text'
6078 - ];
6079 - }
6080 - }
6081 -
6082 - $result = MxChat_Utils::generate_query_embedding($text, $api_key);
6083 -
6084 - if (is_wp_error($result)) {
6085 - return $this->mxchat_map_embedding_error($result);
6086 - }
6087 -
6088 - return $result;
6089 - } catch (Exception $e) {
6090 - //error_log('Embedding Exception: ' . $e->getMessage());
6091 - return [
6092 - 'error' => esc_html__('System error when generating embeddings: ', 'mxchat') . esc_html($e->getMessage()),
6093 - 'error_code' => 'embedding_exception'
6094 - ];
6095 - }
6096 -}
6097 -
6098 -/**
6099 - * Translate a WP_Error from MxChat_Utils::generate_query_embedding() into this
6100 - * class's long-standing ['error','error_code'] contract. Every code string and
6101 - * user-facing message below predates 876edb — the chat pipeline and widget
6102 - * consume them; preserve verbatim. The structured data (branch/status/
6103 - * error_type/reason/model) is attached by Utils on every failure path.
6104 - */
6105 -private function mxchat_map_embedding_error($err) {
6106 - $data = $err->get_error_data();
6107 - $data = is_array($data) ? $data : [];
6108 - $message = $err->get_error_message();
6109 -
6110 - // Custom-provider branch: Utils carries the human-readable string verbatim;
6111 - // its prefixes are stable — map them back onto the existing codes.
6112 - if (($data['branch'] ?? '') === 'custom') {
6113 - if ($message === 'No text provided for embedding generation') {
6114 - return ['error' => esc_html__('No text provided for embedding generation', 'mxchat'), 'error_code' => 'empty_embedding_text'];
6115 - }
6116 - if ($message === 'Custom provider Base URL is not configured.') {
6117 - return ['error' => esc_html__('Custom provider Base URL is not configured.', 'mxchat'), 'error_code' => 'missing_custom_provider_base_url'];
6118 - }
6119 - if (strpos($message, 'Connection error when generating embeddings (custom provider): ') === 0) {
6120 - return ['error' => esc_html($message), 'error_code' => 'embedding_custom_connection_error'];
6121 - }
6122 - if (strpos($message, 'Custom embedding endpoint error: ') === 0) {
6123 - return ['error' => esc_html($message), 'error_code' => 'embedding_custom_api_error'];
6124 - }
6125 - return ['error' => esc_html__('Invalid embedding response from custom provider.', 'mxchat'), 'error_code' => 'embedding_custom_invalid_response'];
6126 - }
6127 -
6128 - // Cloud connection failure (wp_remote_post WP_Error)
6129 - if (($data['kind'] ?? '') === 'connection') {
6130 - return [
6131 - 'error' => esc_html__('Connection error when generating embeddings: ', 'mxchat') . esc_html($data['reason'] ?? ''),
6132 - 'error_code' => 'embedding_connection_error'
6133 - ];
6134 - }
6135 -
6136 - $status = isset($data['status']) ? (int) $data['status'] : 0;
6137 - $error_type = isset($data['error_type']) ? (string) $data['error_type'] : '';
6138 - $reason = isset($data['reason']) ? (string) $data['reason'] : $message;
6139 - $model = isset($data['model']) ? (string) $data['model'] : '';
6140 -
6141 - // HTTP 200 with an unusable body — the invalid-response shapes.
6142 - if ($status === 200) {
6143 - if (strpos($model, 'gemini-embedding') === 0) {
6144 - return ['error' => esc_html__('Received invalid embedding data from the Gemini API.', 'mxchat'), 'error_code' => 'invalid_gemini_embedding_response'];
6145 - }
6146 - return ['error' => esc_html__('Received invalid embedding data from the API.', 'mxchat'), 'error_code' => 'invalid_embedding_response'];
6147 - }
6148 -
6149 - // Handle specific error types
6150 - switch ($error_type) {
6151 - case 'invalid_request_error':
6152 - if (strpos($reason, 'API key') !== false) {
6153 - return [
6154 - 'error' => esc_html__('Invalid API key for embedding generation. Please check your API key configuration.', 'mxchat'),
6155 - 'error_code' => 'embedding_invalid_api_key'
6156 - ];
6157 - }
6158 - break;
6159 -
6160 - case 'authentication_error':
6161 - return [
6162 - 'error' => esc_html__('Authentication failed for embedding generation. Please check your API key.', 'mxchat'),
6163 - 'error_code' => 'embedding_auth_error'
6164 - ];
6165 -
6166 - case 'rate_limit_exceeded':
6167 - return [
6168 - 'error' => esc_html__('Rate limit exceeded for embedding generation. Please try again later.', 'mxchat'),
6169 - 'error_code' => 'embedding_rate_limit'
6170 - ];
6171 -
6172 - case 'quota_exceeded':
6173 - return [
6174 - 'error' => esc_html__('API quota exceeded for embedding generation. Please check your billing details.', 'mxchat'),
6175 - 'error_code' => 'embedding_quota_exceeded'
6176 - ];
6177 - }
6178 -
6179 - // Generic error fallback
6180 - return [
6181 - 'error' => esc_html__('Embedding API error - check embedding API key.: ', 'mxchat') . esc_html($reason),
6182 - 'error_code' => 'embedding_api_error',
6183 - 'status_code' => $status
6184 - ];
6185 -}
6186 -
6187 -private function mxchat_find_relevant_content($user_embedding, $bot_id = 'default', $user_query = '') {
6188 - //error_log("MXCHAT DEBUG: find_relevant_content called with bot_id: " . $bot_id);
6189 -
6190 - // Check for OpenAI Vector Store first (takes priority when enabled)
6191 - $bot_vectorstore_config = $this->get_bot_vectorstore_config($bot_id);
6192 -
6193 - if ($bot_vectorstore_config['use_vectorstore']) {
6194 - // Get current model to verify it's an OpenAI model
6195 - $bot_options = $this->get_bot_options($bot_id);
6196 - $mxchat_options = get_option('mxchat_options', array());
6197 - $current_options = !empty($bot_options) ? $bot_options : $mxchat_options;
6198 - $selected_model = $current_options['model'] ?? 'gpt-5.6-sol';
6199 -
6200 - if ($this->is_openai_chat_model($selected_model)) {
6201 - //error_log("MXCHAT DEBUG: Using OpenAI Vector Store for knowledge retrieval");
6202 - return $this->find_relevant_content_openai_vectorstore($user_query, $bot_id, $bot_vectorstore_config);
6203 - } else {
6204 - //error_log("MXCHAT DEBUG: Vector Store enabled but model is not OpenAI (" . $selected_model . "), skipping Vector Store");
6205 - }
6206 - }
6207 -
6208 - // Get bot-specific Pinecone configuration
6209 - $bot_pinecone_config = $this->get_bot_pinecone_config($bot_id);
6210 -
6211 - // Debug: Log the Pinecone configuration
6212 - //error_log("MXCHAT DEBUG: Pinecone config for bot '$bot_id':");
6213 - //error_log(" - use_pinecone: " . ($bot_pinecone_config['use_pinecone'] ? 'true' : 'false'));
6214 - //error_log(" - api_key: " . (empty($bot_pinecone_config['api_key']) ? 'EMPTY' : 'SET (hidden)'));
6215 - //error_log(" - host: " . ($bot_pinecone_config['host'] ?? 'NOT SET'));
6216 - //error_log(" - namespace: " . ($bot_pinecone_config['namespace'] ?? 'NOT SET'));
6217 -
6218 - // Determine whether to use Pinecone based on bot configuration
6219 - $use_pinecone = isset($bot_pinecone_config['use_pinecone']) ? $bot_pinecone_config['use_pinecone'] : false;
6220 -
6221 - //error_log("MXCHAT DEBUG: Using " . ($use_pinecone ? "Pinecone" : "WordPress Database") . " for knowledge retrieval");
6222 -
6223 - if ($use_pinecone) {
6224 - return $this->find_relevant_content_pinecone($user_embedding, $bot_id, $bot_pinecone_config);
6225 - } else {
6226 - return $this->find_relevant_content_wordpress($user_embedding, $bot_id, $user_query);
6227 - }
6228 -}
6229 -
6230 -private function find_relevant_content_wordpress($user_embedding, $bot_id = 'default', $user_query = '') {
6231 - global $wpdb;
6232 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
6233 - // Initialize similarity analysis storage
6234 - $this->last_similarity_analysis = [
6235 - 'knowledge_base_type' => 'WordPress Database',
6236 - 'bot_id' => $bot_id,
6237 - 'top_matches' => [],
6238 - 'threshold_used' => 0,
6239 - 'total_checked' => 0
6240 - ];
6241 -
6242 - // NEW: Initialize valid URLs array
6243 - $valid_urls = [];
6244 -
6245 - // Get bot-specific options for similarity threshold
6246 - $bot_options = $this->get_bot_options($bot_id);
6247 - $current_options = !empty($bot_options) ? $bot_options : $this->options;
6248 -
6249 - // Get knowledge manager instance for role checking
6250 - $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
6251 -
6252 - // Get base similarity threshold from bot options or default options
6253 - $similarity_threshold = isset($current_options['similarity_threshold'])
6254 - ? ((int) $current_options['similarity_threshold']) / 100
6255 - : 0.35;
6256 - $this->last_similarity_analysis['threshold_used'] = $similarity_threshold;
6257 -
6258 - // Precompute bot_filter once, outside the streaming loop
6259 - $bot_filter = '';
6260 - if ($bot_id !== 'default') {
6261 - $column_exists = $wpdb->get_var("SHOW COLUMNS FROM {$system_prompt_table} LIKE 'bot_metadata'");
6262 - if ($column_exists) {
6263 - $bot_filter = $wpdb->prepare(" AND (bot_metadata = %s OR bot_metadata IS NULL OR bot_metadata = '')", $bot_id);
6264 - }
6265 - }
6266 -
6267 - // Hybrid keyword boost (plan-38ffa1, default OFF). Runs a ranked keyword
6268 - // query alongside the vector scan and fuses the two lists by reciprocal
6269 - // rank, so exact-token queries (SKUs, error codes, names) hit even when
6270 - // their embedding similarity is semantic mush. The keyword leg runs FIRST
6271 - // so the vector scan below can record true cosine similarity for its hits
6272 - // (the display keeps cosine % as the anchor).
6273 - $hybrid_enabled = get_option('mxchat_hybrid_keyword_toggle', 'off') === 'on'
6274 - && trim((string) $user_query) !== '';
6275 - $keyword_hits = array(); // ranked + access-filtered, max 20
6276 - $keyword_ids = array(); // id => keyword rank (1-based)
6277 - $keyword_similarities = array(); // id => cosine recorded during the scan
6278 - if ($hybrid_enabled) {
6279 - $keyword_hits = $this->mxchat_hybrid_keyword_search($user_query, $system_prompt_table, $bot_filter, $knowledge_manager);
6280 - foreach ($keyword_hits as $kw_i => $kw_hit) {
6281 - $keyword_ids[$kw_hit['id']] = $kw_i + 1;
6282 - }
6283 - }
6284 -
6285 - // ===== STREAMING TOP-K PASS =====
6286 - // Stream rows in small batches, compute cosine similarity per row, and keep only:
6287 - // - top 10 by raw similarity (for the testing/debug display panel)
6288 - // - candidates above threshold with access (capped) for context assembly
6289 - // This bounds peak memory regardless of knowledge base size and avoids loading
6290 - // article_content for every row. article_content is fetched in Phase 2 for winners only.
6291 - $batch_size = 250;
6292 - $max_candidates = 200; // safety cap, well above rag_sources_limit * max_chunks_per_source
6293 - $top_display = [];
6294 - $candidates = [];
6295 - $total_checked = 0;
6296 - $offset = 0;
6297 -
6298 - do {
6299 - $batch = $wpdb->get_results($wpdb->prepare(
6300 - "SELECT id, embedding_vector, source_url, role_restriction
6301 - FROM {$system_prompt_table}
6302 - WHERE 1=1 {$bot_filter}
6303 - LIMIT %d OFFSET %d",
6304 - $batch_size,
6305 - $offset
6306 - ));
6307 -
6308 - if (empty($batch)) {
6309 - break;
6310 - }
6311 -
6312 - foreach ($batch as $row) {
6313 - $database_embedding = $row->embedding_vector
6314 - ? unserialize($row->embedding_vector, ['allowed_classes' => false])
6315 - : null;
6316 -
6317 - if (!is_array($database_embedding) || !is_array($user_embedding)) {
6318 - unset($database_embedding);
6319 - continue;
6320 - }
6321 -
6322 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
6323 - unset($database_embedding);
6324 -
6325 - $role_restriction = $row->role_restriction ?? 'public';
6326 - $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
6327 - $source_url = $row->source_url ?? '';
6328 -
6329 - // Maintain top 10 display buffer (insert-if-beats-worst)
6330 - if (count($top_display) < 10) {
6331 - $top_display[] = [
6332 - 'id' => $row->id,
6333 - 'similarity' => $similarity,
6334 - 'source_url' => $source_url,
6335 - 'role_restriction' => $role_restriction,
6336 - 'has_access' => $has_access,
6337 - ];
6338 - usort($top_display, function ($a, $b) {
6339 - return $b['similarity'] <=> $a['similarity'];
6340 - });
6341 - } elseif ($similarity > $top_display[9]['similarity']) {
6342 - $top_display[9] = [
6343 - 'id' => $row->id,
6344 - 'similarity' => $similarity,
6345 - 'source_url' => $source_url,
6346 - 'role_restriction' => $role_restriction,
6347 - 'has_access' => $has_access,
6348 - ];
6349 - usort($top_display, function ($a, $b) {
6350 - return $b['similarity'] <=> $a['similarity'];
6351 - });
6352 - }
6353 -
6354 - // Record cosine for keyword-leg hits so fusion/display can anchor
6355 - // on the true similarity % even for below-threshold rescues.
6356 - if ($hybrid_enabled && isset($keyword_ids[$row->id])) {
6357 - $keyword_similarities[$row->id] = $similarity;
6358 - }
6359 -
6360 - // Track candidates for context assembly (above threshold + has access)
6361 - if ($similarity >= $similarity_threshold && $has_access) {
6362 - $candidates[] = [
6363 - 'id' => $row->id,
6364 - 'similarity' => $similarity,
6365 - 'source_url' => $source_url,
6366 - ];
6367 - }
6368 -
6369 - $total_checked++;
6370 - }
6371 -
6372 - unset($batch);
6373 -
6374 - // Trim candidates periodically to cap memory during long scans
6375 - if (count($candidates) > $max_candidates) {
6376 - usort($candidates, function ($a, $b) {
6377 - return $b['similarity'] <=> $a['similarity'];
6378 - });
6379 - $candidates = array_slice($candidates, 0, $max_candidates);
6380 - }
6381 -
6382 - $offset += $batch_size;
6383 - } while (true);
6384 -
6385 - if ($total_checked === 0) {
6386 - $this->current_valid_urls = [];
6387 - return '';
6388 - }
6389 -
6390 - // Final candidates sort (best first)
6391 - if (count($candidates) > 1) {
6392 - usort($candidates, function ($a, $b) {
6393 - return $b['similarity'] <=> $a['similarity'];
6394 - });
6395 - }
6396 -
6397 - // ===== HYBRID FUSION (plan-38ffa1) =====
6398 - // Reciprocal-rank fusion over the top-20 of each leg (k=60 standard).
6399 - // Rank-based, so the incomparable score scales (cosine 0-1 vs FULLTEXT
6400 - // relevance) never need calibrating. A below-threshold vector row can
6401 - // enter via a strong keyword rank — that is the point of the feature.
6402 - // Every candidate gets a 'rank_score' the downstream source ordering
6403 - // uses: with hybrid OFF it is exactly the cosine similarity, so the
6404 - // legacy path is byte-identical.
6405 - $fused_rank_map = array(); // id => 1-based fused rank
6406 - $matched_via_map = array(); // id => 'vector' | 'keyword' | 'both'
6407 - if (!$hybrid_enabled) {
6408 - foreach ($candidates as &$cand_ref) {
6409 - $cand_ref['rank_score'] = $cand_ref['similarity'];
6410 - }
6411 - unset($cand_ref);
6412 - } else {
6413 - $rrf_k = 60;
6414 - $fused = array();
6415 - foreach (array_slice($candidates, 0, 20) as $leg_rank => $cand) {
6416 - $fused[$cand['id']] = array(
6417 - 'id' => $cand['id'],
6418 - 'similarity' => $cand['similarity'],
6419 - 'source_url' => $cand['source_url'],
6420 - 'rrf' => 1 / ($rrf_k + $leg_rank + 1),
6421 - 'via' => 'vector',
6422 - );
6423 - }
6424 - foreach ($keyword_hits as $leg_rank => $hit) {
6425 - $rrf = 1 / ($rrf_k + $leg_rank + 1);
6426 - if (isset($fused[$hit['id']])) {
6427 - $fused[$hit['id']]['rrf'] += $rrf;
6428 - $fused[$hit['id']]['via'] = 'both';
6429 - } else {
6430 - $fused[$hit['id']] = array(
6431 - 'id' => $hit['id'],
6432 - 'similarity' => $keyword_similarities[$hit['id']] ?? 0.0,
6433 - 'source_url' => $hit['source_url'],
6434 - 'rrf' => $rrf,
6435 - 'via' => 'keyword',
6436 - );
6437 - }
6438 - }
6439 - uasort($fused, function ($a, $b) {
6440 - return $b['rrf'] <=> $a['rrf'];
6441 - });
6442 -
6443 - // Vector candidates beyond the top-20 leg keep flowing to the prompt
6444 - // builders after the fused block, in their vector order — the result
6445 - // count/shape downstream stays unchanged.
6446 - $tail = array_slice($candidates, 20);
6447 - $candidates = array();
6448 - $rank = 0;
6449 - foreach ($fused as $f) {
6450 - $rank++;
6451 - $fused_rank_map[$f['id']] = $rank;
6452 - $matched_via_map[$f['id']] = $f['via'];
6453 - $candidates[] = array(
6454 - 'id' => $f['id'],
6455 - 'similarity' => $f['similarity'],
6456 - 'source_url' => $f['source_url'],
6457 - 'rank_score' => $f['rrf'],
6458 - );
6459 - }
6460 - foreach ($tail as $cand) {
6461 - // Below any fused rrf (min possible fused rrf is 1/(60+40)=0.01;
6462 - // similarity * 1e-6 <= 1e-6), preserving relative vector order.
6463 - $cand['rank_score'] = $cand['similarity'] * 1e-6;
6464 - $candidates[] = $cand;
6465 - }
6466 - if (count($candidates) > $max_candidates) {
6467 - $candidates = array_slice($candidates, 0, $max_candidates);
6468 - }
6469 - }
6470 -
6471 - // ===== PHASE 2: FETCH ARTICLE CONTENT ONLY FOR WINNERS =====
6472 - // Gather unique IDs we actually need (top_display + candidates) and pull
6473 - // article_content in bounded IN() batches. This avoids loading content for
6474 - // every row during the similarity scan.
6475 - $needed_ids = [];
6476 - foreach ($top_display as $item) {
6477 - $needed_ids[$item['id']] = true;
6478 - }
6479 - foreach ($candidates as $item) {
6480 - $needed_ids[$item['id']] = true;
6481 - }
6482 - $needed_ids = array_keys($needed_ids);
6483 -
6484 - $content_map = [];
6485 - if (!empty($needed_ids)) {
6486 - foreach (array_chunk($needed_ids, 250) as $chunk_ids) {
6487 - $placeholders = implode(',', array_fill(0, count($chunk_ids), '%d'));
6488 - $rows = $wpdb->get_results($wpdb->prepare(
6489 - "SELECT id, article_content FROM {$system_prompt_table} WHERE id IN ($placeholders)",
6490 - ...$chunk_ids
6491 - ));
6492 - foreach ($rows as $r) {
6493 - $content_map[$r->id] = $r->article_content;
6494 - }
6495 - unset($rows);
6496 - }
6497 - }
6498 -
6499 - // Build the all_similarities display array from the top 10
6500 - $all_similarities = [];
6501 - foreach ($top_display as $item) {
6502 - $article_content_for_parse = $content_map[$item['id']] ?? '';
6503 - $parsed_for_display = MxChat_Chunker::parse_stored_chunk($article_content_for_parse);
6504 - $is_chunk = $parsed_for_display['is_chunked'];
6505 - $chunk_meta = $parsed_for_display['metadata'];
6506 -
6507 - if (!empty($item['source_url']) && $item['source_url'] !== '#') {
6508 - $source_display = $item['source_url'];
6509 - } else {
6510 - $content_preview = strip_tags($article_content_for_parse);
6511 - $content_preview = preg_replace('/\s+/', ' ', $content_preview);
6512 - $source_display = substr(trim($content_preview), 0, 50) . '...';
6513 - }
6514 -
6515 - $all_similarities[] = [
6516 - 'document_id' => $item['id'],
6517 - 'similarity' => $item['similarity'],
6518 - 'similarity_percentage' => round($item['similarity'] * 100, 2),
6519 - 'above_threshold' => $item['similarity'] >= $similarity_threshold,
6520 - 'source_display' => $source_display,
6521 - 'content_preview' => substr(strip_tags($parsed_for_display['text'] ?? ''), 0, 100) . '...',
6522 - 'used_for_context' => false,
6523 - 'role_restriction' => $item['role_restriction'],
6524 - 'has_access' => $item['has_access'],
6525 - 'filtered_out' => !$item['has_access'],
6526 - 'is_chunk' => $is_chunk,
6527 - 'chunk_index' => $is_chunk ? ($chunk_meta['chunk_index'] ?? 0) : null,
6528 - 'total_chunks' => $is_chunk ? ($chunk_meta['total_chunks'] ?? 1) : null
6529 - ];
6530 - }
6531 -
6532 - // Build url_groups from candidates for chunk reassembly
6533 - $url_groups = array();
6534 - foreach ($candidates as $cand) {
6535 - $article_content = $content_map[$cand['id']] ?? '';
6536 - $parsed = MxChat_Chunker::parse_stored_chunk($article_content);
6537 - $is_chunked = $parsed['is_chunked'];
6538 - $chunk_index = $parsed['metadata']['chunk_index'] ?? 0;
6539 - $text_content = $parsed['text'];
6540 -
6541 - $source_url = $cand['source_url'];
6542 - $group_key = !empty($source_url) ? $source_url : '_manual_' . $cand['id'];
6543 -
6544 - if (!isset($url_groups[$group_key])) {
6545 - $url_groups[$group_key] = array(
6546 - 'source_url' => $source_url,
6547 - 'best_score' => 0,
6548 - 'best_similarity' => 0,
6549 - 'is_chunked' => $is_chunked,
6550 - 'chunks' => array(),
6551 - 'single_text' => '',
6552 - 'single_id' => null
6553 - );
6554 - }
6555 -
6556 - // rank_score == similarity with hybrid off (byte-identical ordering);
6557 - // with hybrid on it carries the fused rank so keyword rescues sort up.
6558 - $cand_rank_score = $cand['rank_score'] ?? $cand['similarity'];
6559 - if ($cand_rank_score > $url_groups[$group_key]['best_score']) {
6560 - $url_groups[$group_key]['best_score'] = $cand_rank_score;
6561 - }
6562 -
6563 - // best_similarity is the group's true COSINE, tracked separately from
6564 - // best_score because the two diverge the moment hybrid fusion is on
6565 - // (best_score becomes an RRF rank). Only consumers that need a real
6566 - // 0-1 confidence read this — today the video-card floor (f52492).
6567 - // Ordering is untouched: best_score still decides it.
6568 - $cand_similarity = (float) ($cand['similarity'] ?? 0);
6569 - if ($cand_similarity > $url_groups[$group_key]['best_similarity']) {
6570 - $url_groups[$group_key]['best_similarity'] = $cand_similarity;
6571 - }
6572 -
6573 - if ($is_chunked) {
6574 - $url_groups[$group_key]['is_chunked'] = true;
6575 - $url_groups[$group_key]['chunks'][] = array(
6576 - 'id' => $cand['id'],
6577 - 'score' => $cand['similarity'],
6578 - 'chunk_index' => $chunk_index,
6579 - 'text' => $text_content
6580 - );
6581 - } else {
6582 - $url_groups[$group_key]['single_text'] = $text_content;
6583 - $url_groups[$group_key]['single_id'] = $cand['id'];
6584 - }
6585 - }
6586 -
6587 - // Hybrid display augmentation (plan-38ffa1, Maxwell's approval note):
6588 - // make sure every fused-top-10 row appears in the debug panel — a
6589 - // keyword-only rescue may sit below the vector top-10 buffer — and stamp
6590 - // matched_via + fused_rank on every row. Cosine % stays the anchor; no
6591 - // raw RRF numbers surface.
6592 - if ($hybrid_enabled) {
6593 - $displayed_ids = array();
6594 - foreach ($all_similarities as $disp_item) {
6595 - $displayed_ids[$disp_item['document_id']] = true;
6596 - }
6597 - $kw_info_by_id = array();
6598 - foreach ($keyword_hits as $hit) {
6599 - $kw_info_by_id[$hit['id']] = $hit;
6600 - }
6601 - foreach ($fused_rank_map as $fused_id => $fused_rank) {
6602 - if ($fused_rank > 10 || isset($displayed_ids[$fused_id])) {
6603 - continue;
6604 - }
6605 - $aug_content = $content_map[$fused_id] ?? '';
6606 - $aug_parsed = MxChat_Chunker::parse_stored_chunk($aug_content);
6607 - $aug_hit = $kw_info_by_id[$fused_id] ?? array();
6608 - $aug_similarity = $keyword_similarities[$fused_id] ?? 0.0;
6609 - $aug_source_url = $aug_hit['source_url'] ?? '';
6610 - if (!empty($aug_source_url) && $aug_source_url !== '#') {
6611 - $aug_source_display = $aug_source_url;
6612 - } else {
6613 - $aug_preview = preg_replace('/\s+/', ' ', strip_tags($aug_content));
6614 - $aug_source_display = substr(trim($aug_preview), 0, 50) . '...';
6615 - }
6616 - $all_similarities[] = [
6617 - 'document_id' => $fused_id,
6618 - 'similarity' => $aug_similarity,
6619 - 'similarity_percentage' => round($aug_similarity * 100, 2),
6620 - 'above_threshold' => $aug_similarity >= $similarity_threshold,
6621 - 'source_display' => $aug_source_display,
6622 - 'content_preview' => substr(strip_tags($aug_parsed['text'] ?? ''), 0, 100) . '...',
6623 - 'used_for_context' => false,
6624 - 'role_restriction' => $aug_hit['role_restriction'] ?? 'public',
6625 - 'has_access' => $aug_hit['has_access'] ?? true,
6626 - 'filtered_out' => false,
6627 - 'is_chunk' => $aug_parsed['is_chunked'],
6628 - 'chunk_index' => $aug_parsed['is_chunked'] ? ($aug_parsed['metadata']['chunk_index'] ?? 0) : null,
6629 - 'total_chunks' => $aug_parsed['is_chunked'] ? ($aug_parsed['metadata']['total_chunks'] ?? 1) : null,
6630 - ];
6631 - }
6632 - foreach ($all_similarities as &$disp_ref) {
6633 - $disp_ref['matched_via'] = $matched_via_map[$disp_ref['document_id']] ?? null;
6634 - $disp_ref['fused_rank'] = $fused_rank_map[$disp_ref['document_id']] ?? null;
6635 - }
6636 - unset($disp_ref);
6637 - }
6638 -
6639 - // Sort for the testing/debug display: fused rank when hybrid is on
6640 - // (nulls last, cosine as tie-break), raw similarity otherwise.
6641 - if ($hybrid_enabled) {
6642 - usort($all_similarities, function ($a, $b) {
6643 - $ar = $a['fused_rank'] ?? PHP_INT_MAX;
6644 - $br = $b['fused_rank'] ?? PHP_INT_MAX;
6645 - if ($ar !== $br) {
6646 - return $ar <=> $br;
6647 - }
6648 - return $b['similarity'] <=> $a['similarity'];
6649 - });
6650 - } else {
6651 - usort($all_similarities, function ($a, $b) {
6652 - return $b['similarity'] <=> $a['similarity'];
6653 - });
6654 - }
6655 -
6656 - // Sort URL groups by best score (highest first)
6657 - uasort($url_groups, function($a, $b) {
6658 - return $b['best_score'] <=> $a['best_score'];
6659 - });
6660 -
6661 - // Get RAG sources limit from options (default 6, min 3, max 10)
6662 - $rag_sources_limit = isset($current_options['rag_sources_limit']) ? intval($current_options['rag_sources_limit']) : 3;
6663 - if ($rag_sources_limit < 3) $rag_sources_limit = 3;
6664 - if ($rag_sources_limit > 10) $rag_sources_limit = 10;
6665 -
6666 - // Take top N unique URLs based on user setting
6667 - $top_urls = array_slice($url_groups, 0, $rag_sources_limit, true);
6668 -
6669 - // Track which document IDs are used for context
6670 - $used_document_ids = [];
6671 - foreach ($top_urls as $group) {
6672 - if ($group['is_chunked']) {
6673 - foreach ($group['chunks'] as $chunk) {
6674 - $used_document_ids[] = $chunk['id'];
6675 - }
6676 - } elseif ($group['single_id']) {
6677 - $used_document_ids[] = $group['single_id'];
6678 - }
6679 - }
6680 -
6681 - // Update the all_similarities array to mark which were actually used
6682 - foreach ($all_similarities as &$similarity_item) {
6683 - $similarity_item['used_for_context'] = in_array($similarity_item['document_id'], $used_document_ids);
6684 - }
6685 -
6686 - // Store top 10 for testing panel
6687 - $this->last_similarity_analysis['top_matches'] = array_slice($all_similarities, 0, 10);
6688 - $this->last_similarity_analysis['total_checked'] = $total_checked;
6689 -
6690 - // Initialize final content
6691 - $content = '';
6692 - $matches_used = 0;
6693 - $total_chunks_used = 0;
6694 - $max_total_chunks = isset($current_options['rag_chunks_limit']) ? intval($current_options['rag_chunks_limit']) : 15;
6695 - if ($max_total_chunks < 8) $max_total_chunks = 8;
6696 - if ($max_total_chunks > 20) $max_total_chunks = 20;
6697 - $max_chunks_per_source = 5; // Cap per individual source to limit token usage
6698 -
6699 - // Check if citation links are enabled (default to 'on' for backwards compatibility)
6700 - // Use fresh options to ensure we get the latest setting value
6701 - $fresh_options = get_option('mxchat_options', []);
6702 - $citation_links_enabled = isset($fresh_options['citation_links_toggle']) ? ($fresh_options['citation_links_toggle'] === 'on') : true;
6703 -
6704 - // Build content from top sources
6705 - foreach ($top_urls as $group_key => $group) {
6706 - $source_url = $group['source_url']; // Use actual source_url, not the group key
6707 -
6708 - // Stop if we've hit the total chunk limit
6709 - if ($total_chunks_used >= $max_total_chunks) {
6710 - break;
6711 - }
6712 -
6713 - $full_text = '';
6714 - $chunks_in_this_source = 1; // Default for non-chunked content
6715 -
6716 - if ($group['is_chunked']) {
6717 - // Calculate how many chunks we can still use (respect both total and per-source caps)
6718 - $chunks_remaining = min($max_chunks_per_source, $max_total_chunks - $total_chunks_used);
6719 -
6720 - // Fetch chunks for this URL with limit
6721 - $full_text = $this->reassemble_chunks_from_wordpress($source_url, $chunks_remaining, $chunks_in_this_source);
6722 -
6723 - // If fetching all chunks fails, fall back to matched chunks
6724 - if (empty($full_text)) {
6725 - // Sort matched chunks by index and concatenate
6726 - usort($group['chunks'], function($a, $b) {
6727 - return $a['chunk_index'] <=> $b['chunk_index'];
6728 - });
6729 -
6730 - $chunk_texts = array();
6731 - $chunks_in_this_source = 0;
6732 - foreach ($group['chunks'] as $chunk) {
6733 - if ($total_chunks_used + $chunks_in_this_source >= $max_total_chunks) {
6734 - break;
6735 - }
6736 - $chunk_texts[] = $chunk['text'];
6737 - $chunks_in_this_source++;
6738 - }
6739 - $full_text = implode("\n\n", $chunk_texts);
6740 - }
6741 - } else {
6742 - $full_text = $group['single_text'];
6743 - $chunks_in_this_source = 1;
6744 - }
6745 -
6746 - if (!empty($full_text)) {
6747 - // Strip URLs from content if citation links are disabled
6748 - if (!$citation_links_enabled) {
6749 - $full_text = preg_replace('#\bhttps?://[^\s<>"\']+#i', '', $full_text);
6750 - $full_text = preg_replace('/\s+/', ' ', trim($full_text)); // Clean up extra spaces
6751 - }
6752 -
6753 - // Use numbered reference for URL-based entries, plain info label for manual entries
6754 - // Manual entries are stored with an internal mxchat:// placeholder URL — never expose them as citations
6755 - if (!empty($source_url) && $source_url !== '#' && strpos($source_url, 'mxchat://') !== 0) {
6756 - $matches_used++;
6757 - $content .= "## Reference " . $matches_used . " ##\n";
6758 - $content .= $full_text . "\n\n";
6759 -
6760 - // Only include citation URLs if citation links are enabled
6761 - if ($citation_links_enabled) {
6762 - $valid_urls[] = $source_url;
6763 - $content .= "URL: " . $source_url . "\n\n";
6764 - }
6765 -
6766 - // Video-backed source → queue the consent-safe embed (03ba33),
6767 - // subject to the card's own confidence floor (f52492). Pass the
6768 - // group's true cosine, NOT best_score — see the gate's docblock.
6769 - $this->maybe_queue_youtube_embed($source_url, $full_text, $group['best_similarity'] ?? null);
6770 - } else {
6771 - // Manual entry — no reference number, no citation
6772 - $content .= "## Information ##\n";
6773 - $content .= $full_text . "\n\n";
6774 - }
6775 -
6776 - // Extract any URLs from the text content itself (only if citation links enabled)
6777 - if ($citation_links_enabled) {
6778 - preg_match_all(
6779 - '#\bhttps?://[^\s<>"\']+#i',
6780 - $full_text,
6781 - $content_urls
6782 - );
6783 - if (!empty($content_urls[0])) {
6784 - $valid_urls = array_merge($valid_urls, $content_urls[0]);
6785 - }
6786 - }
6787 -
6788 - $total_chunks_used += $chunks_in_this_source;
6789 - }
6790 - }
6791 -
6792 - // NEW: Store unique valid URLs for validation
6793 - $this->current_valid_urls = array_unique($valid_urls);
6794 -
6795 - // Store sources and chunks counts for testing/transcript display
6796 - $this->last_similarity_analysis['sources_used'] = $matches_used;
6797 - $this->last_similarity_analysis['total_chunks_used'] = $total_chunks_used;
6798 -
6799 - // Allow add-ons to act on similarity results (e.g. WooCommerce product card display)
6800 - do_action('mxchat_similarity_results', $this->last_similarity_analysis['top_matches'], $bot_id);
6801 -
6802 - // Add response guidelines
6803 - if (empty($top_urls)) {
6804 - // No matched sources: return empty so the prompt assembler's
6805 - // "NO RELEVANT CONTENT FOUND IN KNOWLEDGE DATABASE" branch fires —
6806 - // a no-info sentence wrapped in OFFICIAL KNOWLEDGE markers reads to
6807 - // the model as authoritative content (plan d7daf8).
6808 - $content = '';
6809 - } else {
6810 - // Build response guidelines based on citation links setting
6811 - $content .= "\n## Response Guidelines ##\n" .
6812 - "You are an AI Chatbot. Answer naturally and helpfully using only the information from the references above. " .
6813 - "Be conversational and friendly, but never mention your knowledge base or training data. " .
6814 - "If you don't have specific information or are uncertain about any details, it's always " .
6815 - "better to honestly say you don't know rather than making up or guessing at answers. " .
6816 - "When information is incomplete, let them know you are unsure.\n\n";
6817 -
6818 - // Only add hyperlink instructions if citation links are enabled
6819 - if ($citation_links_enabled) {
6820 - $content .= "CRITICAL: When creating hyperlinks, always use proper markdown format with descriptive text: " .
6821 - "[descriptive text](url). NEVER use empty brackets like [](url). The text in brackets must describe what the link is about. " .
6822 - "Only cite references that have a URL. Do not cite or add source labels to Information sections that have no URL.";
6823 - } else {
6824 - $content .= "IMPORTANT: Do not include any citation links, source URLs, or hyperlinks in your responses. " .
6825 - "Simply provide helpful answers based on the reference information without citing sources.";
6826 - }
6827 - }
6828 -
6829 - return trim($content);
6830 -}
6831 -
6832 -/**
6833 - * plan-mxchat-20260717-03ba33 — if a KB source used for context is a single
6834 - * YouTube video, queue ONE consent-safe embed for the response html channel.
6835 - * Called from BOTH retrieval builders (WordPress DB + Pinecone) inside their
6836 - * real-URL winner branch, in ranked order — so the first (best) video wins and
6837 - * later matches are ignored. Only KB/admin-ingested sources ever reach this
6838 - * point; a URL a visitor pastes in chat never does.
6839 - *
6840 - * plan-mxchat-20260813-f52492 — placing in the winner set is NOT evidence the
6841 - * video answered anything. Ten logged instances in eight days of a correct
6842 - * prose answer carrying an unrelated video card, including a paying customer
6843 - * reporting a broken add-on and being shown two tutorials. Two gates now stand
6844 - * between "a video-backed source was retrieved" and "show the visitor a video":
6845 - * an owner-facing master switch, and the card's own similarity floor.
6846 - *
6847 - * BOTH gates live HERE, at the SET site, and never at the five render sites
6848 - * (:2329 / :2366 / :2396 / :2481 / :2494 — streaming, non-streaming and
6849 - * function-calling). A suppressed card leaves $videoEmbedHtml empty, so every
6850 - * one of those `!empty()` guards short-circuits together and no empty bot row
6851 - * is saved. Gating per-render site would let the paths diverge.
6852 - *
6853 - * @param float|null $match_similarity Cosine similarity of the BEST match in
6854 - * this source's group (see best_similarity in both winner loops).
6855 - * Deliberately FAIL-CLOSED on null: a card we cannot justify with a
6856 - * score is exactly the card this plan exists to stop. Both callers pass
6857 - * it; verify-f52492.php asserts on the deployed file that they still do.
6858 - */
6859 -private function maybe_queue_youtube_embed($source_url, $full_text, $match_similarity = null) {
6860 - if (!empty($this->videoEmbedHtml)) {
6861 - return; // one video per response
6862 - }
6863 - if (!MxChat_Utils::video_embed_enabled()) {
6864 - return; // owner turned video cards off entirely
6865 - }
6866 - $video_id = MxChat_Utils::parse_youtube_id($source_url);
6867 - if (empty($video_id)) {
6868 - return;
6869 - }
6870 - // Confidence floor. NOTE the score read here must be a true cosine — with
6871 - // the hybrid keyword boost on, a group's best_score is a fused RRF rank
6872 - // (~0.016 at rank 1), so comparing THAT to a 0-1 threshold would suppress
6873 - // every card on every hybrid install. best_similarity is tracked separately
6874 - // for precisely this reason.
6875 - $floor = MxChat_Utils::video_embed_threshold();
6876 - if ($match_similarity === null || (float) $match_similarity < $floor) {
6877 - return;
6878 - }
6879 - // Ingestion writes "YouTube Video: {title}" / "Channel: {name}" / "URL: …"
6880 - // header lines into the indexed text. NOTE: when citation links are
6881 - // disabled the winner loop collapses ALL whitespace to single spaces
6882 - // before this runs, so the title must be terminated by the next header
6883 - // label, not by end-of-line. Fall back to a generic label when absent
6884 - // (e.g. a YouTube watch page imported through the plain URL source).
6885 - $title = '';
6886 - if (preg_match('/YouTube Video:\s*(.+?)(?=\s+Channel:\s|\s+URL:\s|\r|\n|$)/i', (string) $full_text, $m)) {
6887 - $title = trim(mb_substr(trim($m[1]), 0, 140));
6888 - if (preg_match('#^https?://#i', $title)) {
6889 - $title = ''; // header carried the URL, not a real title
6890 - }
6891 - }
6892 - $this->videoEmbedHtml = $this->build_youtube_embed_html($video_id, $title, $source_url);
6893 -}
6894 -
6895 -/**
6896 - * Consent-safe click-to-load YouTube facade. No Google iframe is created until
6897 - * the visitor taps play (chat-script.js swaps the facade for a
6898 - * youtube-nocookie.com iframe). The caption always carries a plain "Watch on
6899 - * YouTube" link, which is also the graceful degrade on strict-CSP sites where
6900 - * third-party frames are blocked.
6901 - */
6902 -private function build_youtube_embed_html($video_id, $title, $watch_url) {
6903 - $video_id = preg_replace('/[^A-Za-z0-9_-]/', '', (string) $video_id);
6904 - if ($video_id === '') {
6905 - return '';
6906 - }
6907 - $thumb = 'https://i.ytimg.com/vi/' . $video_id . '/hqdefault.jpg';
6908 - $label = ($title !== '') ? $title : __('YouTube video', 'mxchat');
6909 -
6910 - $html = '<div class="mxchat-youtube-embed" data-video-id="' . esc_attr($video_id) . '">';
6911 - $html .= '<button type="button" class="mxchat-youtube-facade" aria-label="' . esc_attr(sprintf(__('Play video: %s', 'mxchat'), $label)) . '">';
6912 - $html .= '<img class="mxchat-youtube-thumb" src="' . esc_url($thumb) . '" alt="' . esc_attr($label) . '" loading="lazy" />';
6913 - $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>';
6914 - $html .= '</button>';
6915 - $html .= '<div class="mxchat-youtube-caption">';
6916 - $html .= '<span class="mxchat-youtube-title">' . esc_html($label) . '</span>';
6917 - $html .= '<a class="mxchat-youtube-link" href="' . esc_url($watch_url) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Watch on YouTube', 'mxchat') . '</a>';
6918 - $html .= '</div>';
6919 - $html .= '</div>';
6920 - return $html;
6921 -}
6922 -
6923 -/**
6924 - * Fetch and reassemble chunks for a URL from WordPress database
6925 - *
6926 - * @param string $source_url The source URL to fetch chunks for
6927 - * @param int $max_chunks Maximum number of chunks to return (0 = unlimited)
6928 - * @param int &$chunk_count Reference to store the actual number of chunks returned
6929 - * @return string Reassembled content from chunks
6930 - */
6931 -private function reassemble_chunks_from_wordpress($source_url, $max_chunks = 0, &$chunk_count = 0) {
6932 - global $wpdb;
6933 - $table = $wpdb->prefix . 'mxchat_system_prompt_content';
6934 -
6935 - // Fetch all rows with this source_url
6936 - $rows = $wpdb->get_results($wpdb->prepare(
6937 - "SELECT article_content FROM {$table}
6938 - WHERE source_url = %s
6939 - ORDER BY id ASC",
6940 - $source_url
6941 - ));
6942 -
6943 - if (empty($rows)) {
6944 - $chunk_count = 0;
6945 - return '';
6946 - }
6947 -
6948 - // Parse and sort chunks by index
6949 - $chunks = array();
6950 - foreach ($rows as $row) {
6951 - $parsed = MxChat_Chunker::parse_stored_chunk($row->article_content);
6952 -
6953 - if ($parsed['is_chunked']) {
6954 - $chunk_index = $parsed['metadata']['chunk_index'] ?? 0;
6955 - $chunks[$chunk_index] = $parsed['text'];
6956 - } else {
6957 - // Non-chunked content - just return it
6958 - $chunks[] = $parsed['text'];
6959 - }
6960 - }
6961 -
6962 - // Sort by chunk index
6963 - ksort($chunks);
6964 -
6965 - // Apply chunk limit if specified
6966 - if ($max_chunks > 0 && count($chunks) > $max_chunks) {
6967 - $chunks = array_slice($chunks, 0, $max_chunks, true);
6968 - }
6969 -
6970 - // Store actual chunk count
6971 - $chunk_count = count($chunks);
6972 -
6973 - // Reassemble content
6974 - return implode("\n\n", $chunks);
6975 -}
6976 -
6977 -private function find_relevant_content_pinecone($user_embedding, $bot_id = 'default', $bot_config = null) {
6978 - global $wpdb;
6979 -
6980 - //error_log("MXCHAT DEBUG: find_relevant_content_pinecone called");
6981 - //error_log(" - bot_id: " . $bot_id);
6982 - //error_log(" - user_embedding is array: " . (is_array($user_embedding) ? 'yes' : 'no'));
6983 - //error_log(" - user_embedding count: " . (is_array($user_embedding) ? count($user_embedding) : 'N/A'));
6984 -
6985 - // Use bot-specific config or fall back to default
6986 - if ($bot_config === null) {
6987 - $bot_config = $this->get_bot_pinecone_config($bot_id);
6988 - }
6989 -
6990 - $api_key = $bot_config['api_key'] ?? '';
6991 - $host = $bot_config['host'] ?? '';
6992 - $namespace = $bot_config['namespace'] ?? '';
6993 -
6994 - //error_log("MXCHAT DEBUG: Pinecone query parameters:");
6995 - //error_log(" - API Key: " . (empty($api_key) ? 'EMPTY - ERROR!' : 'Present (length: ' . strlen($api_key) . ')'));
6996 - //error_log(" - Host: " . (empty($host) ? 'EMPTY - ERROR!' : $host));
6997 - //error_log(" - Namespace: " . (empty($namespace) ? 'EMPTY (will use default)' : $namespace));
6998 -
6999 - // Initialize similarity analysis storage
7000 - $this->last_similarity_analysis = [
7001 - 'knowledge_base_type' => 'Pinecone',
7002 - 'bot_id' => $bot_id,
7003 - 'namespace' => $namespace,
7004 - 'top_matches' => [],
7005 - 'threshold_used' => 0,
7006 - 'total_checked' => 0
7007 - ];
7008 -
7009 - // NEW: Initialize valid URLs array
7010 - $valid_urls = [];
7011 -
7012 - if (empty($host) || empty($api_key)) {
7013 - //error_log("MXCHAT DEBUG ERROR: Missing Pinecone host or API key!");
7014 - //error_log(" - Host empty: " . (empty($host) ? 'YES' : 'NO'));
7015 - //error_log(" - API key empty: " . (empty($api_key) ? 'YES' : 'NO'));
7016 - // Store empty array for valid URLs since we can't proceed
7017 - $this->current_valid_urls = [];
7018 - return '';
7019 - }
7020 -
7021 - // Get knowledge manager instance for role checking
7022 - $knowledge_manager = MxChat_Knowledge_Manager::get_instance();
7023 -
7024 - // Get the similarity threshold from the bot options or main options
7025 - $bot_options = $this->get_bot_options($bot_id);
7026 - $current_options = !empty($bot_options) ? $bot_options : get_option('mxchat_options', []);
7027 -
7028 - $similarity_threshold = isset($current_options['similarity_threshold'])
7029 - ? ((int) $current_options['similarity_threshold']) / 100
7030 - : 0.35;
7031 -
7032 - $this->last_similarity_analysis['threshold_used'] = $similarity_threshold;
7033 -
7034 - // Prepare the query request for Pinecone
7035 - $api_endpoint = "https://{$host}/query";
7036 -
7037 - $request_body = array(
7038 - 'vector' => $user_embedding,
7039 - 'topK' => 50, // Increased for chunked content grouping - need more candidates to find top N unique URLs
7040 - 'includeMetadata' => true,
7041 - 'includeValues' => true
7042 - );
7043 -
7044 - // Add namespace if specified for this bot
7045 - if (!empty($namespace)) {
7046 - $request_body['namespace'] = $namespace;
7047 - }
7048 -
7049 - //error_log("MXCHAT DEBUG: About to call Pinecone API");
7050 - //error_log(" - Endpoint: " . $api_endpoint);
7051 - //error_log(" - Namespace in request: " . (!empty($namespace) ? $namespace : 'NOT SET'));
7052 -
7053 - $response = wp_remote_post($api_endpoint, array(
7054 - 'headers' => array(
7055 - 'Api-Key' => $api_key,
7056 - 'accept' => 'application/json',
7057 - 'content-type' => 'application/json'
7058 - ),
7059 - 'body' => wp_json_encode($request_body),
7060 - 'timeout' => 30
7061 - ));
7062 -
7063 - if (is_wp_error($response)) {
7064 - //error_log("MXCHAT DEBUG ERROR: WP Error in Pinecone request: " . $response->get_error_message());
7065 - // Store empty array for valid URLs
7066 - $this->current_valid_urls = [];
7067 - return '';
7068 - }
7069 -
7070 - $response_code = wp_remote_retrieve_response_code($response);
7071 - //error_log("MXCHAT DEBUG: Pinecone response code: " . $response_code);
7072 -
7073 - if ($response_code !== 200) {
7074 - $response_body = wp_remote_retrieve_body($response);
7075 - //error_log("MXCHAT DEBUG ERROR: Pinecone API error response: " . substr($response_body, 0, 500));
7076 - // Store empty array for valid URLs
7077 - $this->current_valid_urls = [];
7078 - return '';
7079 - }
7080 -
7081 - // ADD DETAILED DEBUG SECTION HERE
7082 - $response_body = wp_remote_retrieve_body($response);
7083 - //error_log("MXCHAT DEBUG: Raw Pinecone response length: " . strlen($response_body));
7084 -
7085 - $results = json_decode($response_body, true);
7086 -
7087 - if (json_last_error() !== JSON_ERROR_NONE) {
7088 - //error_log("MXCHAT DEBUG ERROR: JSON decode error: " . json_last_error_msg());
7089 - //error_log("MXCHAT DEBUG: First 500 chars of response: " . substr($response_body, 0, 500));
7090 - // Store empty array for valid URLs
7091 - $this->current_valid_urls = [];
7092 - return '';
7093 - }
7094 -
7095 - //error_log("MXCHAT DEBUG: Pinecone response structure:");
7096 - //error_log(" - Has 'matches' key: " . (isset($results['matches']) ? 'yes' : 'no'));
7097 - //error_log(" - Has 'namespace' key: " . (isset($results['namespace']) ? 'yes (' . $results['namespace'] . ')' : 'no'));
7098 -
7099 - if (empty($results['matches'])) {
7100 - //error_log("MXCHAT DEBUG: No matches found in Pinecone response");
7101 - //error_log("MXCHAT DEBUG: Response keys: " . implode(', ', array_keys($results)));
7102 - // Store empty array for valid URLs
7103 - $this->current_valid_urls = [];
7104 - return '';
7105 - }
7106 -
7107 - //error_log("MXCHAT DEBUG: Found " . count($results['matches']) . " matches in Pinecone");
7108 -
7109 - // Log first match details for debugging
7110 - if (!empty($results['matches'][0])) {
7111 - $first_match = $results['matches'][0];
7112 - //error_log("MXCHAT DEBUG: First match details:");
7113 - //error_log(" - Score: " . ($first_match['score'] ?? 'no score'));
7114 - //error_log(" - Has metadata: " . (isset($first_match['metadata']) ? 'yes' : 'no'));
7115 - if (isset($first_match['metadata'])) {
7116 - //error_log(" - Metadata keys: " . implode(', ', array_keys($first_match['metadata'])));
7117 - }
7118 - }
7119 -
7120 - // Initialize the final content
7121 - $content = '';
7122 - $matches_used = 0;
7123 - $matches_used_for_context = [];
7124 - $total_chunks_used = 0;
7125 - $max_total_chunks = isset($current_options['rag_chunks_limit']) ? intval($current_options['rag_chunks_limit']) : 15;
7126 - if ($max_total_chunks < 8) $max_total_chunks = 8;
7127 - if ($max_total_chunks > 20) $max_total_chunks = 20;
7128 - $max_chunks_per_source = 5; // Cap per individual source to limit token usage
7129 -
7130 - // Check if citation links are enabled (default to 'on' for backwards compatibility)
7131 - // Use fresh options to ensure we get the latest setting value
7132 - $fresh_options = get_option('mxchat_options', []);
7133 - $citation_links_enabled = isset($fresh_options['citation_links_toggle']) ? ($fresh_options['citation_links_toggle'] === 'on') : true;
7134 -
7135 - // NEW CHUNKING LOGIC: Group results by source_url for chunk reassembly
7136 - $url_groups = array();
7137 -
7138 - foreach ($results['matches'] as $index => $match) {
7139 - // Skip if similarity is below threshold
7140 - if ($match['score'] < $similarity_threshold) {
7141 - continue;
7142 - }
7143 -
7144 - $metadata = $match['metadata'] ?? array();
7145 - $source_url = $metadata['source_url'] ?? '';
7146 - $match_id = $match['id'] ?? '';
7147 -
7148 - // LAZY ROLE CHECK: Only check role for content we're actually considering
7149 - $role_restriction = $this->get_single_vector_role($match_id, $metadata);
7150 - $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
7151 -
7152 - // Skip if user doesn't have access
7153 - if (!$has_access) {
7154 - continue;
7155 - }
7156 -
7157 - // Use a unique key for manual entries without a source URL
7158 - $group_key = !empty($source_url) ? $source_url : '_manual_' . $match_id;
7159 -
7160 - // Group by source URL (or unique key for manual entries)
7161 - if (!isset($url_groups[$group_key])) {
7162 - $url_groups[$group_key] = array(
7163 - 'source_url' => $source_url,
7164 - 'best_score' => 0,
7165 - 'best_similarity' => 0,
7166 - 'is_chunked' => isset($metadata['is_chunked']) && $metadata['is_chunked'],
7167 - 'chunks' => array(),
7168 - 'single_text' => ''
7169 - );
7170 - }
7171 -
7172 - // Track best score for this group
7173 - if ($match['score'] > $url_groups[$group_key]['best_score']) {
7174 - $url_groups[$group_key]['best_score'] = $match['score'];
7175 - }
7176 -
7177 - // best_similarity mirrors best_score on this backend — Pinecone's score
7178 - // IS the cosine — but the key is carried under the same name as the
7179 - // WP-DB builder's so the shared video-card gate (f52492) has one
7180 - // contract across both retrieval paths.
7181 - if ((float) $match['score'] > $url_groups[$group_key]['best_similarity']) {
7182 - $url_groups[$group_key]['best_similarity'] = (float) $match['score'];
7183 - }
7184 -
7185 - // Store chunk info or single text
7186 - if ($url_groups[$group_key]['is_chunked']) {
7187 - $url_groups[$group_key]['chunks'][] = array(
7188 - 'id' => $match_id,
7189 - 'score' => $match['score'],
7190 - 'chunk_index' => $metadata['chunk_index'] ?? 0,
7191 - 'text' => $metadata['text'] ?? ''
7192 - );
7193 - } else {
7194 - // Non-chunked content - just store the text
7195 - $url_groups[$group_key]['single_text'] = $metadata['text'] ?? '';
7196 - $url_groups[$group_key]['single_id'] = $match_id;
7197 - }
7198 - }
7199 -
7200 - // Sort URL groups by best score (highest first)
7201 - uasort($url_groups, function($a, $b) {
7202 - return $b['best_score'] <=> $a['best_score'];
7203 - });
7204 -
7205 - // Get RAG sources limit from options (default 6, min 3, max 10)
7206 - $rag_sources_limit = isset($current_options['rag_sources_limit']) ? intval($current_options['rag_sources_limit']) : 3;
7207 - if ($rag_sources_limit < 3) $rag_sources_limit = 3;
7208 - if ($rag_sources_limit > 10) $rag_sources_limit = 10;
7209 -
7210 - // Take top N unique URLs based on user setting
7211 - $top_urls = array_slice($url_groups, 0, $rag_sources_limit, true);
7212 -
7213 - // Track which match IDs are actually used for context
7214 - foreach ($top_urls as $group) {
7215 - if ($group['is_chunked']) {
7216 - foreach ($group['chunks'] as $chunk) {
7217 - $matches_used_for_context[] = $chunk['id'];
7218 - }
7219 - } elseif (!empty($group['single_id'])) {
7220 - $matches_used_for_context[] = $group['single_id'];
7221 - }
7222 - }
7223 -
7224 - // Build content from top sources
7225 - foreach ($top_urls as $group_key => $group) {
7226 - $source_url = $group['source_url']; // Use actual source_url, not the group key
7227 -
7228 - // Stop if we've hit the total chunk limit
7229 - if ($total_chunks_used >= $max_total_chunks) {
7230 - break;
7231 - }
7232 -
7233 - $full_text = '';
7234 - $chunks_in_this_source = 1; // Default for non-chunked content
7235 -
7236 - if ($group['is_chunked']) {
7237 - // Calculate how many chunks we can still use (respect both total and per-source caps)
7238 - $chunks_remaining = min($max_chunks_per_source, $max_total_chunks - $total_chunks_used);
7239 -
7240 - // Fetch chunks for this URL with limit
7241 - $full_text = $this->reassemble_chunks_from_pinecone($source_url, $bot_config, $chunks_remaining, $chunks_in_this_source);
7242 -
7243 - // If fetching all chunks fails, fall back to matched chunks
7244 - if (empty($full_text)) {
7245 - // Sort matched chunks by index and concatenate
7246 - usort($group['chunks'], function($a, $b) {
7247 - return $a['chunk_index'] <=> $b['chunk_index'];
7248 - });
7249 -
7250 - $chunk_texts = array();
7251 - $chunks_in_this_source = 0;
7252 - foreach ($group['chunks'] as $chunk) {
7253 - if ($total_chunks_used + $chunks_in_this_source >= $max_total_chunks) {
7254 - break;
7255 - }
7256 - $chunk_texts[] = $chunk['text'];
7257 - $chunks_in_this_source++;
7258 - }
7259 - $full_text = implode("\n\n", $chunk_texts);
7260 - }
7261 - } else {
7262 - $full_text = $group['single_text'];
7263 - $chunks_in_this_source = 1;
7264 - }
7265 -
7266 - if (!empty($full_text)) {
7267 - // Strip URLs from content if citation links are disabled
7268 - if (!$citation_links_enabled) {
7269 - $full_text = preg_replace('#\bhttps?://[^\s<>"\']+#i', '', $full_text);
7270 - $full_text = preg_replace('/\s+/', ' ', trim($full_text)); // Clean up extra spaces
7271 - }
7272 -
7273 - // Use numbered reference for URL-based entries, plain info label for manual entries
7274 - // Manual entries are stored with an internal mxchat:// placeholder URL — never expose them as citations
7275 - if (!empty($source_url) && $source_url !== '#' && strpos($source_url, 'mxchat://') !== 0) {
7276 - $matches_used++;
7277 - $content .= "## Reference " . $matches_used . " ##\n";
7278 - $content .= $full_text . "\n\n";
7279 -
7280 - // Only include citation URLs if citation links are enabled
7281 - if ($citation_links_enabled) {
7282 - $valid_urls[] = $source_url;
7283 - $content .= "URL: " . $source_url . "\n\n";
7284 - }
7285 -
7286 - // Video-backed source → queue the consent-safe embed (03ba33),
7287 - // subject to the card's own confidence floor (f52492). Pass the
7288 - // group's true cosine, NOT best_score — see the gate's docblock.
7289 - $this->maybe_queue_youtube_embed($source_url, $full_text, $group['best_similarity'] ?? null);
7290 - } else {
7291 - // Manual entry — no reference number, no citation. Count it as a USED
7292 - // source (plan-mxchat-20260622-c1fe6a): without this, manual/Direct-Content
7293 - // entries (empty or mxchat:// source_url) never increment $matches_used, so
7294 - // the gate below (`if ($matches_used === 0)`) discards manual-only context on
7295 - // the Pinecone backend and the model is told "No reference information was
7296 - // found" — even though the testing panel reports used_for_context:true. It
7297 - // also corrects the cosmetic sources_used:0 the panel/transcript showed. The
7298 - // sibling local/WP-DB builder gates on empty($top_urls), so it never had this
7299 - // bug; this brings Pinecone to parity. Manual entries are still uncited (not
7300 - // added to $valid_urls, no "URL:" line).
7301 - $matches_used++;
7302 - $content .= "## Information ##\n";
7303 - $content .= $full_text . "\n\n";
7304 - }
7305 -
7306 - // Extract any URLs from the text content itself (only if citation links enabled)
7307 - if ($citation_links_enabled) {
7308 - preg_match_all(
7309 - '#\bhttps?://[^\s<>"\']+#i',
7310 - $full_text,
7311 - $content_urls
7312 - );
7313 - if (!empty($content_urls[0])) {
7314 - $valid_urls = array_merge($valid_urls, $content_urls[0]);
7315 - }
7316 - }
7317 -
7318 - $total_chunks_used += $chunks_in_this_source;
7319 - }
7320 - }
7321 -
7322 - // Process ALL matches for testing data (top 10) - with role checking for testing display
7323 - $all_matches = [];
7324 - foreach ($results['matches'] as $index => $match) {
7325 - if ($index >= 10) break; // Limit to top 10 for testing
7326 -
7327 - $match_id = $match['id'] ?? '';
7328 -
7329 - // Check role access for testing display (use cache if available)
7330 - $role_restriction = $this->get_single_vector_role($match_id, $match['metadata']);
7331 - $has_access = $knowledge_manager->mxchat_user_has_content_access($role_restriction);
7332 -
7333 - $source_display = '';
7334 - if (!empty($match['metadata']['source_url'])) {
7335 - $source_display = $match['metadata']['source_url'];
7336 - } else {
7337 - $content_preview = strip_tags($match['metadata']['text'] ?? '');
7338 - $content_preview = preg_replace('/\s+/', ' ', $content_preview);
7339 - $source_display = substr(trim($content_preview), 0, 50) . '...';
7340 - }
7341 -
7342 - $match_id_for_display = $match['id'] ?? $index;
7343 -
7344 - // Check for chunk metadata in Pinecone
7345 - $is_chunk = isset($match['metadata']['is_chunked']) && $match['metadata']['is_chunked'];
7346 - $chunk_index = isset($match['metadata']['chunk_index']) ? intval($match['metadata']['chunk_index']) : null;
7347 - $total_chunks = isset($match['metadata']['total_chunks']) ? intval($match['metadata']['total_chunks']) : null;
7348 -
7349 - // Also detect chunk from vector ID pattern: {hash}_chunk_{index}
7350 - if (!$is_chunk && MxChat_Chunker::is_chunk_vector_id($match_id_for_display)) {
7351 - $is_chunk = true;
7352 - }
7353 -
7354 - $all_matches[] = [
7355 - 'document_id' => $match_id_for_display,
7356 - 'similarity' => $match['score'],
7357 - 'similarity_percentage' => round($match['score'] * 100, 2),
7358 - 'above_threshold' => $match['score'] >= $similarity_threshold,
7359 - 'source_display' => $source_display,
7360 - 'content_preview' => substr(strip_tags($match['metadata']['text'] ?? ''), 0, 100) . '...',
7361 - 'used_for_context' => in_array($match_id_for_display, $matches_used_for_context),
7362 - 'role_restriction' => $role_restriction,
7363 - 'has_access' => $has_access,
7364 - 'filtered_out' => !$has_access,
7365 - 'is_chunk' => $is_chunk,
7366 - 'chunk_index' => $chunk_index,
7367 - 'total_chunks' => $total_chunks
7368 - ];
7369 - }
7370 -
7371 - // Store for testing panel
7372 - $this->last_similarity_analysis['top_matches'] = $all_matches;
7373 - $this->last_similarity_analysis['total_checked'] = count($results['matches']);
7374 - $this->last_similarity_analysis['sources_used'] = $matches_used;
7375 - $this->last_similarity_analysis['total_chunks_used'] = $total_chunks_used;
7376 -
7377 - // NEW: Store unique valid URLs for validation
7378 - $this->current_valid_urls = array_unique($valid_urls);
7379 -
7380 - // Allow add-ons to act on similarity results (e.g. WooCommerce product card display)
7381 - do_action('mxchat_similarity_results', $this->last_similarity_analysis['top_matches'], $bot_id);
7382 -
7383 - // Add response guidelines
7384 - if ($matches_used === 0) {
7385 - // Empty return → assembler's NO RELEVANT CONTENT branch (plan d7daf8).
7386 - $content = '';
7387 - } else {
7388 - // Build response guidelines based on citation links setting
7389 - $content .= "\n## Response Guidelines ##\n" .
7390 - "You are an AI Chatbot. Answer naturally and helpfully using only the information from the references above. " .
7391 - "Be conversational and friendly, but never mention your knowledge base or training data. " .
7392 - "If you don't have specific information or are uncertain about any details, it's always " .
7393 - "better to honestly say you don't know rather than making up or guessing at answers. " .
7394 - "When information is incomplete, let them know you are unsure.\n\n";
7395 -
7396 - // Only add hyperlink instructions if citation links are enabled
7397 - if ($citation_links_enabled) {
7398 - $content .= "CRITICAL: When creating hyperlinks, always use proper markdown format with descriptive text: " .
7399 - "[descriptive text](url). NEVER use empty brackets like [](url). The text in brackets must describe what the link is about. " .
7400 - "Only cite references that have a URL. Do not cite or add source labels to Information sections that have no URL.";
7401 - } else {
7402 - $content .= "IMPORTANT: Do not include any citation links, source URLs, or hyperlinks in your responses. " .
7403 - "Simply provide helpful answers based on the reference information without citing sources.";
7404 - }
7405 - }
7406 -
7407 - return trim($content);
7408 -}
7409 -
7410 -/**
7411 - * Get role restriction for a single vector (with caching)
7412 - */
7413 -private function get_single_vector_role($vector_id, $metadata = array()) {
7414 - global $wpdb;
7415 -
7416 - if (empty($vector_id)) {
7417 - return 'public';
7418 - }
7419 -
7420 - // Check cache first
7421 - $cache_key = 'mxchat_vector_role_' . $vector_id;
7422 - $cached_role = wp_cache_get($cache_key, 'mxchat_vector_roles');
7423 -
7424 - if ($cached_role !== false) {
7425 - return $cached_role;
7426 - }
7427 -
7428 - $role_restriction = 'public';
7429 -
7430 - // First try Pinecone metadata
7431 - if (!empty($metadata['role_restriction'])) {
7432 - $role_restriction = $metadata['role_restriction'];
7433 - } else {
7434 - // Check WordPress table for user-modified roles
7435 - $roles_table = $wpdb->prefix . 'mxchat_pinecone_roles';
7436 - $stored_role = $wpdb->get_var($wpdb->prepare(
7437 - "SELECT role_restriction FROM {$roles_table} WHERE vector_id = %s",
7438 - $vector_id
7439 - ));
7440 -
7441 - if ($stored_role) {
7442 - $role_restriction = $stored_role;
7443 - }
7444 - }
7445 -
7446 - // Cache individual role for 1 hour
7447 - wp_cache_set($cache_key, $role_restriction, 'mxchat_vector_roles', 3600);
7448 -
7449 - return $role_restriction;
7450 -}
7451 -
7452 -/**
7453 - * Fetch and reassemble all chunks for a URL from Pinecone
7454 - *
7455 - * @param string $source_url The source URL to fetch chunks for
7456 - * @param array $bot_config Bot-specific Pinecone configuration
7457 - * @return string Reassembled content from all chunks
7458 - */
7459 -private function reassemble_chunks_from_pinecone($source_url, $bot_config, $max_chunks = 0, &$chunk_count = 0) {
7460 - $api_key = $bot_config['api_key'] ?? '';
7461 - $host = $bot_config['host'] ?? '';
7462 - $namespace = $bot_config['namespace'] ?? '';
7463 -
7464 - if (empty($host) || empty($api_key)) {
7465 - $chunk_count = 0;
7466 - return '';
7467 - }
7468 -
7469 - $base_hash = md5($source_url);
7470 -
7471 - // Use Pinecone list API to find all chunk vectors with this prefix
7472 - $list_url = "https://{$host}/vectors/list";
7473 -
7474 - // Limit to max_chunks if specified, otherwise fetch up to 100
7475 - $fetch_limit = ($max_chunks > 0 && $max_chunks < 100) ? $max_chunks : 100;
7476 -
7477 - $list_body = array(
7478 - 'prefix' => $base_hash . '_chunk_',
7479 - 'limit' => $fetch_limit
7480 - );
7481 -
7482 - if (!empty($namespace)) {
7483 - $list_body['namespace'] = $namespace;
7484 - }
7485 -
7486 - $list_response = wp_remote_post($list_url, array(
7487 - 'headers' => array(
7488 - 'Api-Key' => $api_key,
7489 - 'accept' => 'application/json',
7490 - 'content-type' => 'application/json'
7491 - ),
7492 - 'body' => wp_json_encode($list_body),
7493 - 'timeout' => 30
7494 - ));
7495 -
7496 - if (is_wp_error($list_response)) {
7497 - //error_log('[MXCHAT-CHUNK] List API error: ' . $list_response->get_error_message());
7498 - return '';
7499 - }
7500 -
7501 - $list_data = json_decode(wp_remote_retrieve_body($list_response), true);
7502 -
7503 - if (empty($list_data['vectors'])) {
7504 - //error_log('[MXCHAT-CHUNK] No chunk vectors found for URL: ' . $source_url);
7505 - return '';
7506 - }
7507 -
7508 - // Extract vector IDs
7509 - $vector_ids = array();
7510 - foreach ($list_data['vectors'] as $vector) {
7511 - if (isset($vector['id'])) {
7512 - $vector_ids[] = $vector['id'];
7513 - }
7514 - }
7515 -
7516 - if (empty($vector_ids)) {
7517 - return '';
7518 - }
7519 -
7520 - // Fetch all chunk content
7521 - $fetch_url = "https://{$host}/vectors/fetch";
7522 -
7523 - $fetch_body = array(
7524 - 'ids' => $vector_ids
7525 - );
7526 -
7527 - if (!empty($namespace)) {
7528 - $fetch_body['namespace'] = $namespace;
7529 - }
7530 -
7531 - $fetch_response = wp_remote_post($fetch_url, array(
7532 - 'headers' => array(
7533 - 'Api-Key' => $api_key,
7534 - 'accept' => 'application/json',
7535 - 'content-type' => 'application/json'
7536 - ),
7537 - 'body' => wp_json_encode($fetch_body),
7538 - 'timeout' => 30
7539 - ));
7540 -
7541 - if (is_wp_error($fetch_response)) {
7542 - //error_log('[MXCHAT-CHUNK] Fetch API error: ' . $fetch_response->get_error_message());
7543 - return '';
7544 - }
7545 -
7546 - $fetch_data = json_decode(wp_remote_retrieve_body($fetch_response), true);
7547 -
7548 - if (empty($fetch_data['vectors'])) {
7549 - return '';
7550 - }
7551 -
7552 - // Sort chunks by index and reassemble
7553 - $chunks = array();
7554 - foreach ($fetch_data['vectors'] as $id => $vector) {
7555 - $metadata = $vector['metadata'] ?? array();
7556 - $chunk_index = $metadata['chunk_index'] ?? 0;
7557 - $text = $metadata['text'] ?? '';
7558 -
7559 - // Store chunk with its index
7560 - $chunks[$chunk_index] = $text;
7561 - }
7562 -
7563 - // Sort by chunk index
7564 - ksort($chunks);
7565 -
7566 - // Apply chunk limit if specified
7567 - if ($max_chunks > 0 && count($chunks) > $max_chunks) {
7568 - $chunks = array_slice($chunks, 0, $max_chunks, true);
7569 - }
7570 -
7571 - // Store actual chunk count
7572 - $chunk_count = count($chunks);
7573 -
7574 - // Reassemble content
7575 - return implode("\n\n", $chunks);
7576 -}
7577 -
7578 -/**
7579 - * Search for relevant content using OpenAI Vector Store (File Search)
7580 - *
7581 - * @param string $user_query The user's query text
7582 - * @param string $bot_id The bot ID
7583 - * @param array $vectorstore_config Vector Store configuration
7584 - * @return string Formatted context string with references
7585 - */
7586 -private function find_relevant_content_openai_vectorstore($user_query, $bot_id = 'default', $vectorstore_config = array()) {
7587 - //error_log("MXCHAT DEBUG: find_relevant_content_openai_vectorstore called");
7588 - //error_log(" - bot_id: " . $bot_id);
7589 - //error_log(" - user_query length: " . strlen($user_query));
7590 -
7591 - // Get OpenAI API key
7592 - $mxchat_options = get_option('mxchat_options', array());
7593 - $api_key = $mxchat_options['api_key'] ?? '';
7594 -
7595 - // Reset vectorstore error tracking
7596 - $this->last_vectorstore_error = null;
7597 -
7598 - if (empty($api_key)) {
7599 - //error_log("MXCHAT DEBUG ERROR: OpenAI API key not configured");
7600 - $this->last_vectorstore_error = 'Vector Store search failed: OpenAI API key is not configured.';
7601 - $this->current_valid_urls = [];
7602 - return '';
7603 - }
7604 -
7605 - // Get Vector Store configuration
7606 - if (empty($vectorstore_config)) {
7607 - $vectorstore_config = $this->get_bot_vectorstore_config($bot_id);
7608 - }
7609 -
7610 - $vectorstore_ids_string = $vectorstore_config['vectorstore_ids'] ?? '';
7611 - $max_results = $vectorstore_config['max_results'] ?? 5;
7612 -
7613 - if (empty($vectorstore_ids_string)) {
7614 - //error_log("MXCHAT DEBUG ERROR: No Vector Store IDs configured");
7615 - $this->last_vectorstore_error = 'Vector Store search failed: No Vector Store IDs are configured for this bot.';
7616 - $this->current_valid_urls = [];
7617 - return '';
7618 - }
7619 -
7620 - // Parse Vector Store IDs
7621 - $vectorstore_ids = array_map('trim', explode(',', $vectorstore_ids_string));
7622 - $vectorstore_ids = array_filter($vectorstore_ids); // Remove empty values
7623 -
7624 - //error_log("MXCHAT DEBUG: Vector Store IDs: " . implode(', ', $vectorstore_ids));
7625 - //error_log("MXCHAT DEBUG: Max results: " . $max_results);
7626 -
7627 - // Initialize similarity analysis storage
7628 - $this->last_similarity_analysis = [
7629 - 'knowledge_base_type' => 'OpenAI Vector Store',
7630 - 'bot_id' => $bot_id,
7631 - 'vectorstore_ids' => $vectorstore_ids,
7632 - 'top_matches' => [],
7633 - 'threshold_used' => 0,
7634 - 'total_checked' => 0
7635 - ];
7636 -
7637 - $valid_urls = [];
7638 -
7639 - // Get the selected model
7640 - $bot_options = $this->get_bot_options($bot_id);
7641 - $current_options = !empty($bot_options) ? $bot_options : $mxchat_options;
7642 - $selected_model = $current_options['model'] ?? 'gpt-5.6-sol';
7643 -
7644 - // Verify it's an OpenAI model
7645 - if (!$this->is_openai_chat_model($selected_model)) {
7646 - //error_log("MXCHAT DEBUG ERROR: Vector Store search requires OpenAI model. Current: " . $selected_model);
7647 - $this->last_vectorstore_error = 'Vector Store search requires an OpenAI model. Current model: ' . $selected_model;
7648 - $this->current_valid_urls = [];
7649 - return '';
7650 - }
7651 -
7652 - // Use OpenAI Responses API with file_search tool
7653 - $request_body = array(
7654 - 'model' => $selected_model,
7655 - 'input' => $user_query,
7656 - 'tools' => array(
7657 - array(
7658 - 'type' => 'file_search',
7659 - 'vector_store_ids' => $vectorstore_ids,
7660 - 'max_num_results' => intval($max_results)
7661 - )
7662 - ),
7663 - 'include' => array('file_search_call.results')
7664 - );
7665 -
7666 - //error_log("MXCHAT VECTORSTORE: ========== REQUEST START ==========");
7667 - //error_log("MXCHAT VECTORSTORE: Model: " . $selected_model);
7668 - //error_log("MXCHAT VECTORSTORE: Query: " . substr($user_query, 0, 200));
7669 - //error_log("MXCHAT VECTORSTORE: Vector Store IDs: " . implode(', ', $vectorstore_ids));
7670 - //error_log("MXCHAT VECTORSTORE: Max Results: " . $max_results);
7671 - //error_log("MXCHAT VECTORSTORE: Request body: " . wp_json_encode($request_body));
7672 -
7673 - $response = wp_remote_post('https://api.openai.com/v1/responses', array(
7674 - 'headers' => array(
7675 - 'Authorization' => 'Bearer ' . $api_key,
7676 - 'Content-Type' => 'application/json'
7677 - ),
7678 - 'body' => wp_json_encode($request_body),
7679 - 'timeout' => 60
7680 - ));
7681 -
7682 - if (is_wp_error($response)) {
7683 - //error_log("MXCHAT VECTORSTORE ERROR: WP Error: " . $response->get_error_message());
7684 - $this->last_vectorstore_error = 'Vector Store API request failed: ' . $response->get_error_message();
7685 - $this->current_valid_urls = [];
7686 - return '';
7687 - }
7688 -
7689 - $response_code = wp_remote_retrieve_response_code($response);
7690 - //error_log("MXCHAT VECTORSTORE: Response code: " . $response_code);
7691 -
7692 - $response_body = wp_remote_retrieve_body($response);
7693 - //error_log("MXCHAT VECTORSTORE: Raw response (first 2000 chars): " . substr($response_body, 0, 2000));
7694 -
7695 - if ($response_code !== 200) {
7696 - //error_log("MXCHAT VECTORSTORE ERROR: API error response: " . $response_body);
7697 - $decoded_error = json_decode($response_body, true);
7698 - $api_error_detail = $this->extract_provider_error($decoded_error, '');
7699 - $this->last_vectorstore_error = 'Vector Store API returned HTTP ' . $response_code . ($api_error_detail ? ': ' . $api_error_detail : '');
7700 - $this->current_valid_urls = [];
7701 - return '';
7702 - }
7703 - $result = json_decode($response_body, true);
7704 -
7705 - if (json_last_error() !== JSON_ERROR_NONE) {
7706 - //error_log("MXCHAT VECTORSTORE ERROR: JSON decode error: " . json_last_error_msg());
7707 - $this->last_vectorstore_error = 'Vector Store response could not be parsed: ' . json_last_error_msg();
7708 - $this->current_valid_urls = [];
7709 - return '';
7710 - }
7711 -
7712 - // Debug: Log the structure of the result
7713 - //error_log("MXCHAT VECTORSTORE: Result keys: " . implode(', ', array_keys($result)));
7714 - if (isset($result['output'])) {
7715 - //error_log("MXCHAT VECTORSTORE: Output count: " . count($result['output']));
7716 - foreach ($result['output'] as $idx => $out) {
7717 - //error_log("MXCHAT VECTORSTORE: Output[$idx] type: " . ($out['type'] ?? 'unknown'));
7718 - //error_log("MXCHAT VECTORSTORE: Output[$idx] keys: " . implode(', ', array_keys($out)));
7719 - }
7720 - } else {
7721 - //error_log("MXCHAT VECTORSTORE: No 'output' key in result!");
7722 - }
7723 -
7724 - // Extract file search results from the response
7725 - $content = '';
7726 - $matches_used = 0;
7727 - $all_matches = [];
7728 -
7729 - // The Responses API returns output array with tool results
7730 - if (isset($result['output']) && is_array($result['output'])) {
7731 - foreach ($result['output'] as $output_item) {
7732 - // Look for file_search_call results
7733 - if (isset($output_item['type']) && $output_item['type'] === 'file_search_call') {
7734 - //error_log("MXCHAT VECTORSTORE: Found file_search_call output item");
7735 - //error_log("MXCHAT VECTORSTORE: file_search_call keys: " . implode(', ', array_keys($output_item)));
7736 -
7737 - // Check for search_results in the output item directly
7738 - $search_results = $output_item['search_results'] ?? $output_item['results'] ?? [];
7739 - //error_log("MXCHAT VECTORSTORE: Search results count: " . count($search_results));
7740 -
7741 - if (empty($search_results)) {
7742 - //error_log("MXCHAT VECTORSTORE: No search results found in file_search_call");
7743 - //error_log("MXCHAT VECTORSTORE: file_search_call content: " . wp_json_encode($output_item));
7744 - }
7745 -
7746 - foreach ($search_results as $index => $search_result) {
7747 - $filename = $search_result['filename'] ?? '';
7748 - $score = $search_result['score'] ?? 0;
7749 - $text_content = '';
7750 -
7751 - // Extract text content from the result
7752 - // The text can be directly on the result OR nested under content array
7753 - if (isset($search_result['text']) && !empty($search_result['text'])) {
7754 - // Direct text field (OpenAI's actual format)
7755 - $text_content = $search_result['text'];
7756 - //error_log("MXCHAT VECTORSTORE: Found text directly on result[$index], length: " . strlen($text_content));
7757 - } elseif (isset($search_result['content']) && is_array($search_result['content'])) {
7758 - // Nested content array format
7759 - foreach ($search_result['content'] as $content_item) {
7760 - if (isset($content_item['text'])) {
7761 - $text_content .= $content_item['text'] . "\n";
7762 - }
7763 - }
7764 - //error_log("MXCHAT VECTORSTORE: Found text in content array for result[$index], length: " . strlen($text_content));
7765 - } else {
7766 - //error_log("MXCHAT VECTORSTORE: No text found for result[$index]. Keys: " . implode(', ', array_keys($search_result)));
7767 - }
7768 -
7769 - if (!empty($text_content)) {
7770 - $content .= "## Reference " . ($matches_used + 1) . " ##\n";
7771 - $content .= trim($text_content) . "\n\n";
7772 -
7773 - if (!empty($filename)) {
7774 - $content .= "Source: " . $filename . "\n\n";
7775 - }
7776 -
7777 - // Extract URLs from content
7778 - preg_match_all(
7779 - '#\bhttps?://[^\s<>"\']+#i',
7780 - $text_content,
7781 - $content_urls
7782 - );
7783 - if (!empty($content_urls[0])) {
7784 - $valid_urls = array_merge($valid_urls, $content_urls[0]);
7785 - }
7786 -
7787 - $matches_used++;
7788 - }
7789 -
7790 - // Store for similarity analysis
7791 - $all_matches[] = [
7792 - 'document_id' => $filename ?: ('result_' . $index),
7793 - 'similarity' => $score,
7794 - 'similarity_percentage' => round($score * 100, 2),
7795 - 'above_threshold' => true,
7796 - 'source_display' => $filename,
7797 - 'content_preview' => substr(strip_tags($text_content), 0, 100) . '...',
7798 - 'used_for_context' => true,
7799 - 'role_restriction' => 'public',
7800 - 'has_access' => true,
7801 - 'filtered_out' => false
7802 - ];
7803 - }
7804 - }
7805 -
7806 - // Also check for message content with annotations (citations)
7807 - if (isset($output_item['type']) && $output_item['type'] === 'message') {
7808 - if (isset($output_item['content']) && is_array($output_item['content'])) {
7809 - foreach ($output_item['content'] as $content_block) {
7810 - if (isset($content_block['annotations']) && is_array($content_block['annotations'])) {
7811 - foreach ($content_block['annotations'] as $annotation) {
7812 - if (isset($annotation['filename'])) {
7813 - $filename = $annotation['filename'];
7814 - $score = $annotation['score'] ?? 0;
7815 - $text_content = '';
7816 -
7817 - if (isset($annotation['content']) && is_array($annotation['content'])) {
7818 - foreach ($annotation['content'] as $ann_content) {
7819 - if (isset($ann_content['text'])) {
7820 - $text_content .= $ann_content['text'] . "\n";
7821 - }
7822 - }
7823 - }
7824 -
7825 - if (!empty($text_content) && $matches_used < $max_results) {
7826 - $content .= "## Reference " . ($matches_used + 1) . " ##\n";
7827 - $content .= trim($text_content) . "\n\n";
7828 - $content .= "Source: " . $filename . "\n\n";
7829 -
7830 - preg_match_all(
7831 - '#\bhttps?://[^\s<>"\']+#i',
7832 - $text_content,
7833 - $content_urls
7834 - );
7835 - if (!empty($content_urls[0])) {
7836 - $valid_urls = array_merge($valid_urls, $content_urls[0]);
7837 - }
7838 -
7839 - $matches_used++;
7840 -
7841 - $all_matches[] = [
7842 - 'document_id' => $filename,
7843 - 'similarity' => $score,
7844 - 'similarity_percentage' => round($score * 100, 2),
7845 - 'above_threshold' => true,
7846 - 'source_display' => $filename,
7847 - 'content_preview' => substr(strip_tags($text_content), 0, 100) . '...',
7848 - 'used_for_context' => true,
7849 - 'role_restriction' => 'public',
7850 - 'has_access' => true,
7851 - 'filtered_out' => false
7852 - ];
7853 - }
7854 - }
7855 - }
7856 - }
7857 - }
7858 - }
7859 - }
7860 - }
7861 - }
7862 -
7863 - // Store for testing panel
7864 - $this->last_similarity_analysis['top_matches'] = $all_matches;
7865 - $this->last_similarity_analysis['total_checked'] = count($all_matches);
7866 -
7867 - // Store unique valid URLs for validation
7868 - $this->current_valid_urls = array_unique($valid_urls);
7869 -
7870 - // Allow add-ons to act on similarity results (e.g. WooCommerce product card display)
7871 - do_action('mxchat_similarity_results', $this->last_similarity_analysis['top_matches'], $bot_id);
7872 -
7873 - //error_log("MXCHAT VECTORSTORE: ========== SEARCH COMPLETE ==========");
7874 - //error_log("MXCHAT VECTORSTORE: Matches used: " . $matches_used);
7875 - //error_log("MXCHAT VECTORSTORE: All matches count: " . count($all_matches));
7876 - //error_log("MXCHAT VECTORSTORE: Content length: " . strlen($content));
7877 - if ($matches_used > 0) {
7878 - //error_log("MXCHAT VECTORSTORE: Content preview: " . substr($content, 0, 500));
7879 - }
7880 -
7881 - // Check if citation links are enabled
7882 - $citation_links_enabled = ($mxchat_options['citation_links_toggle'] ?? 'on') === 'on';
7883 -
7884 - // Add response guidelines
7885 - if ($matches_used === 0) {
7886 - //error_log("MXCHAT VECTORSTORE: No matches found - returning empty reference message");
7887 - // Empty return → assembler's NO RELEVANT CONTENT branch (plan d7daf8).
7888 - $content = '';
7889 - } else {
7890 - // Build response guidelines based on citation links setting
7891 - $content .= "\n## Response Guidelines ##\n" .
7892 - "You are an AI Chatbot. Answer naturally and helpfully using only the information from the references above. " .
7893 - "Be conversational and friendly, but never mention your knowledge base or training data. " .
7894 - "If you don't have specific information or are uncertain about any details, it's always " .
7895 - "better to honestly say you don't know rather than making up or guessing at answers. " .
7896 - "When information is incomplete, let them know you are unsure.\n\n";
7897 -
7898 - // Only add hyperlink instructions if citation links are enabled
7899 - if ($citation_links_enabled) {
7900 - $content .= "CRITICAL: When creating hyperlinks, always use proper markdown format with descriptive text: " .
7901 - "[descriptive text](url). NEVER use empty brackets like [](url). The text in brackets must describe what the link is about.";
7902 - } else {
7903 - $content .= "IMPORTANT: Do not include any citation links, source URLs, or hyperlinks in your responses. " .
7904 - "Simply provide helpful answers based on the reference information without citing sources.";
7905 - }
7906 - }
7907 -
7908 - //error_log("MXCHAT DEBUG: Vector Store search complete. Matches used: " . $matches_used);
7909 -
7910 - return trim($content);
7911 -}
7912 -
7913 -/**
7914 - * Check if the given model is an OpenAI chat model
7915 - *
7916 - * @param string $model The model ID
7917 - * @return bool True if it's an OpenAI model
7918 - */
7919 -private function is_openai_chat_model($model) {
7920 - $openai_prefixes = array('gpt-', 'o1-', 'o3-');
7921 - foreach ($openai_prefixes as $prefix) {
7922 - if (strpos($model, $prefix) === 0) {
7923 - return true;
7924 - }
7925 - }
7926 - return false;
7927 -}
7928 -
7929 -/**
7930 - * Get bot-specific Vector Store configuration
7931 - *
7932 - * @param string $bot_id The bot ID
7933 - * @return array Configuration array
7934 - */
7935 -private function get_bot_vectorstore_config($bot_id = 'default') {
7936 - // Admin Testing tab bot → resolve the DEFAULT bot's backend (see
7937 - // get_bot_pinecone_config). This getter already passes the real default
7938 - // config into the filter, so it was not broken — normalized anyway so the
7939 - // Testing bot can never drift from the front-end default.
7940 - if ($bot_id === 'testing') {
7941 - $bot_id = 'default';
7942 - }
7943 -
7944 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
7945 -
7946 - // Default global settings
7947 - $default_config = array(
7948 - 'use_vectorstore' => ($vectorstore_options['mxchat_use_openai_vectorstore'] ?? '0') === '1',
7949 - 'vectorstore_ids' => $vectorstore_options['mxchat_vectorstore_ids'] ?? '',
7950 - 'max_results' => $vectorstore_options['mxchat_vectorstore_max_results'] ?? 5
7951 - );
7952 -
7953 - // Allow multi-bot plugin to override with bot-specific settings
7954 - $bot_config = apply_filters('mxchat_get_bot_vectorstore_config', $default_config, $bot_id);
7955 -
7956 - // Preserve max_results from global settings if not set in bot config
7957 - if (!isset($bot_config['max_results'])) {
7958 - $bot_config['max_results'] = $default_config['max_results'];
7959 - }
7960 -
7961 - return $bot_config;
7962 -}
7963 -
7964 -private function mxchat_find_relevant_products($user_embedding) {
7965 - //error_log('MXChat Vector Search: Starting product search...');
7966 -
7967 - // Retrieve the add-on settings from the database
7968 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
7969 -
7970 - // Determine whether Pinecone is enabled
7971 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
7972 -
7973 - //error_log('Pinecone enabled flag: ' . $use_pinecone);
7974 -
7975 - if ($use_pinecone === 1) {
7976 - //error_log('MXChat Vector Search: Using Pinecone database for products');
7977 - return $this->find_relevant_products_pinecone($user_embedding);
7978 - } else {
7979 - //error_log('MXChat Vector Search: Using WordPress database for products');
7980 - return $this->find_relevant_products_wordpress($user_embedding);
7981 - }
7982 -}
7983 -private function find_relevant_products_wordpress($user_embedding) {
7984 - global $wpdb;
7985 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
7986 -
7987 - if (!is_array($user_embedding)) {
7988 - return '';
7989 - }
7990 -
7991 - // Streaming top-K pass: scan rows in small batches, keep only the top 3
7992 - // results above the similarity threshold. Peak memory is bounded by
7993 - // $batch_size embedding rows plus a 3-element top list.
7994 - $batch_size = 250;
7995 - $similarity_threshold = 0.85;
7996 - $top_k = 3;
7997 - $top_results = [];
7998 - $offset = 0;
7999 -
8000 - do {
8001 - $batch = $wpdb->get_results($wpdb->prepare(
8002 - "SELECT id, embedding_vector
8003 - FROM {$system_prompt_table}
8004 - LIMIT %d OFFSET %d",
8005 - $batch_size,
8006 - $offset
8007 - ));
8008 -
8009 - if (empty($batch)) {
8010 - break;
8011 - }
8012 -
8013 - foreach ($batch as $row) {
8014 - $database_embedding = $row->embedding_vector
8015 - ? unserialize($row->embedding_vector, ['allowed_classes' => false])
8016 - : null;
8017 -
8018 - if (!is_array($database_embedding)) {
8019 - unset($database_embedding);
8020 - continue;
8021 - }
8022 -
8023 - $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
8024 - unset($database_embedding);
8025 -
8026 - if ($similarity < $similarity_threshold) {
8027 - continue;
8028 - }
8029 -
8030 - // Insert into bounded top-K (kept sorted descending)
8031 - if (count($top_results) < $top_k) {
8032 - $top_results[] = ['id' => $row->id, 'similarity' => $similarity];
8033 - usort($top_results, function ($a, $b) {
8034 - return $b['similarity'] <=> $a['similarity'];
8035 - });
8036 - } elseif ($similarity > $top_results[$top_k - 1]['similarity']) {
8037 - $top_results[$top_k - 1] = ['id' => $row->id, 'similarity' => $similarity];
8038 - usort($top_results, function ($a, $b) {
8039 - return $b['similarity'] <=> $a['similarity'];
8040 - });
8041 - }
8042 - }
8043 -
8044 - unset($batch);
8045 - $offset += $batch_size;
8046 - } while (true);
8047 -
8048 - if (empty($top_results)) {
8049 - return '';
8050 - }
8051 -
8052 - $content = '';
8053 - foreach ($top_results as $result) {
8054 - $chunk_content = $this->fetch_content_with_product_links($result['id']);
8055 - $content .= $chunk_content . "\n\n";
8056 - }
8057 -
8058 - return trim($content);
8059 -}
8060 -
8061 -
8062 -private function find_relevant_products_pinecone($user_embedding) {
8063 - //error_log('Starting Pinecone product search...');
8064 -
8065 - $options = get_option('mxchat_pinecone_addon_options', array());
8066 - $api_key = $options['mxchat_pinecone_api_key'] ?? '';
8067 - $host = $options['mxchat_pinecone_host'] ?? '';
8068 -
8069 - if (empty($host) || empty($api_key)) {
8070 - //error_log('Pinecone credentials not properly configured for product search');
8071 - return '';
8072 - }
8073 -
8074 - $similarity_threshold = 0.85;
8075 - $api_endpoint = "https://{$host}/query";
8076 -
8077 - $request_body = array(
8078 - 'vector' => $user_embedding,
8079 - 'topK' => 5,
8080 - 'includeMetadata' => true,
8081 - 'includeValues' => true,
8082 - 'filter' => array(
8083 - 'type' => 'product'
8084 - )
8085 - );
8086 -
8087 - //error_log('Sending request to Pinecone with body: ' . wp_json_encode($request_body));
8088 -
8089 - $response = wp_remote_post($api_endpoint, array(
8090 - 'headers' => array(
8091 - 'Api-Key' => $api_key,
8092 - 'accept' => 'application/json',
8093 - 'content-type' => 'application/json'
8094 - ),
8095 - 'body' => wp_json_encode($request_body),
8096 - 'timeout' => 30
8097 - ));
8098 -
8099 - if (is_wp_error($response)) {
8100 - //error_log('Pinecone product query error: ' . $response->get_error_message());
8101 - return '';
8102 - }
8103 -
8104 - $response_code = wp_remote_retrieve_response_code($response);
8105 - //error_log('Pinecone response code: ' . $response_code);
8106 -
8107 - if ($response_code !== 200) {
8108 - //error_log('Pinecone API error during product search: ' . wp_remote_retrieve_body($response));
8109 - return '';
8110 - }
8111 -
8112 - $results = json_decode(wp_remote_retrieve_body($response), true);
8113 - //error_log('Pinecone raw response: ' . wp_remote_retrieve_body($response));
8114 -
8115 - if (empty($results['matches'])) {
8116 - //error_log('No matches found in Pinecone response');
8117 - return '';
8118 - }
8119 -
8120 - $content = '';
8121 - foreach ($results['matches'] as $match) {
8122 - if ($match['score'] < $similarity_threshold) {
8123 - //error_log("Match below threshold: " . $match['score']);
8124 - continue;
8125 - }
8126 -
8127 - if (!empty($match['metadata']['text'])) {
8128 - $content .= $match['metadata']['text'];
8129 - if (!empty($match['metadata']['source_url'])) {
8130 - $content .= "\n\nFor more details, check out this product: " . esc_url($match['metadata']['source_url']);
8131 - }
8132 - $content .= "\n\n";
8133 - }
8134 - }
8135 -
8136 - return trim($content);
8137 -}
8138 -
8139 -
8140 -private function fetch_content_with_product_links($most_relevant_id) {
8141 - global $wpdb;
8142 - $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
8143 -
8144 - // Fetch the article content and associated product URL
8145 - $query = $wpdb->prepare("SELECT article_content, source_url FROM {$system_prompt_table} WHERE id = %d", $most_relevant_id);
8146 - $result = $wpdb->get_row($query);
8147 -
8148 - if ($result) {
8149 - // Append the product link to the content if available
8150 - $content = $result->article_content;
8151 - if (!empty($result->source_url)) {
8152 - $content .= "\n\nFor more details, check out this product: " . esc_url($result->source_url);
8153 - }
8154 - return $content;
8155 - }
8156 -
8157 - return null;
8158 -}
8159 -
8160 -/**
8161 - * Get system instructions for a specific bot or default
8162 - * Checks for multi-bot add-on and uses bot-specific instructions if available
8163 - * Automatically strips URLs if citation links are disabled
8164 - * Replaces {visitor_name} placeholder with actual visitor name if available
8165 - *
8166 - * @param string $bot_id The bot ID to get instructions for
8167 - * @param string $session_id Optional session ID to lookup visitor name
8168 - */
8169 -private function get_system_instructions($bot_id = 'default', $session_id = '') {
8170 - $instructions = '';
8171 -
8172 - // Check if multi-bot add-on is active
8173 - if (class_exists('MxChat_Multi_Bot_Core_Manager') && $bot_id !== 'default') {
8174 - // Get bot-specific options from multi-bot add-on
8175 - $bot_options = apply_filters('mxchat_get_bot_options', array(), $bot_id);
8176 -
8177 - // If bot has custom system instructions, use those
8178 - if (!empty($bot_options['system_prompt_instructions'])) {
8179 - $instructions = $bot_options['system_prompt_instructions'];
8180 - }
8181 - }
8182 -
8183 - // Fall back to default system instructions
8184 - if (empty($instructions)) {
8185 - $instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
8186 - }
8187 -
8188 - // Check if citation links are disabled - if so, strip URLs from instructions
8189 - $fresh_options = get_option('mxchat_options', []);
8190 - $citation_links_enabled = isset($fresh_options['citation_links_toggle']) ? ($fresh_options['citation_links_toggle'] === 'on') : true;
8191 -
8192 - if (!$citation_links_enabled && !empty($instructions)) {
8193 - $instructions = preg_replace('#\bhttps?://[^\s<>"\']+#i', '', $instructions);
8194 - $instructions = preg_replace('/\s+/', ' ', trim($instructions)); // Clean up extra spaces
8195 - }
8196 -
8197 - // Replace {visitor_name} placeholder with actual visitor name if available
8198 - if (!empty($instructions) && !empty($session_id) && stripos($instructions, '{visitor_name}') !== false) {
8199 - $visitor_name = MxChat_Session_Store::get($session_id, 'name', '');
8200 -
8201 - if (!empty($visitor_name)) {
8202 - $instructions = str_ireplace('{visitor_name}', sanitize_text_field($visitor_name), $instructions);
8203 - } else {
8204 - // Remove placeholder if no name is available
8205 - $instructions = str_ireplace('{visitor_name}', '', $instructions);
8206 - $instructions = preg_replace('/\s{2,}/', ' ', trim($instructions)); // Clean up extra spaces
8207 - }
8208 - }
8209 -
8210 - // {context} placeholder (plan 59bc1b): inject the assembled knowledge-base
8211 - // block where the owner placed the token. Runs after the URL-strip and
8212 - // {visitor_name} handling and before the developer filter, so filtered
8213 - // instructions already show the final prompt. Only active once the KB
8214 - // assembly has stashed the block (context_kb_block non-null) — the early
8215 - // URL-extraction call happens before assembly and leaves the token alone.
8216 - if ($this->context_kb_block !== null && !empty($instructions) && stripos($instructions, '{context}') !== false) {
8217 - $pos = stripos($instructions, '{context}');
8218 - $instructions = substr($instructions, 0, $pos)
8219 - . rtrim($this->context_kb_block) . "\n"
8220 - . substr($instructions, $pos + strlen('{context}'));
8221 - // Additional occurrences are stripped — never duplicate the KB block.
8222 - $instructions = str_ireplace('{context}', '', $instructions);
8223 - }
8224 -
8225 - // Allow developers to filter system instructions and process shortcodes
8226 - $instructions = apply_filters('mxchat_system_instructions', $instructions, $bot_id, $session_id);
8227 - $instructions = do_shortcode($instructions);
8228 -
8229 - return $instructions;
8230 -}
8231 -/**
8232 - * Get the current bot ID from session or request context
8233 - */
8234 -private function get_current_bot_id($session_id = '') {
8235 - // First, check if bot_id is passed in the current request
8236 - if (isset($_POST['bot_id']) && !empty($_POST['bot_id'])) {
8237 - return sanitize_key($_POST['bot_id']);
8238 - }
8239 -
8240 - // If not in POST, try to get it from session data
8241 - if (!empty($session_id)) {
8242 - $bot_id = get_option("mxchat_session_bot_{$session_id}", '');
8243 - if (!empty($bot_id)) {
8244 - return $bot_id;
8245 - }
8246 - }
8247 -
8248 - // Fall back to default
8249 - return 'default';
8250 -}
8251 -/* ====================================================================== *
8252 - * Native function-calling loop (plan-mxchat-20260617-a41dee)
8253 - *
8254 - * Model-driven tool use. The model is offered MxChat's enabled callbacks as
8255 - * tools (sourced from MxChat_Tool_Registry, the single source the admin AI
8256 - * Tools checklist also reads). When the model calls a tool, the matching
8257 - * callback runs through its EXISTING permission checks, its output is fed
8258 - * back, and the loop continues up to a depth cap. INDEPENDENT of the
8259 - * intent→callback router — it runs only after intents miss, and works with
8260 - * ZERO Actions created.
8261 - *
8262 - * Entered ONLY when: function calling is enabled + the active model is
8263 - * tool-capable + at least one tool is enabled. Default-off, so existing
8264 - * installs never enter this branch (byte-for-byte unchanged behavior). The
8265 - * tool round is buffered (non-streaming) per the plan; the final answer is
8266 - * emitted via the same SSE/JSON envelopes the normal path uses.
8267 - * ====================================================================== */
8268 -
8269 -/** Gate: should the function-calling loop handle this turn? */
8270 -private function mxchat_fc_should_run($selected_model) {
8271 - if (!class_exists('MxChat_Tool_Registry') || !MxChat_Tool_Registry::is_enabled()) {
8272 - return false;
8273 - }
8274 - if (class_exists('MxChat_Model_Catalog') && !MxChat_Model_Catalog::supports_tools($selected_model)) {
8275 - return false;
8276 - }
8277 - $tools = MxChat_Tool_Registry::enabled_tools();
8278 - return !empty($tools);
8279 -}
8280 -
8281 -private function mxchat_fc_log($msg) {
8282 - if (defined('MXCHAT_DEV_MODE') && MXCHAT_DEV_MODE) {
8283 - error_log('[MxChat FC] ' . $msg);
8284 - }
8285 -}
8286 -
8287 -/**
8288 - * Resolve provider transport details. Returns null when FC can't run for this
8289 - * model/config (missing key, unsupported provider) so the caller falls back to
8290 - * the normal path. OpenAI/xAI/DeepSeek/OpenRouter/Custom share the
8291 - * OpenAI-compatible 'openai' family; Claude and Gemini are distinct.
8292 - */
8293 -private function mxchat_fc_resolve_provider($selected_model, $opts) {
8294 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
8295 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
8296 - if ($selected_model === 'claude-opus-4-20250514') { $selected_model = 'claude-opus-4-8'; }
8297 - elseif ($selected_model === 'claude-sonnet-4-20250514') { $selected_model = 'claude-sonnet-4-6'; }
8298 - if ($selected_model === 'openrouter') {
8299 - $model = isset($opts['openrouter_selected_model']) ? $opts['openrouter_selected_model'] : '';
8300 - $key = isset($opts['openrouter_api_key']) ? $opts['openrouter_api_key'] : '';
8301 - if ($model === '' || $key === '') return null;
8302 - return array('family'=>'openai','model'=>$model,'url'=>'https://openrouter.ai/api/v1/chat/completions',
8303 - 'headers'=>array('Content-Type'=>'application/json','Authorization'=>'Bearer '.$key),'tag'=>'openai');
8304 - }
8305 - $prefix = strtolower(explode('-', $selected_model)[0]);
8306 - switch ($prefix) {
8307 - case 'gpt': case 'o1': case 'o3': case 'o4':
8308 - $key = isset($opts['api_key']) ? $opts['api_key'] : '';
8309 - if ($key === '') return null;
8310 - return array('family'=>'openai','model'=>$selected_model,'url'=>'https://api.openai.com/v1/chat/completions',
8311 - 'headers'=>array('Content-Type'=>'application/json','Authorization'=>'Bearer '.$key),'tag'=>'openai');
8312 - case 'claude':
8313 - $key = isset($opts['claude_api_key']) ? $opts['claude_api_key'] : '';
8314 - if ($key === '') return null;
8315 - return array('family'=>'anthropic','model'=>$selected_model,'url'=>'https://api.anthropic.com/v1/messages',
8316 - 'headers'=>array('Content-Type'=>'application/json','x-api-key'=>$key,'anthropic-version'=>'2023-06-01'),'tag'=>'anthropic');
8317 - case 'gemini':
8318 - $key = isset($opts['gemini_api_key']) ? $opts['gemini_api_key'] : '';
8319 - if ($key === '') return null;
8320 - return array('family'=>'gemini','model'=>$selected_model,'key'=>$key,'tag'=>'gemini');
8321 - case 'grok': case 'xai':
8322 - $key = isset($opts['xai_api_key']) ? $opts['xai_api_key'] : '';
8323 - if ($key === '') return null;
8324 - return array('family'=>'openai','model'=>$selected_model,'url'=>'https://api.x.ai/v1/chat/completions',
8325 - 'headers'=>array('Content-Type'=>'application/json','Authorization'=>'Bearer '.$key),'tag'=>'xai');
8326 - case 'deepseek':
8327 - $key = isset($opts['deepseek_api_key']) ? $opts['deepseek_api_key'] : '';
8328 - if ($key === '') return null;
8329 - return array('family'=>'openai','model'=>$selected_model,'url'=>'https://api.deepseek.com/v1/chat/completions',
8330 - 'headers'=>array('Content-Type'=>'application/json','Authorization'=>'Bearer '.$key),'tag'=>'openai');
8331 - case 'custom':
8332 - $base = isset($opts['custom_provider_base_url']) ? rtrim($opts['custom_provider_base_url'], '/') : '';
8333 - $key = isset($opts['custom_provider_api_key']) ? $opts['custom_provider_api_key'] : '';
8334 - $model = isset($opts['custom_provider_model']) ? $opts['custom_provider_model'] : '';
8335 - if ($base === '' || $model === '') return null;
8336 - $url = (strpos($base, 'chat/completions') !== false) ? $base : $base . '/chat/completions';
8337 - $headers = array('Content-Type'=>'application/json');
8338 - if ($key !== '') $headers['Authorization'] = 'Bearer '.$key;
8339 - return array('family'=>'openai','model'=>$model,'url'=>$url,'headers'=>$headers,'tag'=>'openai');
8340 - }
8341 - return null;
8342 -}
8343 -
8344 -/**
8345 - * Top-level function-calling attempt. Returns:
8346 - * ['handled'=>true, 'text'=>'<final answer>'] when the model used ≥1 tool
8347 - * ['handled'=>false] otherwise (caller falls back
8348 - * to the normal streamed path)
8349 - */
8350 -private function mxchat_fc_attempt($message, $relevant_content, $conversation_history, $selected_model, $opts, $session_id, $user_id) {
8351 - $prov = $this->mxchat_fc_resolve_provider($selected_model, $opts);
8352 - if (!$prov) {
8353 - return array('handled' => false);
8354 - }
8355 - $tools = MxChat_Tool_Registry::enabled_tools();
8356 - if (empty($tools)) {
8357 - return array('handled' => false);
8358 - }
8359 -
8360 - $bot_id = $this->get_current_bot_id($session_id);
8361 - $system = $this->get_system_instructions($bot_id, $session_id);
8362 -
8363 - // Force callbacks into return-mode (some echo SSE directly when streaming);
8364 - // we buffer the whole tool round, then emit once. Restored in finally.
8365 - $prev_streaming = $this->is_streaming;
8366 - $this->is_streaming = false;
8367 - try {
8368 - if ($prov['family'] === 'anthropic') {
8369 - return $this->mxchat_fc_loop_anthropic($prov, $system, $relevant_content, $conversation_history, $tools, $message, $user_id, $session_id);
8370 - } elseif ($prov['family'] === 'gemini') {
8371 - return $this->mxchat_fc_loop_gemini($prov, $system, $relevant_content, $conversation_history, $tools, $message, $user_id, $session_id);
8372 - }
8373 - return $this->mxchat_fc_loop_openai($prov, $system, $relevant_content, $conversation_history, $tools, $message, $user_id, $session_id);
8374 - } catch (\Throwable $e) {
8375 - $this->mxchat_fc_log('attempt threw: ' . $e->getMessage());
8376 - return array('handled' => false);
8377 - } finally {
8378 - $this->is_streaming = $prev_streaming;
8379 - }
8380 -}
8381 -
8382 -/** Normalize MxChat history rows to [{role:user|assistant, content}]. */
8383 -private function mxchat_fc_normalize_history($conversation_history) {
8384 - $out = array();
8385 - if (!is_array($conversation_history)) return $out;
8386 - foreach ($conversation_history as $m) {
8387 - if (!is_array($m) || !isset($m['role']) || !isset($m['content'])) continue;
8388 - $role = $m['role'];
8389 - if ($role === 'bot' || $role === 'agent') $role = 'assistant';
8390 - if (!in_array($role, array('user', 'assistant'), true)) $role = 'user';
8391 - $out[] = array('role' => $role, 'content' => (string) $m['content']);
8392 - }
8393 - return $out;
8394 -}
8395 -
8396 -/* ---------------- Per-message AI Tools trace (plan-mxchat-20260813-470f68) ---------------- */
8397 -
8398 -/** Hard ceiling on recorded tool entries per message (multi-round loops included). */
8399 -const FC_TRACE_MAX_ENTRIES = 20;
8400 -/** Max stored length of a single tool's argument excerpt. */
8401 -const FC_TRACE_ARGS_MAX = 500;
8402 -/** Max stored length of a failed tool's error excerpt. */
8403 -const FC_TRACE_ERROR_MAX = 300;
8404 -
8405 -/** Byte-safe clip used by the trace (never splits a multibyte character). */
8406 -private function mxchat_fc_trace_clip($s, $max) {
8407 - $s = (string) $s;
8408 - if (function_exists('mb_strlen') && mb_strlen($s) > $max) {
8409 - return mb_substr($s, 0, $max) . '…';
8410 - }
8411 - if (!function_exists('mb_strlen') && strlen($s) > $max) {
8412 - return substr($s, 0, $max) . '…';
8413 - }
8414 - return $s;
8415 -}
8416 -
8417 -/**
8418 - * Argument excerpt for the trace: credential-looking values replaced, then
8419 - * clipped. There is no shared redaction list in the plugin (the dev-mode logger
8420 - * only str_replaces the known api key), so this list is the trace's own — it is
8421 - * matched on the KEY, recursively, because a nested arg is just as readable in
8422 - * the panel as a top-level one.
8423 - */
8424 -private function mxchat_fc_redact_args($args) {
8425 - if (!is_array($args)) {
8426 - return $args;
8427 - }
8428 - $out = array();
8429 - foreach ($args as $k => $v) {
8430 - if (is_string($k) && preg_match('/(api[_\-]?key|secret|token|password|passwd|pwd|credential|bearer|auth|signature|private[_\-]?key)/i', $k)) {
8431 - $out[$k] = '[redacted]';
8432 - continue;
8433 - }
8434 - $out[$k] = is_array($v) ? $this->mxchat_fc_redact_args($v) : $v;
8435 - }
8436 - return $out;
8437 -}
8438 -
8439 -/** Serialize a tool call's arguments for storage: redact, encode, clip. */
8440 -private function mxchat_fc_trace_args_excerpt($args) {
8441 - if ($args === null || $args === '' || $args === array()) {
8442 - return '';
8443 - }
8444 - $safe = $this->mxchat_fc_redact_args($args);
8445 - if (is_array($safe)) {
8446 - $json = wp_json_encode($safe, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
8447 - $safe = ($json === false) ? '' : $json;
8448 - }
8449 - return $this->mxchat_fc_trace_clip((string) $safe, self::FC_TRACE_ARGS_MAX);
8450 -}
8451 -
8452 -/**
8453 - * Record ONE tool execution for the message's trace. Called for every exit path
8454 - * of mxchat_fc_execute_tool — including "tool not available" and a callback that
8455 - * threw — because a tool that failed is exactly what an owner is hunting for.
8456 - */
8457 -private function mxchat_fc_record_tool_call($tool_name, $args, $result, $started) {
8458 - // Cap keeps a runaway multi-round loop from bloating the row. The FIRST
8459 - // entries are kept: they are the ones that explain how the turn began.
8460 - if (count($this->fc_tool_records) >= self::FC_TRACE_MAX_ENTRIES) {
8461 - return;
8462 - }
8463 -
8464 - $tool = MxChat_Tool_Registry::tool_by_name($tool_name, false); // may be null
8465 - $ok = is_array($result) && !empty($result['ok']);
8466 -
8467 - $record = array(
8468 - 'name' => (string) $tool_name,
8469 - 'label' => (is_array($tool) && !empty($tool['label'])) ? (string) $tool['label'] : (string) $tool_name,
8470 - 'ok' => $ok,
8471 - 'ms' => (int) round((microtime(true) - $started) * 1000),
8472 - );
8473 -
8474 - // Sensitive tools — the cautious/default-off list (money, cart mutation,
8475 - // customer PII, live-agent handoff, data-collection flows) — record the FACT
8476 - // that they fired and NOTHING of their arguments. The fired-fact is the half
8477 - // an owner most needs on exactly these tools; the arguments are the half that
8478 - // carries the PII.
8479 - if (is_array($tool) && !empty($tool['cautious'])) {
8480 - $record['args_redacted'] = 'sensitive';
8481 - } else {
8482 - $excerpt = $this->mxchat_fc_trace_args_excerpt($args);
8483 - if ($excerpt !== '') {
8484 - $record['args_excerpt'] = $excerpt;
8485 - }
8486 - }
8487 -
8488 - // Failures carry the error excerpt — that is the actual debugging value.
8489 - if (!$ok) {
8490 - $err = (is_array($result) && isset($result['content'])) ? (string) $result['content'] : '';
8491 - if ($err !== '') {
8492 - $record['error'] = $this->mxchat_fc_trace_clip($err, self::FC_TRACE_ERROR_MAX);
8493 - }
8494 - }
8495 -
8496 - $this->fc_tool_records[] = $record;
8497 -}
8498 -
8499 -/**
8500 - * Fold this turn's tool trace into the rag_context about to be stored.
8501 - *
8502 - * Additive by construction: with no tool records the argument is returned
8503 - * UNCHANGED (null stays null), so every non-FC save path is byte-identical to
8504 - * before. Called at each save site rather than inside mxchat_save_chat_message
8505 - * because a turn writes several bot rows (card html, video embed) and the trace
8506 - * belongs to the ANSWER row only.
8507 - */
8508 -private function mxchat_fc_attach_tool_trace($rag_context_for_storage) {
8509 - if (empty($this->fc_tool_records)) {
8510 - return $rag_context_for_storage;
8511 - }
8512 - if (!is_array($rag_context_for_storage)) {
8513 - $rag_context_for_storage = array();
8514 - }
8515 - $rag_context_for_storage['tool_calls'] = $this->fc_tool_records;
8516 - // Consume: a turn's trace attaches to ONE row. Without this a later save in
8517 - // the same request (product card, video embed) would carry a duplicate.
8518 - $this->fc_tool_records = array();
8519 - return $rag_context_for_storage;
8520 -}
8521 -
8522 -/** Execute the matched callback for a tool call. Returns ['ok'=>bool,'content'=>string]. */
8523 -private function mxchat_fc_execute_tool($tool_name, $args, $orig_message, $user_id, $session_id) {
8524 - $started = microtime(true);
8525 - $result = $this->mxchat_fc_execute_tool_inner($tool_name, $args, $orig_message, $user_id, $session_id);
8526 - $this->mxchat_fc_record_tool_call($tool_name, $args, $result, $started);
8527 - return $result;
8528 -}
8529 -
8530 -/** Unchanged tool-execution body; wrapped above so every exit path is traced. */
8531 -private function mxchat_fc_execute_tool_inner($tool_name, $args, $orig_message, $user_id, $session_id) {
8532 - $tool = MxChat_Tool_Registry::tool_by_name($tool_name, true); // enabled-only
8533 - if (!$tool) {
8534 - return array('ok' => false, 'content' => 'This tool is not available or not enabled.');
8535 - }
8536 - $fn = $tool['callback'];
8537 -
8538 - // MxChat callbacks are message-driven: hand them the model's `query`
8539 - // (falling back to the original user message).
8540 - $query = '';
8541 - if (is_array($args) && isset($args['query']) && is_string($args['query'])) {
8542 - $query = $args['query'];
8543 - }
8544 - if ($query === '') $query = $orig_message;
8545 -
8546 - // Synthetic intent row (matches wp_mxchat_intents columns → no undefined-prop warnings).
8547 - $synthetic_intent = (object) array(
8548 - 'id' => 0, 'intent_label' => $tool['label'], 'phrases' => '',
8549 - 'embedding_vector' => '', 'callback_function' => $fn,
8550 - 'similarity_threshold' => 0.0, 'enabled' => 1, 'enabled_bots' => null,
8551 - );
8552 -
8553 - try {
8554 - if (!empty($tool['is_addon'])) {
8555 - $result = apply_filters($fn, false, $query, $user_id, $session_id, $synthetic_intent);
8556 - } elseif (method_exists($this, $fn)) {
8557 - $result = call_user_func(array($this, $fn), $query, $user_id, $session_id, $synthetic_intent, null);
8558 - } else {
8559 - return array('ok' => false, 'content' => 'Tool implementation not found.');
8560 - }
8561 - } catch (\Throwable $e) {
8562 - $this->mxchat_fc_log("tool {$fn} threw: " . $e->getMessage());
8563 - return array('ok' => false, 'content' => 'The tool failed to run.');
8564 - }
8565 -
8566 - // plan-mxchat-20260617-48a57a — surface UI-bearing tool output.
8567 - // If the callback produced a UI element (generated image, product card, image
8568 - // gallery), its html MUST reach the FRONTEND as a real rendered bot message —
8569 - // NOT be stripped to text and handed to the model to paraphrase (that was the
8570 - // bug: under function calling, UI-bearing actions rendered nothing). Capture
8571 - // the html here; the FC outcome handler emits it in the response envelope.
8572 - $ui = $this->mxchat_fc_ui_payload_from($result);
8573 - if ($ui['html'] !== '' || !empty($ui['images'])) {
8574 - if ($ui['html'] !== '') {
8575 - $this->fc_ui_html .= ($this->fc_ui_html !== '' ? "\n" : '') . $ui['html'];
8576 - }
8577 - if (!empty($ui['images']) && is_array($ui['images'])) {
8578 - $this->fc_ui_images = array_merge($this->fc_ui_images, $ui['images']);
8579 - }
8580 - $this->fc_ui_captured = true;
8581 -
8582 - // Persist the html to the transcript ONLY if the callback did not already
8583 - // do so itself. Core image/search callbacks self-save (text + html);
8584 - // add-on callbacks (e.g. woo product cards) return html for the caller to
8585 - // save. ui_self_saves carries this from the registry; default by source
8586 - // (core self-saves, add-on does not) when a tool predates the flag.
8587 - $self_saves = array_key_exists('ui_self_saves', $tool)
8588 - ? !empty($tool['ui_self_saves'])
8589 - : empty($tool['is_addon']);
8590 - if ($ui['html'] !== '' && !$self_saves) {
8591 - $this->mxchat_save_chat_message($session_id, 'bot', $ui['html']);
8592 - }
8593 -
8594 - // Hand the MODEL a short acknowledgment (never the raw or stripped html)
8595 - // so the loop can add a one-line caption without trying to re-describe a
8596 - // visual it cannot see and without duplicating the displayed element.
8597 - $summary = isset($ui['text']) ? trim((string) $ui['text']) : '';
8598 - $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');
8599 - $content = $summary !== '' ? ($ack . ' ' . $summary) : $ack;
8600 - $this->mxchat_fc_log("executed {$fn} → [ui payload surfaced] " . substr($content, 0, 120));
8601 - return array('ok' => true, 'content' => $content);
8602 - }
8603 -
8604 - $content = $this->mxchat_fc_stringify_result($result);
8605 - $this->mxchat_fc_log("executed {$fn} → " . substr($content, 0, 160));
8606 - return array('ok' => true, 'content' => $content);
8607 -}
8608 -
8609 -/**
8610 - * Extract a UI payload (html + images + text) from a tool callback's return,
8611 - * falling back to $this->fallbackResponse for callbacks that return true after
8612 - * setting it. plan-mxchat-20260617-48a57a.
8613 - *
8614 - * @return array{html:string,images:array,text:string}
8615 - */
8616 -private function mxchat_fc_ui_payload_from($result) {
8617 - $src = null;
8618 - if (is_array($result)) {
8619 - $src = $result;
8620 - } elseif ($result === true && isset($this->fallbackResponse) && is_array($this->fallbackResponse)) {
8621 - $src = $this->fallbackResponse;
8622 - }
8623 - $html = (is_array($src) && isset($src['html']) && is_string($src['html'])) ? $src['html'] : '';
8624 - $images = (is_array($src) && isset($src['images']) && is_array($src['images'])) ? $src['images'] : array();
8625 - $text = (is_array($src) && isset($src['text'])) ? (string) $src['text'] : '';
8626 - return array('html' => $html, 'images' => $images, 'text' => $text);
8627 -}
8628 -
8629 -/** Coerce a callback's return (string|array|true|false) into a tool-result string. */
8630 -private function mxchat_fc_stringify_result($result) {
8631 - if (is_string($result)) {
8632 - return $result === '' ? 'No result.' : $result;
8633 - }
8634 - if ($result === true) {
8635 - // Callbacks that set fallbackResponse and return true.
8636 - $fb = isset($this->fallbackResponse) ? $this->fallbackResponse : null;
8637 - if (is_array($fb)) {
8638 - if (!empty($fb['text'])) return (string) $fb['text'];
8639 - if (!empty($fb['html'])) return wp_strip_all_tags((string) $fb['html']);
8640 - }
8641 - return 'Done.';
8642 - }
8643 - if ($result === false || $result === null) {
8644 - return 'No result.';
8645 - }
8646 - if (is_array($result)) {
8647 - if (isset($result['text']) && $result['text'] !== '') return (string) $result['text'];
8648 - if (isset($result['html']) && $result['html'] !== '') return wp_strip_all_tags((string) $result['html']);
8649 - $json = wp_json_encode($result);
8650 - return $json !== false ? $json : 'No result.';
8651 - }
8652 - return (string) $result;
8653 -}
8654 -
8655 -/** HTTP code + decoded body for a function-calling request. */
8656 -private function mxchat_fc_post($url, $body, $headers, $tag) {
8657 - $args = array(
8658 - 'body' => wp_json_encode($body),
8659 - 'headers' => $headers,
8660 - 'timeout' => 60,
8661 - 'redirection' => 5,
8662 - 'blocking' => true,
8663 - 'httpversion' => '1.0',
8664 - 'sslverify' => true,
8665 - );
8666 - $response = $this->mxchat_provider_call_with_retry($url, $args, $tag);
8667 - if (is_wp_error($response)) {
8668 - return array('code' => 0, 'data' => null, 'error' => $response->get_error_message());
8669 - }
8670 - $code = (int) wp_remote_retrieve_response_code($response);
8671 - $data = json_decode(wp_remote_retrieve_body($response), true);
8672 - return array('code' => $code, 'data' => $data, 'error' => null);
8673 -}
8674 -
8675 -/* ---------------- OpenAI-compatible loop (OpenAI/xAI/DeepSeek/OpenRouter/Custom) -------------- */
8676 -private function mxchat_fc_loop_openai($prov, $system, $relevant_content, $conversation_history, $tools, $orig_message, $user_id, $session_id) {
8677 - $messages = array();
8678 - $messages[] = array('role' => 'system', 'content' => $system . ' ' . $relevant_content);
8679 - foreach ($this->mxchat_fc_normalize_history($conversation_history) as $m) {
8680 - $messages[] = $m;
8681 - }
8682 -
8683 - $depth = MxChat_Tool_Registry::max_depth();
8684 - $budget = MxChat_Tool_Registry::max_tool_calls_per_turn();
8685 - $tool_schema = MxChat_Tool_Registry::to_openai_tools($tools);
8686 - $used_tool = false;
8687 - $calls_made = 0;
8688 -
8689 - for ($step = 0; $step <= $depth; $step++) {
8690 - $offer_tools = ($step < $depth) && !empty($tool_schema);
8691 - $body = array('model' => $prov['model'], 'messages' => $messages, 'temperature' => 1, 'stream' => false);
8692 - if (strpos($prov['url'], 'api.deepseek.com') !== false) {
8693 - // DeepSeek V4 defaults to thinking mode ON; tool loops want fast
8694 - // deterministic non-thinking turns (legacy deepseek-chat semantics).
8695 - $body['thinking'] = array('type' => 'disabled');
8696 - }
8697 - if ($offer_tools) {
8698 - $body['tools'] = $tool_schema;
8699 - $body['tool_choice'] = 'auto';
8700 - }
8701 - $r = $this->mxchat_fc_post($prov['url'], $body, $prov['headers'], $prov['tag']);
8702 - if ($r['code'] !== 200 || !is_array($r['data'])) {
8703 - $this->mxchat_fc_log('openai call failed: code=' . $r['code'] . ' err=' . ($r['error'] ?? ''));
8704 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
8705 - }
8706 - $msg = isset($r['data']['choices'][0]['message']) ? $r['data']['choices'][0]['message'] : null;
8707 - if (!$msg) {
8708 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
8709 - }
8710 - $tool_calls = isset($msg['tool_calls']) && is_array($msg['tool_calls']) ? $msg['tool_calls'] : array();
8711 - if (empty($tool_calls)) {
8712 - $text = isset($msg['content']) ? trim((string) $msg['content']) : '';
8713 - if (!$used_tool) return array('handled' => false); // model never used a tool → normal path
8714 - return array('handled' => true, 'text' => ($text !== '' ? $text : $this->mxchat_fc_giveup_text()));
8715 - }
8716 - // Append the assistant tool-call turn verbatim, then a tool result per call.
8717 - $used_tool = true;
8718 - $messages[] = $msg;
8719 - foreach ($tool_calls as $tc) {
8720 - if ($calls_made >= $budget) break;
8721 - $calls_made++;
8722 - $name = isset($tc['function']['name']) ? $tc['function']['name'] : '';
8723 - $args = array();
8724 - if (isset($tc['function']['arguments'])) {
8725 - $decoded = json_decode($tc['function']['arguments'], true);
8726 - if (is_array($decoded)) $args = $decoded;
8727 - }
8728 - $exec = $this->mxchat_fc_execute_tool($name, $args, $orig_message, $user_id, $session_id);
8729 - $messages[] = array(
8730 - 'role' => 'tool',
8731 - 'tool_call_id' => isset($tc['id']) ? $tc['id'] : '',
8732 - 'content' => $exec['content'],
8733 - );
8734 - }
8735 - }
8736 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
8737 -}
8738 -
8739 -/* ---------------- Anthropic Claude loop ---------------- */
8740 -private function mxchat_fc_loop_anthropic($prov, $system, $relevant_content, $conversation_history, $tools, $orig_message, $user_id, $session_id) {
8741 - $messages = $this->mxchat_fc_normalize_history($conversation_history);
8742 - $messages[] = array('role' => 'user', 'content' => $relevant_content);
8743 -
8744 - $depth = MxChat_Tool_Registry::max_depth();
8745 - $budget = MxChat_Tool_Registry::max_tool_calls_per_turn();
8746 - $tool_schema = MxChat_Tool_Registry::to_anthropic_tools($tools);
8747 - $omit_temp = $this->mxchat_claude_omits_temperature($prov['model']);
8748 - $used_tool = false;
8749 - $calls_made = 0;
8750 -
8751 - for ($step = 0; $step <= $depth; $step++) {
8752 - $offer_tools = ($step < $depth) && !empty($tool_schema);
8753 - $body = array('model' => $prov['model'], 'max_tokens' => 1024, 'temperature' => 0.8,
8754 - 'messages' => $messages,
8755 - // Breakpoint on the last system block caches tools+system
8756 - // together (tools precede system in Anthropic's prefix).
8757 - 'system' => $this->mxchat_anthropic_system_blocks($system));
8758 - if ($omit_temp) unset($body['temperature']);
8759 - if ($offer_tools) {
8760 - $body['tools'] = $tool_schema;
8761 - $body['tool_choice'] = array('type' => 'auto');
8762 - }
8763 - $r = $this->mxchat_fc_post($prov['url'], $body, $prov['headers'], $prov['tag']);
8764 - if ($r['code'] !== 200 || !is_array($r['data'])) {
8765 - $this->mxchat_fc_log('anthropic call failed: code=' . $r['code'] . ' err=' . ($r['error'] ?? ''));
8766 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
8767 - }
8768 - $content = isset($r['data']['content']) && is_array($r['data']['content']) ? $r['data']['content'] : array();
8769 - $tool_uses = array();
8770 - $text_out = '';
8771 - foreach ($content as $block) {
8772 - if (!isset($block['type'])) continue;
8773 - if ($block['type'] === 'tool_use') {
8774 - $tool_uses[] = $block;
8775 - } elseif ($block['type'] === 'text' && isset($block['text'])) {
8776 - $text_out .= $block['text'];
8777 - }
8778 - }
8779 - if (empty($tool_uses)) {
8780 - if (!$used_tool) return array('handled' => false);
8781 - $text_out = trim($text_out);
8782 - return array('handled' => true, 'text' => ($text_out !== '' ? $text_out : $this->mxchat_fc_giveup_text()));
8783 - }
8784 - // Append the assistant turn (the full content array), then a user turn of tool_result blocks.
8785 - $used_tool = true;
8786 - $messages[] = array('role' => 'assistant', 'content' => $content);
8787 - $results = array();
8788 - foreach ($tool_uses as $tu) {
8789 - if ($calls_made >= $budget) break;
8790 - $calls_made++;
8791 - $name = isset($tu['name']) ? $tu['name'] : '';
8792 - $args = isset($tu['input']) && is_array($tu['input']) ? $tu['input'] : array();
8793 - $exec = $this->mxchat_fc_execute_tool($name, $args, $orig_message, $user_id, $session_id);
8794 - $results[] = array(
8795 - 'type' => 'tool_result',
8796 - 'tool_use_id' => isset($tu['id']) ? $tu['id'] : '',
8797 - 'content' => $exec['content'],
8798 - );
8799 - }
8800 - $messages[] = array('role' => 'user', 'content' => $results);
8801 - }
8802 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
8803 -}
8804 -
8805 -/* ---------------- Google Gemini loop ---------------- */
8806 -private function mxchat_fc_loop_gemini($prov, $system, $relevant_content, $conversation_history, $tools, $orig_message, $user_id, $session_id) {
8807 - $contents = array();
8808 - $contents[] = array('role' => 'user', 'parts' => array(array('text' => '[System Instructions] ' . $system . ' ' . $relevant_content)));
8809 - $contents[] = array('role' => 'model', 'parts' => array(array('text' => 'I understand and will follow these instructions.')));
8810 - foreach ($this->mxchat_fc_normalize_history($conversation_history) as $m) {
8811 - $contents[] = array('role' => ($m['role'] === 'assistant' ? 'model' : 'user'),
8812 - 'parts' => array(array('text' => $m['content'])));
8813 - }
8814 -
8815 - $depth = MxChat_Tool_Registry::max_depth();
8816 - $budget = MxChat_Tool_Registry::max_tool_calls_per_turn();
8817 - $tool_schema = MxChat_Tool_Registry::to_gemini_tools($tools);
8818 - // Function calling (tools + functionDeclarations + toolConfig) is a v1beta feature on the
8819 - // Generative Language REST API. The v1 endpoint silently ignores the tools array, so a
8820 - // non-preview model (e.g. gemini-2.5-pro, gemini-3.5-flash, gemini-3.1-flash-lite) would
8821 - // just answer in text and never emit a tool call. Always use v1beta for the FC loop —
8822 - // confirmed against Google's function-calling docs (their REST example targets
8823 - // v1beta/models/gemini-3.5-flash:generateContent). v1beta is a superset, so every model
8824 - // reachable on v1 is also reachable here.
8825 - $api_version = 'v1beta';
8826 - $url = 'https://generativelanguage.googleapis.com/' . $api_version . '/models/' . $prov['model'] . ':generateContent?key=' . $prov['key'];
8827 - $headers = array('Content-Type' => 'application/json');
8828 - $used_tool = false;
8829 - $calls_made = 0;
8830 -
8831 - for ($step = 0; $step <= $depth; $step++) {
8832 - $offer_tools = ($step < $depth) && !empty($tool_schema);
8833 - $body = array(
8834 - 'contents' => $contents,
8835 - 'generationConfig' => array('temperature' => 0.7, 'topP' => 0.95, 'topK' => 40, 'maxOutputTokens' => 8192),
8836 - );
8837 - if ($offer_tools) {
8838 - $body['tools'] = $tool_schema;
8839 - $body['toolConfig'] = array('functionCallingConfig' => array('mode' => 'AUTO'));
8840 - }
8841 - $r = $this->mxchat_fc_post($url, $body, $headers, 'gemini');
8842 - if ($r['code'] !== 200 || !is_array($r['data']) || isset($r['data']['error'])) {
8843 - $this->mxchat_fc_log('gemini call failed: code=' . $r['code'] . ' err=' . ($r['error'] ?? ''));
8844 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
8845 - }
8846 - $parts = isset($r['data']['candidates'][0]['content']['parts']) && is_array($r['data']['candidates'][0]['content']['parts'])
8847 - ? $r['data']['candidates'][0]['content']['parts'] : array();
8848 - $fn_calls = array();
8849 - $text_out = '';
8850 - foreach ($parts as $p) {
8851 - if (isset($p['functionCall'])) {
8852 - $fn_calls[] = $p['functionCall'];
8853 - } elseif (isset($p['text'])) {
8854 - $text_out .= $p['text'];
8855 - }
8856 - }
8857 - if (empty($fn_calls)) {
8858 - if (!$used_tool) return array('handled' => false);
8859 - $text_out = trim($text_out);
8860 - return array('handled' => true, 'text' => ($text_out !== '' ? $text_out : $this->mxchat_fc_giveup_text()));
8861 - }
8862 - // Append the model turn (its parts) then a user turn of functionResponse parts.
8863 - $used_tool = true;
8864 - $contents[] = array('role' => 'model', 'parts' => $parts);
8865 - $resp_parts = array();
8866 - foreach ($fn_calls as $fcall) {
8867 - if ($calls_made >= $budget) break;
8868 - $calls_made++;
8869 - $name = isset($fcall['name']) ? $fcall['name'] : '';
8870 - $args = isset($fcall['args']) && is_array($fcall['args']) ? $fcall['args'] : array();
8871 - $exec = $this->mxchat_fc_execute_tool($name, $args, $orig_message, $user_id, $session_id);
8872 - $fr = array('name' => $name, 'response' => array('result' => $exec['content']));
8873 - // Gemini 3 function calls carry a unique id; echo the matching id back in the
8874 - // functionResponse so the model maps the result to the right call (Google REST
8875 - // guidance). Older models omit the id — then we send none, exactly as before.
8876 - if (isset($fcall['id']) && $fcall['id'] !== '') { $fr['id'] = $fcall['id']; }
8877 - $resp_parts[] = array('functionResponse' => $fr);
8878 - }
8879 - $contents[] = array('role' => 'user', 'parts' => $resp_parts);
8880 - }
8881 - return $used_tool ? array('handled' => true, 'text' => $this->mxchat_fc_giveup_text()) : array('handled' => false);
8882 -}
8883 -
8884 -private function mxchat_fc_giveup_text() {
8885 - return esc_html__('I looked into that but could not put together a final answer. Please try rephrasing your request.', 'mxchat');
8886 -}
8887 -
8888 -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.6-sol') {
8889 - try {
8890 - if (!$relevant_content) {
8891 - $error_response = [
8892 - 'error' => esc_html__("I couldn't find relevant information on that topic.", 'mxchat'),
8893 - 'error_code' => 'no_relevant_content'
8894 - ];
8895 -
8896 - if ($testing_data !== null) {
8897 - $error_response['testing_data'] = $testing_data;
8898 - }
8899 -
8900 - return $error_response;
8901 - }
8902 -
8903 - if (!is_array($conversation_history)) {
8904 - $conversation_history = array();
8905 - }
8906 -
8907 - // Check if this is an OpenRouter model
8908 - if ($selected_model === 'openrouter') {
8909 - // Get the actual OpenRouter model from options
8910 - $openrouter_selected_model = $this->options['openrouter_selected_model'] ?? '';
8911 -
8912 - if (empty($openrouter_selected_model)) {
8913 - $error_response = [
8914 - 'error' => esc_html__('No OpenRouter model selected. Please select a model in settings.', 'mxchat'),
8915 - 'error_code' => 'no_openrouter_model_selected'
8916 - ];
8917 - if ($testing_data !== null) {
8918 - $error_response['testing_data'] = $testing_data;
8919 - }
8920 - return $error_response;
8921 - }
8922 -
8923 - if (empty($openrouter_api_key)) {
8924 - $error_response = [
8925 - 'error' => esc_html__('OpenRouter API key is not configured', 'mxchat'),
8926 - 'error_code' => 'missing_openrouter_api_key'
8927 - ];
8928 - if ($testing_data !== null) {
8929 - $error_response['testing_data'] = $testing_data;
8930 - }
8931 - return $error_response;
8932 - }
8933 -
8934 - if ($streaming) {
8935 - return $this->mxchat_generate_response_openrouter_stream(
8936 - $openrouter_selected_model,
8937 - $openrouter_api_key,
8938 - $conversation_history,
8939 - $relevant_content,
8940 - $session_id,
8941 - $testing_data
8942 - );
8943 - } else {
8944 - $response = $this->mxchat_generate_response_openrouter(
8945 - $openrouter_selected_model,
8946 - $openrouter_api_key,
8947 - $conversation_history,
8948 - $relevant_content,
8949 - $session_id
8950 - );
8951 - }
8952 -
8953 - if (is_array($response) && isset($response['error'])) {
8954 - if ($testing_data !== null) {
8955 - $response['testing_data'] = $testing_data;
8956 - }
8957 - return $response;
8958 - }
8959 -
8960 - return $response;
8961 - }
8962 -
8963 - // Extract model prefix to determine the provider
8964 - $model_parts = explode('-', $selected_model);
8965 - $provider = strtolower($model_parts[0]);
8966 -
8967 - // Handle model selection based on provider prefix
8968 - switch ($provider) {
8969 - case 'gemini':
8970 - if (empty($gemini_api_key)) {
8971 - $error_response = [
8972 - 'error' => esc_html__('Google Gemini API key is not configured', 'mxchat'),
8973 - 'error_code' => 'missing_gemini_api_key'
8974 - ];
8975 - if ($testing_data !== null) {
8976 - $error_response['testing_data'] = $testing_data;
8977 - }
8978 - return $error_response;
8979 - }
8980 - $response = $this->mxchat_generate_response_gemini(
8981 - $selected_model,
8982 - $gemini_api_key,
8983 - $conversation_history,
8984 - $relevant_content,
8985 - $session_id
8986 - );
8987 - break;
8988 -
8989 - case 'claude':
8990 - if (empty($claude_api_key)) {
8991 - $error_response = [
8992 - 'error' => esc_html__('Claude API key is not configured', 'mxchat'),
8993 - 'error_code' => 'missing_claude_api_key'
8994 - ];
8995 - if ($testing_data !== null) {
8996 - $error_response['testing_data'] = $testing_data;
8997 - }
8998 - return $error_response;
8999 - }
9000 - if ($streaming) {
9001 - return $this->mxchat_generate_response_claude_stream(
9002 - $selected_model,
9003 - $claude_api_key,
9004 - $conversation_history,
9005 - $relevant_content,
9006 - $session_id,
9007 - $testing_data
9008 - );
9009 - } else {
9010 - $response = $this->mxchat_generate_response_claude(
9011 - $selected_model,
9012 - $claude_api_key,
9013 - $conversation_history,
9014 - $relevant_content,
9015 - $session_id
9016 - );
9017 - }
9018 - break;
9019 -
9020 - case 'grok':
9021 - if (empty($xai_api_key)) {
9022 - $error_response = [
9023 - 'error' => esc_html__('X.AI API key is not configured', 'mxchat'),
9024 - 'error_code' => 'missing_xai_api_key'
9025 - ];
9026 - if ($testing_data !== null) {
9027 - $error_response['testing_data'] = $testing_data;
9028 - }
9029 - return $error_response;
9030 - }
9031 - if ($streaming) {
9032 - return $this->mxchat_generate_response_xai_stream(
9033 - $selected_model,
9034 - $xai_api_key,
9035 - $conversation_history,
9036 - $relevant_content,
9037 - $session_id,
9038 - $testing_data
9039 - );
9040 - } else {
9041 - $response = $this->mxchat_generate_response_xai(
9042 - $selected_model,
9043 - $xai_api_key,
9044 - $conversation_history,
9045 - $relevant_content,
9046 - $session_id
9047 - );
9048 - }
9049 - break;
9050 -
9051 - case 'deepseek':
9052 - if (empty($deepseek_api_key)) {
9053 - $error_response = [
9054 - 'error' => esc_html__('DeepSeek API key is not configured', 'mxchat'),
9055 - 'error_code' => 'missing_deepseek_api_key'
9056 - ];
9057 - if ($testing_data !== null) {
9058 - $error_response['testing_data'] = $testing_data;
9059 - }
9060 - return $error_response;
9061 - }
9062 - if ($streaming) {
9063 - return $this->mxchat_generate_response_deepseek_stream(
9064 - $selected_model,
9065 - $deepseek_api_key,
9066 - $conversation_history,
9067 - $relevant_content,
9068 - $session_id,
9069 - $testing_data
9070 - );
9071 - } else {
9072 - $response = $this->mxchat_generate_response_deepseek(
9073 - $selected_model,
9074 - $deepseek_api_key,
9075 - $conversation_history,
9076 - $relevant_content,
9077 - $session_id
9078 - );
9079 - }
9080 - break;
9081 -
9082 - case 'custom':
9083 - // Custom (OpenAI-compatible) provider — Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI
9084 - $cp_base_url = isset($this->options['custom_provider_base_url']) ? trim((string) $this->options['custom_provider_base_url']) : '';
9085 - if (empty($cp_base_url)) {
9086 - $error_response = [
9087 - 'error' => esc_html__('Custom provider is not configured. Set Base URL in MxChat → API Keys → Custom Provider.', 'mxchat'),
9088 - 'error_code' => 'missing_custom_provider_base_url'
9089 - ];
9090 - if ($testing_data !== null) {
9091 - $error_response['testing_data'] = $testing_data;
9092 - }
9093 - return $error_response;
9094 - }
9095 - if ($streaming) {
9096 - return $this->mxchat_generate_response_custom_stream(
9097 - $selected_model,
9098 - $conversation_history,
9099 - $relevant_content,
9100 - $session_id,
9101 - $testing_data
9102 - );
9103 - } else {
9104 - $response = $this->mxchat_generate_response_custom(
9105 - $selected_model,
9106 - $conversation_history,
9107 - $relevant_content
9108 - );
9109 - }
9110 - break;
9111 -
9112 - case 'gpt':
9113 - case 'o1':
9114 - if (empty($api_key)) {
9115 - $error_response = [
9116 - 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
9117 - 'error_code' => 'missing_openai_api_key'
9118 - ];
9119 - if ($testing_data !== null) {
9120 - $error_response['testing_data'] = $testing_data;
9121 - }
9122 - return $error_response;
9123 - }
9124 -
9125 - // Check if web search is enabled for this OpenAI model
9126 - $web_search_enabled = isset($this->options['enable_web_search']) && $this->options['enable_web_search'] === 'on';
9127 - // Models that don't support web search
9128 - $unsupported_web_search_models = array('gpt-4.1-nano');
9129 - $model_supports_web_search = !in_array($selected_model, $unsupported_web_search_models);
9130 -
9131 - if ($web_search_enabled && $model_supports_web_search) {
9132 - // Use Responses API (required for some models, or when web search is enabled)
9133 - return $this->mxchat_generate_response_openai_web_search(
9134 - $selected_model,
9135 - $api_key,
9136 - $conversation_history,
9137 - $relevant_content,
9138 - $session_id,
9139 - $testing_data,
9140 - $streaming
9141 - );
9142 - } elseif ($streaming) {
9143 - return $this->mxchat_generate_response_openai_stream(
9144 - $selected_model,
9145 - $api_key,
9146 - $conversation_history,
9147 - $relevant_content,
9148 - $session_id,
9149 - $testing_data
9150 - );
9151 - } else {
9152 - $response = $this->mxchat_generate_response_openai(
9153 - $selected_model,
9154 - $api_key,
9155 - $conversation_history,
9156 - $relevant_content,
9157 - $session_id
9158 - );
9159 - }
9160 - break;
9161 -
9162 - default:
9163 - if (empty($api_key)) {
9164 - $error_response = [
9165 - 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
9166 - 'error_code' => 'missing_openai_api_key'
9167 - ];
9168 - if ($testing_data !== null) {
9169 - $error_response['testing_data'] = $testing_data;
9170 - }
9171 - return $error_response;
9172 - }
9173 -
9174 - // Check if web search is enabled (default case also handles OpenAI models)
9175 - $web_search_enabled = isset($this->options['enable_web_search']) && $this->options['enable_web_search'] === 'on';
9176 - $unsupported_web_search_models = array('gpt-4.1-nano');
9177 - $model_supports_web_search = !in_array($selected_model, $unsupported_web_search_models);
9178 -
9179 - if ($web_search_enabled && $model_supports_web_search) {
9180 - return $this->mxchat_generate_response_openai_web_search(
9181 - $selected_model,
9182 - $api_key,
9183 - $conversation_history,
9184 - $relevant_content,
9185 - $session_id,
9186 - $testing_data,
9187 - $streaming
9188 - );
9189 - } elseif ($streaming) {
9190 - return $this->mxchat_generate_response_openai_stream(
9191 - $selected_model,
9192 - $api_key,
9193 - $conversation_history,
9194 - $relevant_content,
9195 - $session_id,
9196 - $testing_data
9197 - );
9198 - } else {
9199 - $response = $this->mxchat_generate_response_openai(
9200 - $selected_model,
9201 - $api_key,
9202 - $conversation_history,
9203 - $relevant_content,
9204 - $session_id
9205 - );
9206 - }
9207 - break;
9208 - }
9209 -
9210 - if (is_array($response) && isset($response['error'])) {
9211 - if ($testing_data !== null) {
9212 - $response['testing_data'] = $testing_data;
9213 - }
9214 - return $response;
9215 - }
9216 -
9217 - return $response;
9218 -
9219 - } catch (Exception $e) {
9220 - $error_response = [
9221 - 'error' => sprintf(esc_html__('An error occurred: %s', 'mxchat'), esc_html($e->getMessage())),
9222 - 'error_code' => 'system_exception',
9223 - 'exception_details' => $e->getMessage()
9224 - ];
9225 -
9226 - if ($testing_data !== null) {
9227 - $error_response['testing_data'] = $testing_data;
9228 - }
9229 -
9230 - return $error_response;
9231 - }
9232 -}
9233 -private function mxchat_generate_response_openrouter_stream($selected_model, $openrouter_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
9234 - try {
9235 - $bot_id = $this->get_current_bot_id($session_id);
9236 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
9237 -
9238 - if (!is_array($conversation_history)) {
9239 - $conversation_history = array();
9240 - }
9241 -
9242 - $formatted_conversation = array();
9243 -
9244 - $formatted_conversation[] = array(
9245 - 'role' => 'system',
9246 - 'content' => $system_prompt_instructions . " " . $relevant_content
9247 - );
9248 -
9249 - foreach ($conversation_history as $message) {
9250 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
9251 - $role = $message['role'];
9252 - if ($role === 'bot' || $role === 'agent') {
9253 - $role = 'assistant';
9254 - }
9255 - if (!in_array($role, ['system', 'assistant', 'user'])) {
9256 - $role = 'user';
9257 - }
9258 - $formatted_conversation[] = array(
9259 - 'role' => $role,
9260 - 'content' => $message['content']
9261 - );
9262 - }
9263 - }
9264 -
9265 - if (headers_sent() || !function_exists('curl_init')) {
9266 - $regular_response = $this->mxchat_generate_response_openrouter(
9267 - $selected_model,
9268 - $openrouter_api_key,
9269 - $conversation_history,
9270 - $relevant_content,
9271 - $session_id
9272 - );
9273 -
9274 - // Save bot response to transcript
9275 - if (!empty($regular_response) && !empty($session_id)) {
9276 - $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
9277 - }
9278 -
9279 - $response_data = [
9280 - 'text' => $regular_response,
9281 - 'html' => '',
9282 - 'session_id' => $session_id
9283 - ];
9284 -
9285 - if ($testing_data !== null) {
9286 - $response_data['testing_data'] = $testing_data;
9287 - }
9288 -
9289 - header('Content-Type: application/json');
9290 - echo json_encode($response_data);
9291 - return true;
9292 - }
9293 -
9294 - $body = json_encode([
9295 - 'model' => $selected_model,
9296 - 'messages' => $formatted_conversation,
9297 - 'temperature' => 1,
9298 - 'stream' => true
9299 - ]);
9300 -
9301 - // V2 retry-on-initial-connect: setup_streaming_headers is now lazy-fired
9302 - // inside WRITEFUNCTION on first byte of a successful upstream.
9303 -
9304 - $captured_status_code = 0;
9305 - $captured_body_pre_stream = '';
9306 - $full_response = '';
9307 - $stream_started = false;
9308 - $buffer = '';
9309 - $errno = 0;
9310 - $last_curl_error = '';
9311 - $http_code = 0;
9312 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
9313 - $backoff_ms = array(0, 750, 2000);
9314 -
9315 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
9316 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
9317 - usleep($backoff_ms[$attempt] * 1000);
9318 - }
9319 -
9320 - $captured_status_code = 0;
9321 - $captured_body_pre_stream = '';
9322 - $full_response = '';
9323 - $stream_started = false;
9324 - $buffer = '';
9325 -
9326 - $ch = curl_init();
9327 - curl_setopt($ch, CURLOPT_URL, 'https://openrouter.ai/api/v1/chat/completions');
9328 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
9329 - curl_setopt($ch, CURLOPT_POST, true);
9330 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
9331 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
9332 - 'Content-Type: application/json',
9333 - 'Authorization: Bearer ' . $openrouter_api_key,
9334 - 'HTTP-Referer: ' . home_url(),
9335 - 'X-Title: ' . get_bloginfo('name')
9336 - ));
9337 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
9338 - curl_setopt($ch, CURLOPT_TIMEOUT, 60);
9339 -
9340 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
9341 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
9342 - $captured_status_code = (int) $m[1];
9343 - }
9344 - return strlen($header);
9345 - });
9346 -
9347 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
9348 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
9349 - $captured_body_pre_stream .= $data;
9350 - return strlen($data);
9351 - }
9352 -
9353 - if (!$this->streaming_headers_sent) {
9354 - $this->setup_streaming_headers();
9355 - }
9356 -
9357 - if (!$stream_started && $testing_data !== null) {
9358 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
9359 - flush();
9360 - $stream_started = true;
9361 - }
9362 -
9363 - $buffer .= $data;
9364 - $lines = explode("\n", $buffer);
9365 - $buffer = array_pop($lines);
9366 -
9367 - foreach ($lines as $line) {
9368 - if (trim($line) === '') {
9369 - continue;
9370 - }
9371 - if (strpos($line, 'data: ') !== 0) {
9372 - continue;
9373 - }
9374 -
9375 - $json_str = substr($line, 6);
9376 -
9377 - if (trim($json_str) === '[DONE]') {
9378 - echo "data: [DONE]\n\n";
9379 - flush();
9380 - continue;
9381 - }
9382 -
9383 - $json = json_decode(trim($json_str), true);
9384 - if ($json && isset($json['choices'][0]['delta']['content'])) {
9385 - $content = $json['choices'][0]['delta']['content'];
9386 - $full_response .= $content;
9387 -
9388 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
9389 - flush();
9390 - }
9391 - }
9392 -
9393 - return strlen($data);
9394 - });
9395 -
9396 - $response = curl_exec($ch);
9397 - $errno = curl_errno($ch);
9398 - $last_curl_error = curl_error($ch);
9399 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
9400 - curl_close($ch);
9401 -
9402 - if (!$errno && $http_code === 200) {
9403 - break;
9404 - }
9405 -
9406 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'openai', $errno);
9407 - $can_retry = !$this->streaming_headers_sent
9408 - && ($attempt + 1) < $max_attempts
9409 - && $is_transient;
9410 -
9411 - if (defined('WP_DEBUG') && WP_DEBUG) {
9412 - error_log(sprintf(
9413 - '[MxChat] openrouter_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
9414 - $attempt + 1, $max_attempts, $http_code, $errno,
9415 - $is_transient ? 'yes' : 'no',
9416 - $can_retry ? 'Retrying.' : 'Giving up.'
9417 - ));
9418 - }
9419 -
9420 - if (!$can_retry) {
9421 - break;
9422 - }
9423 - }
9424 -
9425 - if (!$errno && $http_code === 200) {
9426 - if (!empty($full_response) && !empty($session_id)) {
9427 - $rag_context_for_storage = null;
9428 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
9429 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
9430 -
9431 - if ($has_rag_data || $has_action_data) {
9432 - $rag_context_for_storage = [];
9433 -
9434 - if ($has_rag_data) {
9435 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
9436 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
9437 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
9438 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
9439 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
9440 - }
9441 -
9442 - if ($has_action_data) {
9443 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
9444 - }
9445 - }
9446 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $this->mxchat_fc_attach_tool_trace($rag_context_for_storage));
9447 - }
9448 - return true;
9449 - }
9450 -
9451 - return $this->mxchat_stream_emit_fallback(
9452 - 'openai',
9453 - $this->mxchat_generate_response_openrouter($selected_model, $openrouter_api_key, $conversation_history, $relevant_content, $session_id),
9454 - $session_id,
9455 - $testing_data
9456 - );
9457 -
9458 - } catch (Exception $e) {
9459 - return $this->mxchat_stream_emit_fallback(
9460 - 'openai',
9461 - $this->mxchat_generate_response_openrouter($selected_model, $openrouter_api_key, $conversation_history, $relevant_content, $session_id),
9462 - $session_id,
9463 - $testing_data
9464 - );
9465 - }
9466 -}
9467 -private function mxchat_generate_response_openai_stream($selected_model, $api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
9468 - // OpenAI retires gpt-5.1-chat-latest / gpt-5.3-chat-latest on 2026-08-10
9469 - // (replacement gpt-5.6-sol). Read-time rescue mirrors the non-streaming
9470 - // path (plan e46b8f).
9471 - if ($selected_model === 'gpt-5.1-chat-latest' || $selected_model === 'gpt-5.3-chat-latest') { $selected_model = 'gpt-5.6-sol'; }
9472 - try {
9473 - $bot_id = $this->get_current_bot_id($session_id);
9474 -
9475 - // Get system prompt instructions using centralized function
9476 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
9477 -
9478 - // Ensure conversation_history is an array
9479 - if (!is_array($conversation_history)) {
9480 - $conversation_history = array();
9481 - }
9482 -
9483 - // Format conversation history for OpenAI
9484 - $formatted_conversation = array();
9485 -
9486 - $formatted_conversation[] = array(
9487 - 'role' => 'system',
9488 - 'content' => $system_prompt_instructions . " " . $relevant_content
9489 - );
9490 -
9491 - foreach ($conversation_history as $message) {
9492 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
9493 - $role = $message['role'];
9494 - if ($role === 'bot' || $role === 'agent') {
9495 - $role = 'assistant';
9496 - }
9497 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
9498 - $role = 'user';
9499 - }
9500 - $formatted_conversation[] = array(
9501 - 'role' => $role,
9502 - 'content' => $message['content']
9503 - );
9504 - }
9505 - }
9506 -
9507 - // Check if we can actually stream
9508 - if (headers_sent() || !function_exists('curl_init')) {
9509 - // Fallback to regular response with testing data
9510 - $regular_response = $this->mxchat_generate_response_openai(
9511 - $selected_model,
9512 - $api_key,
9513 - $conversation_history,
9514 - $relevant_content,
9515 - $session_id
9516 - );
9517 -
9518 - // Save bot response to transcript
9519 - if (!empty($regular_response) && !empty($session_id)) {
9520 - $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
9521 - }
9522 -
9523 - $response_data = [
9524 - 'text' => $regular_response,
9525 - 'html' => '',
9526 - 'session_id' => $session_id
9527 - ];
9528 -
9529 - if ($testing_data !== null) {
9530 - $response_data['testing_data'] = $testing_data;
9531 - }
9532 -
9533 - header('Content-Type: application/json');
9534 - echo json_encode($response_data);
9535 - return true;
9536 - }
9537 -
9538 - // Build request body with optimal settings for fast streaming
9539 - $request_body = [
9540 - 'model' => $selected_model,
9541 - 'messages' => $formatted_conversation,
9542 - 'temperature' => 1,
9543 - 'stream' => true
9544 - ];
9545 -
9546 - // reasoning_effort — sourced from the core model catalog (plan-dcb71c);
9547 - // frozen inline ladder lives in mxchat_reasoning_effort_fallback().
9548 - $effort = $this->mxchat_reasoning_effort_for($selected_model, 'chat');
9549 - if ($effort !== null) {
9550 - $request_body['reasoning_effort'] = $effort;
9551 - }
9552 -
9553 - $body = json_encode($request_body);
9554 -
9555 - // V2 retry-on-initial-connect: do NOT call setup_streaming_headers() here.
9556 - // It is now lazy-fired inside the WRITEFUNCTION on the first byte of a
9557 - // SUCCESSFUL upstream response, gated by the captured HTTP status.
9558 -
9559 - $captured_status_code = 0;
9560 - $captured_body_pre_stream = '';
9561 - $full_response = '';
9562 - $stream_started = false;
9563 - $buffer = '';
9564 - $errno = 0;
9565 - $last_curl_error = '';
9566 - $http_code = 0;
9567 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
9568 - $backoff_ms = array(0, 750, 2000);
9569 - $reasoning_stripped = false; // plan-25b972: one strip-and-retry allowed
9570 -
9571 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
9572 - $delay = isset($backoff_ms[$attempt]) ? $backoff_ms[$attempt] : 0;
9573 - if ($attempt > 0 && $delay > 0) {
9574 - usleep($delay * 1000);
9575 - }
9576 -
9577 - // Reset per-attempt capture state.
9578 - $captured_status_code = 0;
9579 - $captured_body_pre_stream = '';
9580 - $full_response = '';
9581 - $stream_started = false;
9582 - $buffer = '';
9583 -
9584 - $ch = curl_init();
9585 - curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
9586 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
9587 - curl_setopt($ch, CURLOPT_POST, true);
9588 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
9589 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
9590 - 'Content-Type: application/json',
9591 - 'Authorization: Bearer ' . $api_key
9592 - ));
9593 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
9594 - curl_setopt($ch, CURLOPT_TIMEOUT, 60);
9595 -
9596 - // Capture HTTP status as soon as response headers arrive — fires before WRITEFUNCTION.
9597 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
9598 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
9599 - $captured_status_code = (int) $m[1];
9600 - }
9601 - return strlen($header);
9602 - });
9603 -
9604 - // Buffer control for real-time streaming
9605 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
9606 - // V2 guard: if upstream returned non-200, buffer body for transient
9607 - // classification and DO NOT emit to client. Stream channel must NOT open.
9608 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
9609 - $captured_body_pre_stream .= $data;
9610 - return strlen($data);
9611 - }
9612 -
9613 - // Lazy-fire streaming headers on first byte of a SUCCESSFUL upstream.
9614 - // After this point streaming_headers_sent === true → retry is structurally blocked.
9615 - if (!$this->streaming_headers_sent) {
9616 - $this->setup_streaming_headers();
9617 - }
9618 -
9619 - // Send testing data as the first event if available
9620 - if (!$stream_started && $testing_data !== null) {
9621 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
9622 - flush();
9623 - $stream_started = true;
9624 - }
9625 -
9626 - // CRITICAL FIX: Append new data to buffer
9627 - $buffer .= $data;
9628 -
9629 - // Process complete lines only
9630 - $lines = explode("\n", $buffer);
9631 -
9632 - // CRITICAL FIX: Keep the last incomplete line in the buffer
9633 - $buffer = array_pop($lines);
9634 -
9635 - foreach ($lines as $line) {
9636 - if (trim($line) === '') {
9637 - continue;
9638 - }
9639 - if (strpos($line, 'data: ') !== 0) {
9640 - continue;
9641 - }
9642 -
9643 - $json_str = substr($line, 6);
9644 -
9645 - if (trim($json_str) === '[DONE]') {
9646 - echo "data: [DONE]\n\n";
9647 - flush();
9648 - continue;
9649 - }
9650 -
9651 - $json = json_decode(trim($json_str), true);
9652 - if ($json && isset($json['choices'][0]['delta']['content'])) {
9653 - $content = $json['choices'][0]['delta']['content'];
9654 - $full_response .= $content;
9655 -
9656 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
9657 - flush();
9658 - }
9659 - }
9660 -
9661 - return strlen($data);
9662 - });
9663 -
9664 - $response = curl_exec($ch);
9665 - $errno = curl_errno($ch);
9666 - $last_curl_error = curl_error($ch);
9667 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
9668 - curl_close($ch);
9669 -
9670 - if (!$errno && $http_code === 200) {
9671 - break; // Happy path — WRITEFUNCTION already streamed everything.
9672 - }
9673 -
9674 - // plan-25b972 self-heal: a 400 rejecting our reasoning_effort VALUE
9675 - // (per-model support drift / stale catalog entry) is deterministic —
9676 - // strip the param and retry ONCE immediately, independent of the
9677 - // transient-retry setting. Checked BEFORE transient classification
9678 - // so the same body is never re-sent to a guaranteed 400.
9679 - if (!$reasoning_stripped
9680 - && !$this->streaming_headers_sent
9681 - && !$errno
9682 - && isset($request_body['reasoning_effort'])
9683 - && $this->mxchat_is_reasoning_effort_rejection($http_code, $captured_body_pre_stream)) {
9684 - $reasoning_stripped = true;
9685 - if (defined('WP_DEBUG') && WP_DEBUG) {
9686 - error_log(sprintf(
9687 - '[MxChat] openai_stream: model %s rejected reasoning_effort \'%s\' — retrying once without the param (plan-25b972).',
9688 - $selected_model, $request_body['reasoning_effort']
9689 - ));
9690 - }
9691 - unset($request_body['reasoning_effort']);
9692 - $body = json_encode($request_body);
9693 - if ($max_attempts <= $attempt + 1) {
9694 - $max_attempts = $attempt + 2; // grant the retry even when transient retry is off
9695 - }
9696 - $backoff_ms[$attempt + 1] = 0; // deterministic 400 — no backoff needed
9697 - continue;
9698 - }
9699 -
9700 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'openai', $errno);
9701 - $can_retry = !$this->streaming_headers_sent
9702 - && ($attempt + 1) < $max_attempts
9703 - && $is_transient;
9704 -
9705 - if (defined('WP_DEBUG') && WP_DEBUG) {
9706 - error_log(sprintf(
9707 - '[MxChat] openai_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
9708 - $attempt + 1, $max_attempts, $http_code, $errno,
9709 - $is_transient ? 'yes' : 'no',
9710 - $can_retry ? 'Retrying.' : 'Giving up.'
9711 - ));
9712 - }
9713 -
9714 - if (!$can_retry) {
9715 - break;
9716 - }
9717 - }
9718 -
9719 - // Post-loop branch.
9720 - if (!$errno && $http_code === 200) {
9721 - // Happy path — save the complete response to maintain chat persistence.
9722 - if (!empty($full_response) && !empty($session_id)) {
9723 - $rag_context_for_storage = null;
9724 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
9725 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
9726 -
9727 - if ($has_rag_data || $has_action_data) {
9728 - $rag_context_for_storage = [];
9729 -
9730 - if ($has_rag_data) {
9731 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
9732 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
9733 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
9734 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
9735 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
9736 - }
9737 -
9738 - if ($has_action_data) {
9739 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
9740 - }
9741 - }
9742 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $this->mxchat_fc_attach_tool_trace($rag_context_for_storage));
9743 - }
9744 -
9745 - return true;
9746 - }
9747 -
9748 - // Failure path — branch on whether SSE channel was opened.
9749 - return $this->mxchat_stream_emit_fallback(
9750 - 'openai',
9751 - $this->mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content, $session_id),
9752 - $session_id,
9753 - $testing_data
9754 - );
9755 -
9756 - } catch (Exception $e) {
9757 - return $this->mxchat_stream_emit_fallback(
9758 - 'openai',
9759 - $this->mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content, $session_id),
9760 - $session_id,
9761 - $testing_data
9762 - );
9763 - }
9764 -}
9765 -
9766 -/**
9767 - * Shared fallback emitter for streaming chat functions. Two outcomes:
9768 - * - streaming_headers_sent === true: SSE channel is open. Emit fallback content
9769 - * as `data: {...}\n\n` + `data: [DONE]\n\n` so the widget renders it as a
9770 - * normal bot bubble. Transcript row is persisted.
9771 - * - streaming_headers_sent === false: SSE channel never opened (retries
9772 - * exhausted on initial connect). Emit a clean JSON response — the path
9773 - * the widget would normally hit if streaming wasn't even attempted.
9774 - *
9775 - * Used by all six *_stream functions after their per-attempt retry loop.
9776 - */
9777 -private function mxchat_stream_emit_fallback($provider_hint, $regular_response, $session_id, $testing_data = null) {
9778 - $is_error_array = is_array($regular_response) && isset($regular_response['error']);
9779 -
9780 - if ($this->streaming_headers_sent) {
9781 - if ($is_error_array) {
9782 - echo "data: " . json_encode([
9783 - 'error' => true,
9784 - 'error_message' => $regular_response['error'],
9785 - 'error_code' => $regular_response['error_code'] ?? 'api_error',
9786 - 'text' => $regular_response['error'],
9787 - 'message' => $regular_response['error']
9788 - ]) . "\n\n";
9789 - echo "data: [DONE]\n\n";
9790 - flush();
9791 - return true;
9792 - }
9793 - $fallback_message = (string) $regular_response;
9794 - if (!empty($fallback_message) && !empty($session_id)) {
9795 - $this->mxchat_save_chat_message($session_id, 'bot', $fallback_message);
9796 - }
9797 - echo "data: " . json_encode(['content' => $fallback_message]) . "\n\n";
9798 - echo "data: [DONE]\n\n";
9799 - flush();
9800 - return true;
9801 - }
9802 -
9803 - // SSE channel never opened — clean JSON fallback.
9804 - if ($is_error_array) {
9805 - header('Content-Type: application/json');
9806 - echo json_encode(array(
9807 - 'error' => true,
9808 - 'error_message' => $regular_response['error'],
9809 - 'error_code' => $regular_response['error_code'] ?? 'api_error',
9810 - 'text' => $regular_response['error'],
9811 - 'message' => $regular_response['error'],
9812 - ));
9813 - return true;
9814 - }
9815 -
9816 - $fallback_message = (string) $regular_response;
9817 - if (!empty($fallback_message) && !empty($session_id)) {
9818 - $this->mxchat_save_chat_message($session_id, 'bot', $fallback_message);
9819 - }
9820 - $response_data = array(
9821 - 'text' => $fallback_message,
9822 - 'html' => '',
9823 - 'session_id' => $session_id,
9824 - );
9825 - if ($testing_data !== null) {
9826 - $response_data['testing_data'] = $testing_data;
9827 - }
9828 - header('Content-Type: application/json');
9829 - echo json_encode($response_data);
9830 - return true;
9831 -}
9832 -
9833 -/**
9834 - * Resolve custom (OpenAI-compatible) provider config from settings.
9835 - * Returns ['base_url','api_key','model','auth_scheme','api_version','chat_url','headers'].
9836 - */
9837 -private function mxchat_resolve_custom_provider() {
9838 - $base_url = isset($this->options['custom_provider_base_url']) ? rtrim(trim((string) $this->options['custom_provider_base_url']), '/') : '';
9839 - $api_key = isset($this->options['custom_provider_api_key']) ? trim((string) $this->options['custom_provider_api_key']) : '';
9840 - $model = isset($this->options['custom_provider_model']) ? trim((string) $this->options['custom_provider_model']) : '';
9841 - $auth_scheme = isset($this->options['custom_provider_auth_scheme']) ? $this->options['custom_provider_auth_scheme'] : 'bearer';
9842 - $api_version = isset($this->options['custom_provider_api_version']) ? trim((string) $this->options['custom_provider_api_version']) : '';
9843 -
9844 - $chat_url = $base_url . '/chat/completions';
9845 - if (!empty($api_version)) {
9846 - $chat_url .= (strpos($chat_url, '?') === false ? '?' : '&') . 'api-version=' . rawurlencode($api_version);
9847 - }
9848 -
9849 - $headers = array('Content-Type: application/json');
9850 - if (!empty($api_key)) {
9851 - if ($auth_scheme === 'api-key') {
9852 - $headers[] = 'api-key: ' . $api_key;
9853 - } else {
9854 - $headers[] = 'Authorization: Bearer ' . $api_key;
9855 - }
9856 - }
9857 -
9858 - return array(
9859 - 'base_url' => $base_url,
9860 - 'api_key' => $api_key,
9861 - 'model' => $model !== '' ? $model : 'default',
9862 - 'auth_scheme' => $auth_scheme,
9863 - 'api_version' => $api_version,
9864 - 'chat_url' => $chat_url,
9865 - 'headers' => $headers,
9866 - );
9867 -}
9868 -
9869 -/**
9870 - * Streaming chat completion against an OpenAI-compatible custom provider
9871 - * (Ollama, LM Studio, vLLM, llama.cpp, Azure OpenAI, etc.).
9872 - * Mirrors mxchat_generate_response_openai_stream but with parameterized URL/auth/model.
9873 - */
9874 -private function mxchat_generate_response_custom_stream($selected_model, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
9875 - try {
9876 - $cfg = $this->mxchat_resolve_custom_provider();
9877 - if (empty($cfg['base_url'])) {
9878 - return array('error' => esc_html__('Custom provider Base URL is not configured.', 'mxchat'), 'error_code' => 'missing_custom_provider_base_url');
9879 - }
9880 -
9881 - $bot_id = $this->get_current_bot_id($session_id);
9882 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
9883 - if (!is_array($conversation_history)) {
9884 - $conversation_history = array();
9885 - }
9886 -
9887 - $formatted_conversation = array();
9888 - $formatted_conversation[] = array(
9889 - 'role' => 'system',
9890 - 'content' => $system_prompt_instructions . ' ' . $relevant_content,
9891 - );
9892 - foreach ($conversation_history as $message) {
9893 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
9894 - $role = $message['role'];
9895 - if ($role === 'bot' || $role === 'agent') { $role = 'assistant'; }
9896 - if (!in_array($role, array('system', 'assistant', 'user', 'function', 'tool'))) { $role = 'user'; }
9897 - $formatted_conversation[] = array('role' => $role, 'content' => $message['content']);
9898 - }
9899 - }
9900 -
9901 - if (headers_sent() || !function_exists('curl_init')) {
9902 - // No streaming capability — fall through to non-stream wrapper
9903 - $regular = $this->mxchat_generate_response_custom($selected_model, $conversation_history, $relevant_content);
9904 - if (!empty($regular) && !empty($session_id) && is_string($regular)) {
9905 - $this->mxchat_save_chat_message($session_id, 'bot', $regular);
9906 - }
9907 - $response_data = array('text' => is_string($regular) ? $regular : '', 'html' => '', 'session_id' => $session_id);
9908 - if ($testing_data !== null) { $response_data['testing_data'] = $testing_data; }
9909 - header('Content-Type: application/json');
9910 - echo json_encode($response_data);
9911 - return true;
9912 - }
9913 -
9914 - $request_body = array(
9915 - 'model' => $cfg['model'],
9916 - 'messages' => $formatted_conversation,
9917 - 'stream' => true,
9918 - );
9919 - $body = json_encode($request_body);
9920 -
9921 - // V2 retry-on-initial-connect: setup_streaming_headers is lazy-fired in WRITEFUNCTION.
9922 -
9923 - $captured_status_code = 0;
9924 - $captured_body_pre_stream = '';
9925 - $full_response = '';
9926 - $stream_started = false;
9927 - $buffer = '';
9928 - $errno = 0;
9929 - $http_code = 0;
9930 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
9931 - $backoff_ms = array(0, 750, 2000);
9932 -
9933 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
9934 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
9935 - usleep($backoff_ms[$attempt] * 1000);
9936 - }
9937 -
9938 - $captured_status_code = 0;
9939 - $captured_body_pre_stream = '';
9940 - $full_response = '';
9941 - $stream_started = false;
9942 - $buffer = '';
9943 -
9944 - $ch = curl_init();
9945 - curl_setopt($ch, CURLOPT_URL, $cfg['chat_url']);
9946 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
9947 - curl_setopt($ch, CURLOPT_POST, true);
9948 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
9949 - curl_setopt($ch, CURLOPT_HTTPHEADER, $cfg['headers']);
9950 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
9951 - curl_setopt($ch, CURLOPT_TIMEOUT, 120);
9952 -
9953 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
9954 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
9955 - $captured_status_code = (int) $m[1];
9956 - }
9957 - return strlen($header);
9958 - });
9959 -
9960 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
9961 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
9962 - $captured_body_pre_stream .= $data;
9963 - return strlen($data);
9964 - }
9965 -
9966 - if (!$this->streaming_headers_sent) {
9967 - $this->setup_streaming_headers();
9968 - }
9969 -
9970 - if (!$stream_started && $testing_data !== null) {
9971 - echo "data: " . json_encode(array('testing_data' => $testing_data)) . "\n\n";
9972 - flush();
9973 - $stream_started = true;
9974 - }
9975 - $buffer .= $data;
9976 - $lines = explode("\n", $buffer);
9977 - $buffer = array_pop($lines);
9978 - foreach ($lines as $line) {
9979 - if (trim($line) === '') { continue; }
9980 - if (strpos($line, 'data: ') !== 0) { continue; }
9981 - $json_str = substr($line, 6);
9982 - if (trim($json_str) === '[DONE]') {
9983 - echo "data: [DONE]\n\n";
9984 - flush();
9985 - continue;
9986 - }
9987 - $json = json_decode(trim($json_str), true);
9988 - if ($json && isset($json['choices'][0]['delta']['content'])) {
9989 - $content = $json['choices'][0]['delta']['content'];
9990 - $full_response .= $content;
9991 - echo "data: " . json_encode(array('content' => $content)) . "\n\n";
9992 - flush();
9993 - }
9994 - }
9995 - return strlen($data);
9996 - });
9997 -
9998 - $response = curl_exec($ch);
9999 - $errno = curl_errno($ch);
10000 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
10001 - curl_close($ch);
10002 -
10003 - if (!$errno && $http_code === 200) {
10004 - break;
10005 - }
10006 -
10007 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'openai', $errno);
10008 - $can_retry = !$this->streaming_headers_sent
10009 - && ($attempt + 1) < $max_attempts
10010 - && $is_transient;
10011 -
10012 - if (defined('WP_DEBUG') && WP_DEBUG) {
10013 - error_log(sprintf(
10014 - '[MxChat] custom_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
10015 - $attempt + 1, $max_attempts, $http_code, $errno,
10016 - $is_transient ? 'yes' : 'no',
10017 - $can_retry ? 'Retrying.' : 'Giving up.'
10018 - ));
10019 - }
10020 -
10021 - if (!$can_retry) {
10022 - break;
10023 - }
10024 - }
10025 -
10026 - if (!$errno && $http_code === 200) {
10027 - if (!empty($full_response) && !empty($session_id)) {
10028 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response);
10029 - }
10030 - return true;
10031 - }
10032 -
10033 - return $this->mxchat_stream_emit_fallback(
10034 - 'openai',
10035 - $this->mxchat_generate_response_custom($selected_model, $conversation_history, $relevant_content),
10036 - $session_id,
10037 - $testing_data
10038 - );
10039 -
10040 - } catch (Exception $e) {
10041 - return array('error' => sprintf(esc_html__('Custom provider error: %s', 'mxchat'), $e->getMessage()), 'error_code' => 'custom_provider_exception');
10042 - }
10043 -}
10044 -
10045 -/**
10046 - * Non-streaming chat completion against a custom OpenAI-compatible provider.
10047 - * Returns string content on success, array['error'=>...] on failure.
10048 - */
10049 -private function mxchat_generate_response_custom($selected_model, $conversation_history, $relevant_content) {
10050 - $cfg = $this->mxchat_resolve_custom_provider();
10051 - if (empty($cfg['base_url'])) {
10052 - return array('error' => esc_html__('Custom provider Base URL is not configured.', 'mxchat'), 'error_code' => 'missing_custom_provider_base_url');
10053 - }
10054 -
10055 - $bot_id = $this->get_current_bot_id(null);
10056 - $system_prompt_instructions = $this->get_system_instructions($bot_id, null);
10057 - if (!is_array($conversation_history)) {
10058 - $conversation_history = array();
10059 - }
10060 -
10061 - $messages = array(array(
10062 - 'role' => 'system',
10063 - 'content' => $system_prompt_instructions . ' ' . $relevant_content,
10064 - ));
10065 - foreach ($conversation_history as $message) {
10066 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
10067 - $role = $message['role'];
10068 - if ($role === 'bot' || $role === 'agent') { $role = 'assistant'; }
10069 - if (!in_array($role, array('system', 'assistant', 'user', 'function', 'tool'))) { $role = 'user'; }
10070 - $messages[] = array('role' => $role, 'content' => $message['content']);
10071 - }
10072 - }
10073 -
10074 - $headers_assoc = array('Content-Type' => 'application/json');
10075 - if (!empty($cfg['api_key'])) {
10076 - if ($cfg['auth_scheme'] === 'api-key') {
10077 - $headers_assoc['api-key'] = $cfg['api_key'];
10078 - } else {
10079 - $headers_assoc['Authorization'] = 'Bearer ' . $cfg['api_key'];
10080 - }
10081 - }
10082 -
10083 - $response = $this->mxchat_provider_call_with_retry($cfg['chat_url'], array(
10084 - 'headers' => $headers_assoc,
10085 - 'body' => wp_json_encode(array(
10086 - 'model' => $cfg['model'],
10087 - 'messages' => $messages,
10088 - )),
10089 - 'timeout' => 120,
10090 - ), 'openai');
10091 -
10092 - if (is_wp_error($response)) {
10093 - return array('error' => sprintf(esc_html__('Custom provider request failed: %s', 'mxchat'), $response->get_error_message()), 'error_code' => 'custom_provider_network_error');
10094 - }
10095 - $code = (int) wp_remote_retrieve_response_code($response);
10096 - if ($code < 200 || $code >= 300) {
10097 - return array('error' => sprintf(esc_html__('Custom provider returned HTTP %d.', 'mxchat'), $code), 'error_code' => 'custom_provider_http_error');
10098 - }
10099 - $body = json_decode(wp_remote_retrieve_body($response), true);
10100 - if (isset($body['choices'][0]['message']['content'])) {
10101 - return (string) $body['choices'][0]['message']['content'];
10102 - }
10103 - return array('error' => esc_html__('Custom provider returned an unexpected response shape.', 'mxchat'), 'error_code' => 'custom_provider_response_shape');
10104 -}
10105 -
10106 -/**
10107 - * Generate response using OpenAI Responses API with web search tool
10108 - * This uses the newer Responses API which supports web search functionality
10109 - */
10110 -private function mxchat_generate_response_openai_web_search($selected_model, $api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null, $streaming = false) {
10111 - // OpenAI retires gpt-5.1-chat-latest / gpt-5.3-chat-latest on 2026-08-10
10112 - // (replacement gpt-5.6-sol). Read-time rescue mirrors the chat paths
10113 - // (plan e46b8f).
10114 - if ($selected_model === 'gpt-5.1-chat-latest' || $selected_model === 'gpt-5.3-chat-latest') { $selected_model = 'gpt-5.6-sol'; }
10115 - try {
10116 - $bot_id = $this->get_current_bot_id($session_id);
10117 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
10118 -
10119 - if (!is_array($conversation_history)) {
10120 - $conversation_history = array();
10121 - }
10122 -
10123 - // Build the input for Responses API
10124 - // The Responses API uses a different format - we need to construct the input properly
10125 - $input_parts = [];
10126 -
10127 - // Add system instructions as context
10128 - $system_context = $system_prompt_instructions . "\n\n" . $relevant_content;
10129 -
10130 - // Build conversation as input items for Responses API
10131 - foreach ($conversation_history as $message) {
10132 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
10133 - $role = $message['role'];
10134 - if ($role === 'bot' || $role === 'agent') {
10135 - $role = 'assistant';
10136 - }
10137 - if (!in_array($role, ['assistant', 'user'])) {
10138 - $role = 'user';
10139 - }
10140 - $input_parts[] = [
10141 - 'type' => 'message',
10142 - 'role' => $role,
10143 - 'content' => $message['content']
10144 - ];
10145 - }
10146 - }
10147 -
10148 - // Build request body for Responses API
10149 - $request_body = [
10150 - 'model' => $selected_model,
10151 - 'input' => $input_parts,
10152 - 'instructions' => $system_context,
10153 - 'stream' => $streaming
10154 - ];
10155 -
10156 - // Only add web search tool if web search is enabled in settings
10157 - $web_search_enabled = isset($this->options['enable_web_search']) && $this->options['enable_web_search'] === 'on';
10158 - if ($web_search_enabled) {
10159 - $request_body['tools'] = [
10160 - ['type' => 'web_search']
10161 - ];
10162 - }
10163 -
10164 - // reasoning.effort — sourced from the core model catalog (plan-dcb71c),
10165 - // 'websearch' surface; frozen inline ladder in mxchat_reasoning_effort_fallback().
10166 - $effort = $this->mxchat_reasoning_effort_for($selected_model, 'websearch');
10167 - if ($effort !== null) {
10168 - $request_body['reasoning'] = ['effort' => $effort];
10169 - }
10170 -
10171 - //error_log("MXCHAT WEB SEARCH: Request body: " . json_encode($request_body));
10172 -
10173 - if ($streaming) {
10174 - return $this->mxchat_web_search_streaming_response($request_body, $api_key, $session_id, $testing_data);
10175 - } else {
10176 - return $this->mxchat_web_search_non_streaming_response($request_body, $api_key, $session_id, $testing_data);
10177 - }
10178 -
10179 - } catch (Exception $e) {
10180 - //error_log("MXCHAT WEB SEARCH ERROR: " . $e->getMessage());
10181 - return [
10182 - 'error' => sprintf(esc_html__('Web search error: %s', 'mxchat'), esc_html($e->getMessage())),
10183 - 'error_code' => 'web_search_exception'
10184 - ];
10185 - }
10186 -}
10187 -
10188 -/**
10189 - * Handle non-streaming web search response
10190 - */
10191 -private function mxchat_web_search_non_streaming_response($request_body, $api_key, $session_id, $testing_data) {
10192 - $request_body['stream'] = false;
10193 -
10194 - $response = $this->mxchat_provider_call_with_retry('https://api.openai.com/v1/responses', array(
10195 - 'headers' => array(
10196 - 'Authorization' => 'Bearer ' . $api_key,
10197 - 'Content-Type' => 'application/json'
10198 - ),
10199 - 'body' => json_encode($request_body),
10200 - 'timeout' => 90
10201 - ), 'openai');
10202 -
10203 - if (is_wp_error($response)) {
10204 - //error_log("MXCHAT WEB SEARCH ERROR: WP Error: " . $response->get_error_message());
10205 - return [
10206 - 'error' => esc_html__('Failed to connect to OpenAI web search API', 'mxchat'),
10207 - 'error_code' => 'web_search_connection_error'
10208 - ];
10209 - }
10210 -
10211 - $response_code = wp_remote_retrieve_response_code($response);
10212 - $response_body = wp_remote_retrieve_body($response);
10213 -
10214 - //error_log("MXCHAT WEB SEARCH: Response code: " . $response_code);
10215 - //error_log("MXCHAT WEB SEARCH: Response body (first 2000): " . substr($response_body, 0, 2000));
10216 -
10217 - if ($response_code !== 200) {
10218 - $error_data = json_decode($response_body, true);
10219 - $error_message = $this->extract_provider_error($error_data, 'Unknown API error');
10220 - return [
10221 - 'error' => sprintf(esc_html__('OpenAI API error: %s', 'mxchat'), esc_html($error_message)),
10222 - 'error_code' => 'web_search_api_error'
10223 - ];
10224 - }
10225 -
10226 - $result = json_decode($response_body, true);
10227 -
10228 - if (json_last_error() !== JSON_ERROR_NONE) {
10229 - return [
10230 - 'error' => esc_html__('Invalid response from OpenAI', 'mxchat'),
10231 - 'error_code' => 'web_search_json_error'
10232 - ];
10233 - }
10234 -
10235 - // Extract the response text and citations from Responses API format
10236 - $output_text = '';
10237 - $citations = [];
10238 -
10239 - if (isset($result['output'])) {
10240 - foreach ($result['output'] as $output_item) {
10241 - if ($output_item['type'] === 'message' && isset($output_item['content'])) {
10242 - foreach ($output_item['content'] as $content_item) {
10243 - if ($content_item['type'] === 'output_text') {
10244 - $output_text .= $content_item['text'];
10245 -
10246 - // Extract citations/annotations
10247 - if (isset($content_item['annotations'])) {
10248 - foreach ($content_item['annotations'] as $annotation) {
10249 - if ($annotation['type'] === 'url_citation') {
10250 - $citations[] = [
10251 - 'url' => $annotation['url'],
10252 - 'title' => $annotation['title'] ?? ''
10253 - ];
10254 - }
10255 - }
10256 - }
10257 - }
10258 - }
10259 - }
10260 - }
10261 - }
10262 -
10263 - // If we have citations, append them to the response
10264 - if (!empty($citations)) {
10265 - $output_text .= "\n\n**Sources:**\n";
10266 - $seen_urls = [];
10267 - foreach ($citations as $citation) {
10268 - if (!in_array($citation['url'], $seen_urls)) {
10269 - $seen_urls[] = $citation['url'];
10270 - $title = !empty($citation['title']) ? $citation['title'] : $citation['url'];
10271 - $output_text .= "- [" . $title . "](" . $citation['url'] . ")\n";
10272 - }
10273 - }
10274 - }
10275 -
10276 - // Transcript save is handled by the main handler (mxchat_handle_chat_request)
10277 - // which includes rag_context for the "sources" link in transcripts.
10278 -
10279 - // plan-4aa8e5: a 200 whose output carries no output_text (status
10280 - // "incomplete" with max_output_tokens exhausted, content-filter-emptied
10281 - // output, shape drift) previously fell through and returned '' — a
10282 - // silent empty bot bubble. This is the DEFAULT model path
10283 - // (the default OpenAI chat model routes through /v1/responses).
10284 - if (trim($output_text) === '') {
10285 - return $this->mxchat_empty_completion_error($result, 'OpenAI');
10286 - }
10287 -
10288 - return $output_text;
10289 -}
10290 -
10291 -/**
10292 - * Handle streaming web search response using Responses API
10293 - */
10294 -private function mxchat_web_search_streaming_response($request_body, $api_key, $session_id, $testing_data) {
10295 - $request_body['stream'] = true;
10296 -
10297 - // Check if we can stream
10298 - if (headers_sent() || !function_exists('curl_init')) {
10299 - // Fallback to non-streaming
10300 - return $this->mxchat_web_search_non_streaming_response($request_body, $api_key, $session_id, $testing_data);
10301 - }
10302 -
10303 - // Setup streaming headers
10304 - $this->setup_streaming_headers();
10305 -
10306 - $ch = curl_init();
10307 - curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/responses');
10308 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
10309 - curl_setopt($ch, CURLOPT_POST, true);
10310 - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request_body));
10311 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
10312 - 'Content-Type: application/json',
10313 - 'Authorization: Bearer ' . $api_key
10314 - ));
10315 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
10316 - curl_setopt($ch, CURLOPT_TIMEOUT, 120);
10317 -
10318 - $full_response = '';
10319 - $stream_started = false;
10320 - $buffer = '';
10321 - $citations = [];
10322 - $empty_error_emitted = false;
10323 -
10324 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$citations, &$empty_error_emitted, $testing_data) {
10325 - // Send testing data as first event if available
10326 - if (!$stream_started && $testing_data !== null) {
10327 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
10328 - flush();
10329 - $stream_started = true;
10330 - }
10331 -
10332 - $buffer .= $data;
10333 - $lines = explode("\n", $buffer);
10334 - $buffer = array_pop($lines);
10335 -
10336 - foreach ($lines as $line) {
10337 - if (trim($line) === '') continue;
10338 - if (strpos($line, 'data: ') !== 0) continue;
10339 -
10340 - $json_str = substr($line, 6);
10341 -
10342 - if (trim($json_str) === '[DONE]') {
10343 - // Append citations if we have any
10344 - if (!empty($citations)) {
10345 - $citation_text = "\n\n**Sources:**\n";
10346 - $seen_urls = [];
10347 - foreach ($citations as $citation) {
10348 - if (!in_array($citation['url'], $seen_urls)) {
10349 - $seen_urls[] = $citation['url'];
10350 - $title = !empty($citation['title']) ? $citation['title'] : $citation['url'];
10351 - $citation_text .= "- [" . $title . "](" . $citation['url'] . ")\n";
10352 - }
10353 - }
10354 - echo "data: " . json_encode(['content' => $citation_text]) . "\n\n";
10355 - $full_response .= $citation_text;
10356 - flush();
10357 - }
10358 - // plan-4aa8e5: zero deltas streamed → say so instead of
10359 - // closing a silent empty bubble (client renders text events).
10360 - if (trim($full_response) === '' && !$empty_error_emitted) {
10361 - $empty_error_emitted = true;
10362 - echo "data: " . json_encode(['content' => esc_html__('The AI provider returned an empty response. Please try again.', 'mxchat')]) . "\n\n";
10363 - }
10364 - echo "data: [DONE]\n\n";
10365 - flush();
10366 - continue;
10367 - }
10368 -
10369 - $json = json_decode(trim($json_str), true);
10370 - if (!$json) continue;
10371 -
10372 - // Handle Responses API streaming events
10373 - // The format is different from Chat Completions
10374 - if (isset($json['type'])) {
10375 - switch ($json['type']) {
10376 - case 'response.output_text.delta':
10377 - // Text content delta
10378 - if (isset($json['delta'])) {
10379 - $content = $json['delta'];
10380 - $full_response .= $content;
10381 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
10382 - flush();
10383 - }
10384 - break;
10385 -
10386 - case 'response.output_item.done':
10387 - // Check for citations in completed items
10388 - if (isset($json['item']['content'])) {
10389 - foreach ($json['item']['content'] as $content_item) {
10390 - if (isset($content_item['annotations'])) {
10391 - foreach ($content_item['annotations'] as $annotation) {
10392 - if ($annotation['type'] === 'url_citation') {
10393 - $citations[] = [
10394 - 'url' => $annotation['url'],
10395 - 'title' => $annotation['title'] ?? ''
10396 - ];
10397 - }
10398 - }
10399 - }
10400 - }
10401 - }
10402 - break;
10403 - }
10404 - }
10405 - }
10406 -
10407 - return strlen($data);
10408 - });
10409 -
10410 - $response = curl_exec($ch);
10411 - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
10412 -
10413 - if (curl_errno($ch) || $http_code !== 200) {
10414 - $curl_error = curl_error($ch);
10415 - curl_close($ch);
10416 -
10417 - //error_log("MXCHAT WEB SEARCH STREAM ERROR: HTTP $http_code, cURL error: $curl_error");
10418 -
10419 - return $this->mxchat_stream_emit_fallback(
10420 - 'web_search',
10421 - $this->mxchat_web_search_non_streaming_response($request_body, $api_key, $session_id, $testing_data),
10422 - $session_id,
10423 - $testing_data
10424 - );
10425 - }
10426 -
10427 - curl_close($ch);
10428 -
10429 - // plan-4aa8e5: the Responses API can end its stream via typed events
10430 - // without a [DONE] line — if nothing was streamed at all, close out with
10431 - // the empty-completion message instead of leaving a silent bubble.
10432 - if (trim($full_response) === '' && !$empty_error_emitted) {
10433 - echo "data: " . json_encode(['content' => esc_html__('The AI provider returned an empty response. Please try again.', 'mxchat')]) . "\n\n";
10434 - echo "data: [DONE]\n\n";
10435 - flush();
10436 - }
10437 -
10438 - // Save the complete response with RAG context so the "sources" link
10439 - // appears in transcripts — mirrors the pattern used by Claude/OpenAI streaming.
10440 - if (!empty($full_response) && !empty($session_id)) {
10441 - $rag_context_for_storage = null;
10442 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
10443 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
10444 -
10445 - if ($has_rag_data || $has_action_data) {
10446 - $rag_context_for_storage = [];
10447 -
10448 - if ($has_rag_data) {
10449 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
10450 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
10451 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
10452 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
10453 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
10454 - }
10455 -
10456 - if ($has_action_data) {
10457 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
10458 - }
10459 - }
10460 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $this->mxchat_fc_attach_tool_trace($rag_context_for_storage));
10461 - }
10462 -
10463 - return true;
10464 -}
10465 -
10466 -private function mxchat_generate_response_claude_stream($selected_model, $claude_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
10467 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
10468 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
10469 - if ($selected_model === 'claude-opus-4-20250514') { $selected_model = 'claude-opus-4-8'; }
10470 - elseif ($selected_model === 'claude-sonnet-4-20250514') { $selected_model = 'claude-sonnet-4-6'; }
10471 - try {
10472 - // Get bot ID from session or request
10473 - $bot_id = $this->get_current_bot_id($session_id);
10474 -
10475 - // Get system prompt instructions using centralized function
10476 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
10477 - // Ensure conversation_history is an array
10478 - if (!is_array($conversation_history)) {
10479 - $conversation_history = array();
10480 - }
10481 -
10482 - // Clean and validate conversation history
10483 - foreach ($conversation_history as &$message) {
10484 - // Convert bot and agent roles to assistant
10485 - if ($message['role'] === 'bot' || $message['role'] === 'agent') {
10486 - $message['role'] = 'assistant';
10487 - }
10488 -
10489 - // Remove unsupported roles - Claude only supports 'assistant' and 'user'
10490 - if (!in_array($message['role'], ['assistant', 'user'])) {
10491 - $message['role'] = 'user';
10492 - }
10493 -
10494 - // Ensure content field exists
10495 - if (!isset($message['content']) || empty($message['content'])) {
10496 - $message['content'] = '';
10497 - }
10498 -
10499 - // Remove any unsupported fields
10500 - $message = array_intersect_key($message, array_flip(['role', 'content']));
10501 - }
10502 -
10503 - // Add relevant content as the latest user message
10504 - $conversation_history[] = [
10505 - 'role' => 'user',
10506 - 'content' => $relevant_content
10507 - ];
10508 -
10509 - // Prepare the request body with stream: true
10510 - $payload = [
10511 - 'model' => $selected_model,
10512 - 'messages' => $conversation_history,
10513 - 'max_tokens' => 1000,
10514 - 'temperature' => 0.8,
10515 - 'system' => $this->mxchat_anthropic_system_blocks($system_prompt_instructions),
10516 - 'stream' => true
10517 - ];
10518 - if ($this->mxchat_claude_omits_temperature($selected_model)) { unset($payload['temperature']); }
10519 - $body = json_encode($payload);
10520 -
10521 - // Check if we can actually stream (headers not sent, etc.)
10522 - if (headers_sent() || !function_exists('curl_init')) {
10523 - // Fallback to regular response with testing data
10524 - //error_log("MxChat: Streaming not possible, falling back to regular response");
10525 - $regular_response = $this->mxchat_generate_response_claude(
10526 - $selected_model,
10527 - $claude_api_key,
10528 - array_slice($conversation_history, 0, -1), // Remove the added content
10529 - $relevant_content,
10530 - $session_id
10531 - );
10532 -
10533 - // Save bot response to transcript
10534 - if (!empty($regular_response) && !empty($session_id)) {
10535 - $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
10536 - }
10537 -
10538 - // Return as JSON with testing data
10539 - $response_data = [
10540 - 'text' => $regular_response,
10541 - 'html' => '',
10542 - 'session_id' => $session_id
10543 - ];
10544 -
10545 - if ($testing_data !== null) {
10546 - $response_data['testing_data'] = $testing_data;
10547 - //error_log("MxChat Testing: Added testing data to Claude fallback response");
10548 - }
10549 -
10550 - // Clear any streaming headers and send JSON
10551 - if (headers_sent() === false) {
10552 - header('Content-Type: application/json');
10553 - }
10554 - echo json_encode($response_data);
10555 - return true; // Indicate we handled the response
10556 - }
10557 -
10558 - // V2 retry-on-initial-connect: setup_streaming_headers is lazy-fired in WRITEFUNCTION.
10559 -
10560 - $captured_status_code = 0;
10561 - $captured_body_pre_stream = '';
10562 - $full_response = '';
10563 - $stream_started = false;
10564 - $buffer = '';
10565 - $errno = 0;
10566 - $http_code = 0;
10567 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
10568 - $backoff_ms = array(0, 750, 2000);
10569 -
10570 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
10571 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
10572 - usleep($backoff_ms[$attempt] * 1000);
10573 - }
10574 -
10575 - $captured_status_code = 0;
10576 - $captured_body_pre_stream = '';
10577 - $full_response = '';
10578 - $stream_started = false;
10579 - $buffer = '';
10580 -
10581 - $ch = curl_init();
10582 - curl_setopt($ch, CURLOPT_URL, 'https://api.anthropic.com/v1/messages');
10583 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
10584 - curl_setopt($ch, CURLOPT_POST, true);
10585 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
10586 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
10587 - 'Content-Type: application/json',
10588 - 'x-api-key: ' . $claude_api_key,
10589 - 'anthropic-version: 2023-06-01'
10590 - ));
10591 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
10592 - curl_setopt($ch, CURLOPT_TIMEOUT, 60);
10593 -
10594 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
10595 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
10596 - $captured_status_code = (int) $m[1];
10597 - }
10598 - return strlen($header);
10599 - });
10600 -
10601 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
10602 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
10603 - $captured_body_pre_stream .= $data;
10604 - return strlen($data);
10605 - }
10606 -
10607 - if (!$this->streaming_headers_sent) {
10608 - $this->setup_streaming_headers();
10609 - }
10610 -
10611 - if (!$stream_started && $testing_data !== null) {
10612 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
10613 - flush();
10614 - $stream_started = true;
10615 - }
10616 -
10617 - $buffer .= $data;
10618 - $lines = explode("\n", $buffer);
10619 - $buffer = array_pop($lines);
10620 -
10621 - foreach ($lines as $line) {
10622 - if (trim($line) === '') {
10623 - continue;
10624 - }
10625 -
10626 - if (strpos($line, 'event: ') === 0) {
10627 - continue;
10628 - }
10629 -
10630 - if (strpos($line, 'data: ') === 0) {
10631 - $json_str = substr($line, 6);
10632 -
10633 - $json = json_decode(trim($json_str), true);
10634 - if (json_last_error() !== JSON_ERROR_NONE) {
10635 - continue;
10636 - }
10637 -
10638 - if (isset($json['type'])) {
10639 - switch ($json['type']) {
10640 - case 'content_block_delta':
10641 - if (isset($json['delta']['text'])) {
10642 - $content = $json['delta']['text'];
10643 - $full_response .= $content;
10644 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
10645 - flush();
10646 - }
10647 - break;
10648 -
10649 - case 'message_stop':
10650 - echo "data: [DONE]\n\n";
10651 - flush();
10652 - break;
10653 -
10654 - case 'error':
10655 - echo "data: " . json_encode(['error' => $this->extract_provider_error($json, 'Unknown error')]) . "\n\n";
10656 - flush();
10657 - break;
10658 - }
10659 - }
10660 - }
10661 - }
10662 -
10663 - return strlen($data);
10664 - });
10665 -
10666 - $response = curl_exec($ch);
10667 - $errno = curl_errno($ch);
10668 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
10669 - curl_close($ch);
10670 -
10671 - if (!$errno && $http_code === 200) {
10672 - break;
10673 - }
10674 -
10675 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'anthropic', $errno);
10676 - $can_retry = !$this->streaming_headers_sent
10677 - && ($attempt + 1) < $max_attempts
10678 - && $is_transient;
10679 -
10680 - if (defined('WP_DEBUG') && WP_DEBUG) {
10681 - error_log(sprintf(
10682 - '[MxChat] claude_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
10683 - $attempt + 1, $max_attempts, $http_code, $errno,
10684 - $is_transient ? 'yes' : 'no',
10685 - $can_retry ? 'Retrying.' : 'Giving up.'
10686 - ));
10687 - }
10688 -
10689 - if (!$can_retry) {
10690 - break;
10691 - }
10692 - }
10693 -
10694 - if ($errno || $http_code !== 200) {
10695 - return $this->mxchat_stream_emit_fallback(
10696 - 'anthropic',
10697 - $this->mxchat_generate_response_claude($selected_model, $claude_api_key, array_slice($conversation_history, 0, -1), $relevant_content, $session_id),
10698 - $session_id,
10699 - $testing_data
10700 - );
10701 - }
10702 -
10703 - // Save the complete response to maintain chat persistence
10704 - if (!empty($full_response) && !empty($session_id)) {
10705 - // Prepare RAG context for streaming response
10706 - $rag_context_for_storage = null;
10707 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
10708 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
10709 -
10710 - if ($has_rag_data || $has_action_data) {
10711 - $rag_context_for_storage = [];
10712 -
10713 - if ($has_rag_data) {
10714 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
10715 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
10716 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
10717 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
10718 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
10719 - }
10720 -
10721 - if ($has_action_data) {
10722 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
10723 - }
10724 - }
10725 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $this->mxchat_fc_attach_tool_trace($rag_context_for_storage));
10726 - }
10727 -
10728 - return true; // Indicate streaming completed successfully
10729 -
10730 - } catch (Exception $e) {
10731 - return $this->mxchat_stream_emit_fallback(
10732 - 'anthropic',
10733 - $this->mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content, $session_id),
10734 - $session_id,
10735 - $testing_data
10736 - );
10737 - }
10738 -}
10739 -private function mxchat_generate_response_xai_stream($selected_model, $xai_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
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 - // Ensure conversation_history is an array
10748 - if (!is_array($conversation_history)) {
10749 - $conversation_history = array();
10750 - }
10751 -
10752 - // Format conversation history for X.AI (same as OpenAI format)
10753 - $formatted_conversation = array();
10754 -
10755 - $formatted_conversation[] = array(
10756 - 'role' => 'system',
10757 - 'content' => $system_prompt_instructions . " " . $relevant_content
10758 - );
10759 -
10760 - foreach ($conversation_history as $message) {
10761 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
10762 - $role = $message['role'];
10763 - if ($role === 'bot' || $role === 'agent') {
10764 - $role = 'assistant';
10765 - }
10766 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
10767 - $role = 'user';
10768 - }
10769 - $formatted_conversation[] = array(
10770 - 'role' => $role,
10771 - 'content' => $message['content']
10772 - );
10773 - }
10774 - }
10775 -
10776 - // Check if we can actually stream
10777 - if (headers_sent() || !function_exists('curl_init')) {
10778 - // Fallback to regular response with testing data
10779 - //error_log("MxChat: X.AI streaming not possible, falling back to regular response");
10780 - $regular_response = $this->mxchat_generate_response_xai(
10781 - $selected_model,
10782 - $xai_api_key,
10783 - $conversation_history,
10784 - $relevant_content,
10785 - $session_id
10786 - );
10787 -
10788 - // Save bot response to transcript
10789 - if (!empty($regular_response) && !empty($session_id)) {
10790 - $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
10791 - }
10792 -
10793 - $response_data = [
10794 - 'text' => $regular_response,
10795 - 'html' => '',
10796 - 'session_id' => $session_id
10797 - ];
10798 -
10799 - if ($testing_data !== null) {
10800 - $response_data['testing_data'] = $testing_data;
10801 - //error_log("MxChat Testing: Added testing data to X.AI fallback response");
10802 - }
10803 -
10804 - header('Content-Type: application/json');
10805 - echo json_encode($response_data);
10806 - return true;
10807 - }
10808 -
10809 - // Prepare the request body with stream: true
10810 - $body = json_encode([
10811 - 'model' => $selected_model,
10812 - 'messages' => $formatted_conversation,
10813 - 'temperature' => 0.8,
10814 - 'stream' => true
10815 - ]);
10816 -
10817 - // V2 retry-on-initial-connect: setup_streaming_headers is lazy-fired in WRITEFUNCTION.
10818 -
10819 - $captured_status_code = 0;
10820 - $captured_body_pre_stream = '';
10821 - $full_response = '';
10822 - $stream_started = false;
10823 - $buffer = '';
10824 - $errno = 0;
10825 - $http_code = 0;
10826 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
10827 - $backoff_ms = array(0, 750, 2000);
10828 -
10829 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
10830 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
10831 - usleep($backoff_ms[$attempt] * 1000);
10832 - }
10833 -
10834 - $captured_status_code = 0;
10835 - $captured_body_pre_stream = '';
10836 - $full_response = '';
10837 - $stream_started = false;
10838 - $buffer = '';
10839 -
10840 - $ch = curl_init();
10841 - curl_setopt($ch, CURLOPT_URL, 'https://api.x.ai/v1/chat/completions');
10842 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
10843 - curl_setopt($ch, CURLOPT_POST, true);
10844 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
10845 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
10846 - 'Content-Type: application/json',
10847 - 'Authorization: Bearer ' . $xai_api_key
10848 - ));
10849 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
10850 - curl_setopt($ch, CURLOPT_TIMEOUT, 60);
10851 -
10852 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
10853 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
10854 - $captured_status_code = (int) $m[1];
10855 - }
10856 - return strlen($header);
10857 - });
10858 -
10859 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
10860 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
10861 - $captured_body_pre_stream .= $data;
10862 - return strlen($data);
10863 - }
10864 -
10865 - if (!$this->streaming_headers_sent) {
10866 - $this->setup_streaming_headers();
10867 - }
10868 -
10869 - if (!$stream_started && $testing_data !== null) {
10870 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
10871 - flush();
10872 - $stream_started = true;
10873 - }
10874 -
10875 - $buffer .= $data;
10876 - $lines = explode("\n", $buffer);
10877 - $buffer = array_pop($lines);
10878 -
10879 - foreach ($lines as $line) {
10880 - if (trim($line) === '') {
10881 - continue;
10882 - }
10883 - if (strpos($line, 'data: ') !== 0) {
10884 - continue;
10885 - }
10886 -
10887 - $json_str = substr($line, 6);
10888 -
10889 - if (trim($json_str) === '[DONE]') {
10890 - echo "data: [DONE]\n\n";
10891 - flush();
10892 - continue;
10893 - }
10894 -
10895 - $json = json_decode(trim($json_str), true);
10896 - if ($json && isset($json['choices'][0]['delta']['content'])) {
10897 - $content = $json['choices'][0]['delta']['content'];
10898 - $full_response .= $content;
10899 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
10900 - flush();
10901 - }
10902 - }
10903 -
10904 - return strlen($data);
10905 - });
10906 -
10907 - $response = curl_exec($ch);
10908 - $errno = curl_errno($ch);
10909 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
10910 - curl_close($ch);
10911 -
10912 - if (!$errno && $http_code === 200) {
10913 - break;
10914 - }
10915 -
10916 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'xai', $errno);
10917 - $can_retry = !$this->streaming_headers_sent
10918 - && ($attempt + 1) < $max_attempts
10919 - && $is_transient;
10920 -
10921 - if (defined('WP_DEBUG') && WP_DEBUG) {
10922 - error_log(sprintf(
10923 - '[MxChat] xai_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
10924 - $attempt + 1, $max_attempts, $http_code, $errno,
10925 - $is_transient ? 'yes' : 'no',
10926 - $can_retry ? 'Retrying.' : 'Giving up.'
10927 - ));
10928 - }
10929 -
10930 - if (!$can_retry) {
10931 - break;
10932 - }
10933 - }
10934 -
10935 - if ($errno || $http_code !== 200) {
10936 - return $this->mxchat_stream_emit_fallback(
10937 - 'xai',
10938 - $this->mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content, $session_id),
10939 - $session_id,
10940 - $testing_data
10941 - );
10942 - }
10943 -
10944 - // Save the complete response to maintain chat persistence
10945 - if (!empty($full_response) && !empty($session_id)) {
10946 - // Prepare RAG context for streaming response
10947 - $rag_context_for_storage = null;
10948 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
10949 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
10950 -
10951 - if ($has_rag_data || $has_action_data) {
10952 - $rag_context_for_storage = [];
10953 -
10954 - if ($has_rag_data) {
10955 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
10956 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
10957 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
10958 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
10959 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
10960 - }
10961 -
10962 - if ($has_action_data) {
10963 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
10964 - }
10965 - }
10966 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $this->mxchat_fc_attach_tool_trace($rag_context_for_storage));
10967 - }
10968 -
10969 - return true; // Indicate streaming completed successfully
10970 -
10971 - } catch (Exception $e) {
10972 - return $this->mxchat_stream_emit_fallback(
10973 - 'xai',
10974 - $this->mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content),
10975 - $session_id,
10976 - $testing_data
10977 - );
10978 - }
10979 -}
10980 -private function mxchat_generate_response_deepseek_stream($selected_model, $deepseek_api_key, $conversation_history, $relevant_content, $session_id, $testing_data = null) {
10981 - try {
10982 - // Get bot ID from session or request
10983 - $bot_id = $this->get_current_bot_id($session_id);
10984 -
10985 - // Get system prompt instructions using centralized function
10986 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
10987 -
10988 - // Ensure conversation_history is an array
10989 - if (!is_array($conversation_history)) {
10990 - $conversation_history = array();
10991 - }
10992 -
10993 - // Format conversation history for DeepSeek
10994 - $formatted_conversation = array();
10995 -
10996 - $formatted_conversation[] = array(
10997 - 'role' => 'system',
10998 - 'content' => $system_prompt_instructions . " " . $relevant_content
10999 - );
11000 -
11001 - foreach ($conversation_history as $message) {
11002 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
11003 - $role = $message['role'];
11004 - if ($role === 'bot' || $role === 'agent') {
11005 - $role = 'assistant';
11006 - }
11007 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
11008 - $role = 'user';
11009 - }
11010 - $formatted_conversation[] = array(
11011 - 'role' => $role,
11012 - 'content' => $message['content']
11013 - );
11014 - }
11015 - }
11016 -
11017 - // Check if we can actually stream
11018 - if (headers_sent() || !function_exists('curl_init')) {
11019 - // Fallback to regular response with testing data
11020 - //error_log("MxChat: DeepSeek streaming not possible, falling back to regular response");
11021 - $regular_response = $this->mxchat_generate_response_deepseek(
11022 - $selected_model,
11023 - $deepseek_api_key,
11024 - $conversation_history,
11025 - $relevant_content,
11026 - $session_id
11027 - );
11028 -
11029 - // Save bot response to transcript
11030 - if (!empty($regular_response) && !empty($session_id)) {
11031 - $this->mxchat_save_chat_message($session_id, 'bot', $regular_response);
11032 - }
11033 -
11034 - $response_data = [
11035 - 'text' => $regular_response,
11036 - 'html' => '',
11037 - 'session_id' => $session_id
11038 - ];
11039 -
11040 - if ($testing_data !== null) {
11041 - $response_data['testing_data'] = $testing_data;
11042 - //error_log("MxChat Testing: Added testing data to DeepSeek fallback response");
11043 - }
11044 -
11045 - header('Content-Type: application/json');
11046 - echo json_encode($response_data);
11047 - return true;
11048 - }
11049 -
11050 - // Prepare the request body with stream: true
11051 - $body = json_encode([
11052 - 'model' => $selected_model,
11053 - 'messages' => $formatted_conversation,
11054 - 'temperature' => 0.8,
11055 - 'stream' => true,
11056 - // DeepSeek V4 defaults to thinking mode ON (temperature ignored,
11057 - // long silent reasoning before the first delta); the widget wants
11058 - // the legacy deepseek-chat semantics = non-thinking.
11059 - 'thinking' => ['type' => 'disabled']
11060 - ]);
11061 -
11062 - // V2 retry-on-initial-connect: setup_streaming_headers is lazy-fired in WRITEFUNCTION.
11063 -
11064 - $captured_status_code = 0;
11065 - $captured_body_pre_stream = '';
11066 - $full_response = '';
11067 - $stream_started = false;
11068 - $buffer = '';
11069 - $errno = 0;
11070 - $http_code = 0;
11071 - $max_attempts = $this->mxchat_retry_enabled() ? 3 : 1;
11072 - $backoff_ms = array(0, 750, 2000);
11073 -
11074 - for ($attempt = 0; $attempt < $max_attempts; $attempt++) {
11075 - if ($attempt > 0 && $backoff_ms[$attempt] > 0) {
11076 - usleep($backoff_ms[$attempt] * 1000);
11077 - }
11078 -
11079 - $captured_status_code = 0;
11080 - $captured_body_pre_stream = '';
11081 - $full_response = '';
11082 - $stream_started = false;
11083 - $buffer = '';
11084 -
11085 - $ch = curl_init();
11086 - curl_setopt($ch, CURLOPT_URL, 'https://api.deepseek.com/v1/chat/completions');
11087 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
11088 - curl_setopt($ch, CURLOPT_POST, true);
11089 - curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
11090 - curl_setopt($ch, CURLOPT_HTTPHEADER, array(
11091 - 'Content-Type: application/json',
11092 - 'Authorization: Bearer ' . $deepseek_api_key
11093 - ));
11094 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
11095 - curl_setopt($ch, CURLOPT_TIMEOUT, 60);
11096 -
11097 - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use (&$captured_status_code) {
11098 - if ($captured_status_code === 0 && preg_match('#^HTTP/\S+\s+(\d+)\b#', $header, $m)) {
11099 - $captured_status_code = (int) $m[1];
11100 - }
11101 - return strlen($header);
11102 - });
11103 -
11104 - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$full_response, &$stream_started, &$buffer, &$captured_status_code, &$captured_body_pre_stream, $testing_data) {
11105 - if ($captured_status_code !== 0 && $captured_status_code !== 200) {
11106 - $captured_body_pre_stream .= $data;
11107 - return strlen($data);
11108 - }
11109 -
11110 - if (!$this->streaming_headers_sent) {
11111 - $this->setup_streaming_headers();
11112 - }
11113 -
11114 - if (!$stream_started && $testing_data !== null) {
11115 - echo "data: " . json_encode(['testing_data' => $testing_data]) . "\n\n";
11116 - flush();
11117 - $stream_started = true;
11118 - }
11119 -
11120 - $buffer .= $data;
11121 - $lines = explode("\n", $buffer);
11122 - $buffer = array_pop($lines);
11123 -
11124 - foreach ($lines as $line) {
11125 - if (trim($line) === '') {
11126 - continue;
11127 - }
11128 - if (strpos($line, 'data: ') !== 0) {
11129 - continue;
11130 - }
11131 -
11132 - $json_str = substr($line, 6);
11133 -
11134 - if (trim($json_str) === '[DONE]') {
11135 - echo "data: [DONE]\n\n";
11136 - flush();
11137 - continue;
11138 - }
11139 -
11140 - $json = json_decode(trim($json_str), true);
11141 - if ($json && isset($json['choices'][0]['delta']['content'])) {
11142 - $content = $json['choices'][0]['delta']['content'];
11143 - $full_response .= $content;
11144 - echo "data: " . json_encode(['content' => $content]) . "\n\n";
11145 - flush();
11146 - }
11147 - }
11148 -
11149 - return strlen($data);
11150 - });
11151 -
11152 - $response = curl_exec($ch);
11153 - $errno = curl_errno($ch);
11154 - $http_code = $captured_status_code !== 0 ? $captured_status_code : (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
11155 - curl_close($ch);
11156 -
11157 - if (!$errno && $http_code === 200) {
11158 - break;
11159 - }
11160 -
11161 - $is_transient = $this->mxchat_is_transient_provider_error_raw($http_code, $captured_body_pre_stream, 'openai', $errno);
11162 - $can_retry = !$this->streaming_headers_sent
11163 - && ($attempt + 1) < $max_attempts
11164 - && $is_transient;
11165 -
11166 - if (defined('WP_DEBUG') && WP_DEBUG) {
11167 - error_log(sprintf(
11168 - '[MxChat] deepseek_stream initial-connect failure (attempt=%d/%d, status=%d, errno=%d, transient=%s, %s).',
11169 - $attempt + 1, $max_attempts, $http_code, $errno,
11170 - $is_transient ? 'yes' : 'no',
11171 - $can_retry ? 'Retrying.' : 'Giving up.'
11172 - ));
11173 - }
11174 -
11175 - if (!$can_retry) {
11176 - break;
11177 - }
11178 - }
11179 -
11180 - if ($errno || $http_code !== 200) {
11181 - return $this->mxchat_stream_emit_fallback(
11182 - 'openai',
11183 - $this->mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content, $session_id),
11184 - $session_id,
11185 - $testing_data
11186 - );
11187 - }
11188 -
11189 - // Save the complete response to maintain chat persistence
11190 - if (!empty($full_response) && !empty($session_id)) {
11191 - // Prepare RAG context for streaming response
11192 - $rag_context_for_storage = null;
11193 - $has_rag_data = $this->last_similarity_analysis !== null && !empty($this->last_similarity_analysis['top_matches']);
11194 - $has_action_data = isset($this->last_action_analysis) && !empty($this->last_action_analysis);
11195 -
11196 - if ($has_rag_data || $has_action_data) {
11197 - $rag_context_for_storage = [];
11198 -
11199 - if ($has_rag_data) {
11200 - $rag_context_for_storage['top_matches'] = $this->last_similarity_analysis['top_matches'];
11201 - $rag_context_for_storage['approved_urls'] = $this->current_valid_urls ?? [];
11202 - $rag_context_for_storage['similarity_threshold'] = $this->last_similarity_analysis['threshold_used'] ?? 0.35;
11203 - $rag_context_for_storage['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'] ?? 'WordPress Database';
11204 - $rag_context_for_storage['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
11205 - }
11206 -
11207 - if ($has_action_data) {
11208 - $rag_context_for_storage['action_analysis'] = $this->last_action_analysis;
11209 - }
11210 - }
11211 - $this->mxchat_save_chat_message($session_id, 'bot', $full_response, null, $this->mxchat_fc_attach_tool_trace($rag_context_for_storage));
11212 - }
11213 -
11214 - return true; // Indicate streaming completed successfully
11215 -
11216 - } catch (Exception $e) {
11217 - return $this->mxchat_stream_emit_fallback(
11218 - 'openai',
11219 - $this->mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content),
11220 - $session_id,
11221 - $testing_data
11222 - );
11223 - }
11224 -}
11225 -
11226 -
11227 -/**
11228 - * Extract a human-readable error message from a decoded provider response body.
11229 - * Providers disagree on shape: OpenAI/Anthropic/Google nest it (error.message),
11230 - * xAI returns a plain string under 'error'. Mirrors mxchat-vision's shipped
11231 - * extract_provider_error(); deliberately hint-free in core (vision's too-small
11232 - * image hint is an upload concern that doesn't apply here).
11233 - *
11234 - * @param mixed $decoded_body Decoded JSON body (array), or whatever json_decode returned.
11235 - * @param string $fallback Message to return when no provider text is found.
11236 - * @return string
11237 - */
11238 -private function extract_provider_error($decoded_body, $fallback) {
11239 - $message = '';
11240 - if (isset($decoded_body['error']['message']) && is_string($decoded_body['error']['message']) && $decoded_body['error']['message'] !== '') {
11241 - $message = $decoded_body['error']['message'];
11242 - } elseif (isset($decoded_body['error']) && is_string($decoded_body['error']) && $decoded_body['error'] !== '') {
11243 - $message = $decoded_body['error'];
11244 - }
11245 -
11246 - if ($message === '') {
11247 - return $fallback;
11248 - }
11249 -
11250 - return $message;
11251 -}
11252 -
11253 -/**
11254 - * plan-4aa8e5: a provider 200 whose body parses to no text must never reach
11255 - * the widget as a silent empty bot bubble. Standard error shape for that
11256 - * case, preferring the body's own explanation — error.message first (the
11257 - * 950731 passthrough pattern), then the Responses API's
11258 - * incomplete_details.reason (e.g. "max_output_tokens") — before the generic
11259 - * retry message.
11260 - */
11261 -private function mxchat_empty_completion_error($decoded_body, $provider_label) {
11262 - $reason = '';
11263 - if (isset($decoded_body['error']['message']) && is_string($decoded_body['error']['message']) && $decoded_body['error']['message'] !== '') {
11264 - $reason = $decoded_body['error']['message'];
11265 - } elseif (isset($decoded_body['incomplete_details']['reason']) && is_string($decoded_body['incomplete_details']['reason']) && $decoded_body['incomplete_details']['reason'] !== '') {
11266 - $reason = sprintf(__('response incomplete: %s', 'mxchat'), $decoded_body['incomplete_details']['reason']);
11267 - }
11268 -
11269 - $message = ($reason !== '')
11270 - ? sprintf(esc_html__('%1$s returned an empty response (%2$s). Please try again.', 'mxchat'), $provider_label, esc_html($reason))
11271 - : sprintf(esc_html__('%s returned an empty response. Please try again.', 'mxchat'), $provider_label);
11272 -
11273 - return [
11274 - 'error' => $message,
11275 - 'error_code' => 'empty_completion',
11276 - 'provider' => strtolower($provider_label),
11277 - ];
11278 -}
11279 -
11280 -private function mxchat_generate_response_openrouter($selected_model, $openrouter_api_key, $conversation_history, $relevant_content, $session_id = '') {
11281 - try {
11282 - if (!is_array($conversation_history)) {
11283 - $conversation_history = array();
11284 - }
11285 -
11286 - $bot_id = $this->get_current_bot_id($session_id);
11287 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
11288 -
11289 - $formatted_conversation = array();
11290 -
11291 - $formatted_conversation[] = array(
11292 - 'role' => 'system',
11293 - 'content' => $system_prompt_instructions . " " . $relevant_content
11294 - );
11295 -
11296 - foreach ($conversation_history as $message) {
11297 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
11298 - $role = $message['role'];
11299 -
11300 - if ($role === 'bot' || $role === 'agent') {
11301 - $role = 'assistant';
11302 - }
11303 - if (!in_array($role, ['system', 'assistant', 'user'])) {
11304 - $role = 'user';
11305 - }
11306 -
11307 - $formatted_conversation[] = array(
11308 - 'role' => $role,
11309 - 'content' => $message['content']
11310 - );
11311 - }
11312 - }
11313 -
11314 - $body = json_encode([
11315 - 'model' => $selected_model,
11316 - 'messages' => $formatted_conversation,
11317 - 'temperature' => 1,
11318 - ]);
11319 -
11320 - $args = [
11321 - 'body' => $body,
11322 - 'headers' => [
11323 - 'Content-Type' => 'application/json',
11324 - 'Authorization' => 'Bearer ' . $openrouter_api_key,
11325 - 'HTTP-Referer' => home_url(),
11326 - 'X-Title' => get_bloginfo('name'),
11327 - ],
11328 - 'timeout' => 60,
11329 - 'redirection' => 5,
11330 - 'blocking' => true,
11331 - 'httpversion' => '1.0',
11332 - 'sslverify' => true,
11333 - ];
11334 -
11335 - $response = $this->mxchat_provider_call_with_retry('https://openrouter.ai/api/v1/chat/completions', $args, 'openai');
11336 -
11337 - if (is_wp_error($response)) {
11338 - $error_message = $response->get_error_message();
11339 - return [
11340 - 'error' => $this->mxchat_friendly_chat_error(0, $error_message, 'OpenRouter', $selected_model),
11341 - 'error_code' => 'openrouter_connection_error',
11342 - 'provider' => 'openrouter'
11343 - ];
11344 - }
11345 -
11346 - $status_code = wp_remote_retrieve_response_code($response);
11347 - if ($status_code !== 200) {
11348 - $response_body = wp_remote_retrieve_body($response);
11349 - $decoded_response = json_decode($response_body, true);
11350 -
11351 - $error_message = $this->extract_provider_error($decoded_response, 'HTTP Error ' . $status_code);
11352 -
11353 - return [
11354 - 'error' => esc_html__('OpenRouter API error: ', 'mxchat') . esc_html($error_message),
11355 - 'error_code' => 'openrouter_api_error',
11356 - 'provider' => 'openrouter',
11357 - 'status_code' => $status_code
11358 - ];
11359 - }
11360 -
11361 - $response_body = wp_remote_retrieve_body($response);
11362 - $decoded_response = json_decode($response_body, true);
11363 -
11364 - if (isset($decoded_response['choices'][0]['message']['content'])) {
11365 - $text = trim($decoded_response['choices'][0]['message']['content']);
11366 - if ($text !== '') {
11367 - return $text;
11368 - }
11369 - return $this->mxchat_empty_completion_error($decoded_response, 'OpenRouter');
11370 - } else {
11371 - return [
11372 - 'error' => esc_html__('Unexpected response format from OpenRouter.', 'mxchat'),
11373 - 'error_code' => 'openrouter_response_format_error',
11374 - 'provider' => 'openrouter'
11375 - ];
11376 - }
11377 - } catch (Exception $e) {
11378 - return [
11379 - 'error' => esc_html__('System error when processing OpenRouter request: ', 'mxchat') . esc_html($e->getMessage()),
11380 - 'error_code' => 'openrouter_exception',
11381 - 'provider' => 'openrouter'
11382 - ];
11383 - }
11384 -}
11385 -
11386 -/**
11387 - * Build a chat-bubble-safe message for a non-200 provider (chat) error.
11388 - *
11389 - * Visitors must NEVER see raw API internals (model names, key/billing/quota
11390 - * text). Admins (manage_options) get an actionable hint — and, for the common
11391 - * "model not available on this key" case, a direct pointer to change the model
11392 - * (the site owner can fix it in one click). Anthropic returns model-access as a
11393 - * 4xx with a message like "Claude Fable 5 is not available. Please use Opus 4.8."
11394 - *
11395 - * Provider-agnostic by design (reusable for the xai/gemini/deepseek branches),
11396 - * but Anthropic is the confirmed, reproduced case wired up here (plan 1d3b0f).
11397 - *
11398 - * @param int $http_code HTTP status from the provider.
11399 - * @param string $error_message Raw provider error.message (may be empty).
11400 - * @param string $provider_label Human provider name, e.g. 'Anthropic'.
11401 - * @param string $model The model id the failing request used. When a
11402 - * model-access failure is detected and this is
11403 - * non-empty, a persistent admin notice is armed
11404 - * (mxchat_show_model_access_notice) so the OWNER
11405 - * learns about it even when only anonymous
11406 - * visitors hit the broken bot (plan e46b8f).
11407 - * @return string Message safe to render as a chat bubble.
11408 - */
11409 -private function mxchat_friendly_chat_error($http_code, $error_message, $provider_label = '', $model = '') {
11410 - $raw = trim((string) $error_message);
11411 -
11412 - // Detect a model-access / availability problem the site owner can fix by
11413 - // choosing a different model. (Anthropic phrasing + the common API shapes.)
11414 - $low = strtolower($raw);
11415 - $is_model_access = (strpos($low, 'not available') !== false)
11416 - || (strpos($low, 'does not have access') !== false)
11417 - || (strpos($low, 'do not have access') !== false)
11418 - || (strpos($low, 'does not exist') !== false) // OpenAI: "model `x` does not exist or you do not have access"
11419 - || (strpos($low, 'model_not_found') !== false)
11420 - || (strpos($low, 'not_found_error') !== false)
11421 - || (strpos($low, 'model not found') !== false) // xAI
11422 - || (strpos($low, 'not found') !== false) // Gemini: "models/x is not found for API version ..."
11423 - || (strpos($low, 'permission_denied') !== false) // Gemini gated model
11424 - || (strpos($low, 'permission denied') !== false);
11425 -
11426 - // Arm the persistent admin notice (throttled: skip if the same model was
11427 - // flagged within the last hour — chat errors can fire per message).
11428 - if ($is_model_access && $model !== '') {
11429 - $existing = get_option('mxchat_model_access_notice');
11430 - $stale = !is_array($existing)
11431 - || !isset($existing['model'], $existing['time'])
11432 - || $existing['model'] !== $model
11433 - || (time() - (int) $existing['time']) > HOUR_IN_SECONDS;
11434 - if ($stale) {
11435 - update_option('mxchat_model_access_notice', array(
11436 - 'model' => (string) $model,
11437 - 'provider' => (string) $provider_label,
11438 - 'time' => time(),
11439 - ), false);
11440 - }
11441 - }
11442 -
11443 - if (current_user_can('manage_options')) {
11444 - if ($is_model_access) {
11445 - return $raw !== ''
11446 - ? sprintf(
11447 - /* translators: %s: raw provider error detail */
11448 - esc_html__('The selected AI model isn\'t available on your API key. Choose another model in MxChat → Settings. (Details: %s)', 'mxchat'),
11449 - $raw
11450 - )
11451 - : esc_html__('The selected AI model isn\'t available on your API key. Choose another model in MxChat → Settings.', 'mxchat');
11452 - }
11453 - return $raw !== ''
11454 - ? sprintf(
11455 - /* translators: 1: provider label, 2: raw provider error detail */
11456 - esc_html__('The AI provider (%1$s) returned an error: %2$s. Check your model and API key in MxChat → Settings.', 'mxchat'),
11457 - $provider_label !== '' ? $provider_label : esc_html__('AI', 'mxchat'),
11458 - $raw
11459 - )
11460 - : esc_html__('The AI provider returned an error. Check your model and API key in MxChat → Settings.', 'mxchat');
11461 - }
11462 -
11463 - // Visitors: friendly, generic, no internals leaked.
11464 - return esc_html__('Sorry, I\'m having trouble responding right now. Please try again in a moment.', 'mxchat');
11465 -}
11466 -
11467 -private function mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content, $session_id = '') {
11468 - // Anthropic retired claude-opus-4-20250514 / claude-sonnet-4-20250514 on 2026-06-15.
11469 - // Read-time rescue: remap a saved dead ID to the current equivalent before the API call.
11470 - if ($selected_model === 'claude-opus-4-20250514') { $selected_model = 'claude-opus-4-8'; }
11471 - elseif ($selected_model === 'claude-sonnet-4-20250514') { $selected_model = 'claude-sonnet-4-6'; }
11472 -
11473 - // Get bot ID from session or request
11474 - $bot_id = $this->get_current_bot_id($session_id);
11475 -
11476 - // Get system prompt instructions using centralized function
11477 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
11478 -
11479 - // Clean and validate conversation history
11480 - foreach ($conversation_history as &$message) {
11481 - // Convert bot and agent roles to assistant
11482 - if ($message['role'] === 'bot' || $message['role'] === 'agent') {
11483 - $message['role'] = 'assistant';
11484 - }
11485 -
11486 - // Remove unsupported roles - Claude only supports 'assistant' and 'user'
11487 - if (!in_array($message['role'], ['assistant', 'user'])) {
11488 - $message['role'] = 'user';
11489 - }
11490 -
11491 - // Ensure content field exists
11492 - if (!isset($message['content']) || empty($message['content'])) {
11493 - $message['content'] = '';
11494 - }
11495 -
11496 - // Remove any unsupported fields
11497 - $message = array_intersect_key($message, array_flip(['role', 'content']));
11498 - }
11499 -
11500 - // Add relevant content as the latest user message
11501 - $conversation_history[] = [
11502 - 'role' => 'user',
11503 - 'content' => $relevant_content
11504 - ];
11505 -
11506 - // Build request body
11507 - $payload = [
11508 - 'model' => $selected_model,
11509 - 'max_tokens' => 1000,
11510 - 'temperature' => 0.8,
11511 - 'messages' => $conversation_history,
11512 - 'system' => $this->mxchat_anthropic_system_blocks($system_prompt_instructions)
11513 - ];
11514 - if ($this->mxchat_claude_omits_temperature($selected_model)) { unset($payload['temperature']); }
11515 - $body = json_encode($payload);
11516 -
11517 - // Set up API request
11518 - $args = [
11519 - 'body' => $body,
11520 - 'headers' => [
11521 - 'Content-Type' => 'application/json',
11522 - 'x-api-key' => $claude_api_key,
11523 - 'anthropic-version' => '2023-06-01'
11524 - ],
11525 - 'timeout' => 60,
11526 - 'redirection' => 5,
11527 - 'blocking' => true,
11528 - 'httpversion' => '1.0',
11529 - 'sslverify' => true,
11530 - ];
11531 -
11532 - // Make API request
11533 - $response = $this->mxchat_provider_call_with_retry('https://api.anthropic.com/v1/messages', $args, 'anthropic');
11534 -
11535 - // Check for WordPress errors
11536 - if (is_wp_error($response)) {
11537 - //error_log("Claude API request error: " . $response->get_error_message());
11538 - return "Sorry, there was an error connecting to the API.";
11539 - }
11540 -
11541 - // Check HTTP response code
11542 - $http_code = wp_remote_retrieve_response_code($response);
11543 - if ($http_code !== 200) {
11544 - $error_body = wp_remote_retrieve_body($response);
11545 - //error_log("Claude API HTTP error: " . $http_code . " - " . $error_body);
11546 -
11547 - // Try to extract error message from response
11548 - $error_data = json_decode($error_body, true);
11549 - $error_message = isset($error_data['error']['message']) ?
11550 - $error_data['error']['message'] :
11551 - "HTTP error " . $http_code;
11552 -
11553 - // Surface an admin-actionable message (and a model-change pointer for the
11554 - // model-access case) without leaking raw API internals to visitors. This
11555 - // is the single chokepoint for BOTH the non-streaming and streaming Claude
11556 - // paths (the stream's non-200 fallback re-enters this method). plan 1d3b0f.
11557 - return $this->mxchat_friendly_chat_error($http_code, $error_message, 'Anthropic', $selected_model);
11558 - }
11559 -
11560 - // Parse response
11561 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
11562 -
11563 - // Check for JSON decode errors
11564 - if (json_last_error() !== JSON_ERROR_NONE) {
11565 - //error_log("Claude API JSON decode error: " . json_last_error_msg());
11566 - return "Sorry, there was an error processing the API response.";
11567 - }
11568 -
11569 - // Prompt-cache visibility (plan 1ff43b), dev mode only: a working cache
11570 - // shows cache_creation_input_tokens on the first request of a conversation
11571 - // and cache_read_input_tokens > 0 on the ones after it.
11572 - if (defined('MXCHAT_DEV_MODE') && MXCHAT_DEV_MODE && isset($response_body['usage'])) {
11573 - error_log(sprintf(
11574 - '[MxChat Anthropic cache] input=%d cache_write=%d cache_read=%d',
11575 - intval($response_body['usage']['input_tokens'] ?? 0),
11576 - intval($response_body['usage']['cache_creation_input_tokens'] ?? 0),
11577 - intval($response_body['usage']['cache_read_input_tokens'] ?? 0)
11578 - ));
11579 - }
11580 -
11581 - // Extract and validate response content. claude-fable-5 prepends a
11582 - // thinking block to content even with no thinking param — take the first
11583 - // TEXT block rather than content[0].
11584 - if (isset($response_body['content']) && is_array($response_body['content'])) {
11585 - foreach ($response_body['content'] as $block) {
11586 - // plan-4aa8e5: skip empty text blocks — a 200 whose only text
11587 - // block trims to '' must not render as a silent empty bubble.
11588 - if (isset($block['type'], $block['text']) && $block['type'] === 'text' && trim($block['text']) !== '') {
11589 - return trim($block['text']);
11590 - }
11591 - }
11592 - return $this->mxchat_empty_completion_error($response_body, 'Claude');
11593 - }
11594 -
11595 - // Log unexpected response format
11596 - //error_log("Claude API unexpected response format: " . print_r($response_body, true));
11597 - return "Sorry, I received an unexpected response format from the API.";
11598 -}
11599 -private function mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content, $session_id = '') {
11600 - // OpenAI retires gpt-5.1-chat-latest / gpt-5.3-chat-latest on 2026-08-10
11601 - // (replacement gpt-5.6-sol). Read-time rescue for saved / bot-level ids
11602 - // that missed mxchat_migrate_deprecated_models() (plan e46b8f).
11603 - if ($selected_model === 'gpt-5.1-chat-latest' || $selected_model === 'gpt-5.3-chat-latest') { $selected_model = 'gpt-5.6-sol'; }
11604 - try {
11605 - // Ensure conversation_history is an array
11606 - if (!is_array($conversation_history)) {
11607 - $conversation_history = array();
11608 - }
11609 -
11610 - // Get bot ID from session or request. plan eb9c38: resolve the real bot
11611 - // from the session (was hardcoded '' → always default bot on multi-bot
11612 - // installs) and fix the undefined $session_id that fed get_system_instructions.
11613 - $bot_id = $this->get_current_bot_id($session_id);
11614 -
11615 - // Get system prompt instructions using centralized function
11616 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
11617 -
11618 - // Create a new array for the formatted conversation
11619 - $formatted_conversation = array();
11620 -
11621 - // Add system message first
11622 - $formatted_conversation[] = array(
11623 - 'role' => 'system',
11624 - 'content' => $system_prompt_instructions . " " . $relevant_content
11625 - );
11626 -
11627 - // Add the rest of the conversation history
11628 - foreach ($conversation_history as $message) {
11629 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
11630 - $role = $message['role'];
11631 -
11632 - // Convert roles to supported format
11633 - if ($role === 'bot' || $role === 'agent') {
11634 - $role = 'assistant';
11635 - }
11636 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
11637 - $role = 'user';
11638 - }
11639 -
11640 - $formatted_conversation[] = array(
11641 - 'role' => $role,
11642 - 'content' => $message['content']
11643 - );
11644 - }
11645 - }
11646 -
11647 - // Build request body with optimal settings for fast responses
11648 - $request_body = [
11649 - 'model' => $selected_model,
11650 - 'messages' => $formatted_conversation,
11651 - 'temperature' => 1,
11652 - 'stream' => false
11653 - ];
11654 -
11655 - // reasoning_effort — sourced from the core model catalog (plan-dcb71c);
11656 - // frozen inline ladder lives in mxchat_reasoning_effort_fallback().
11657 - $effort = $this->mxchat_reasoning_effort_for($selected_model, 'chat');
11658 - if ($effort !== null) {
11659 - $request_body['reasoning_effort'] = $effort;
11660 - }
11661 -
11662 - $body = json_encode($request_body);
11663 -
11664 - $args = [
11665 - 'body' => $body,
11666 - 'headers' => [
11667 - 'Content-Type' => 'application/json',
11668 - 'Authorization' => 'Bearer ' . $api_key,
11669 - ],
11670 - 'timeout' => 60,
11671 - 'redirection' => 5,
11672 - 'blocking' => true,
11673 - 'httpversion' => '1.0',
11674 - 'sslverify' => true,
11675 - ];
11676 -
11677 - $response = $this->mxchat_provider_call_with_retry('https://api.openai.com/v1/chat/completions', $args, 'openai');
11678 -
11679 - if (is_wp_error($response)) {
11680 - $error_message = $response->get_error_message();
11681 - return [
11682 - 'error' => $this->mxchat_friendly_chat_error(0, $error_message, 'OpenAI', $selected_model),
11683 - 'error_code' => 'openai_connection_error',
11684 - 'provider' => 'openai'
11685 - ];
11686 - }
11687 -
11688 - $status_code = wp_remote_retrieve_response_code($response);
11689 -
11690 - // plan-25b972 self-heal: a 400 rejecting our reasoning_effort VALUE is
11691 - // deterministic (per-model support drift / stale catalog entry) — strip
11692 - // the param and retry ONCE.
11693 - if ($status_code !== 200
11694 - && isset($request_body['reasoning_effort'])
11695 - && $this->mxchat_is_reasoning_effort_rejection($status_code, wp_remote_retrieve_body($response))) {
11696 - if (defined('WP_DEBUG') && WP_DEBUG) {
11697 - error_log(sprintf(
11698 - '[MxChat] openai chat: model %s rejected reasoning_effort \'%s\' — retrying once without the param (plan-25b972).',
11699 - $selected_model, $request_body['reasoning_effort']
11700 - ));
11701 - }
11702 - unset($request_body['reasoning_effort']);
11703 - $args['body'] = json_encode($request_body);
11704 - $retry_response = $this->mxchat_provider_call_with_retry('https://api.openai.com/v1/chat/completions', $args, 'openai');
11705 - if (!is_wp_error($retry_response)) {
11706 - $response = $retry_response;
11707 - $status_code = wp_remote_retrieve_response_code($response);
11708 - }
11709 - }
11710 -
11711 - if ($status_code !== 200) {
11712 - $response_body = wp_remote_retrieve_body($response);
11713 - $decoded_response = json_decode($response_body, true);
11714 -
11715 - $error_message = isset($decoded_response['error']['message'])
11716 - ? $decoded_response['error']['message']
11717 - : 'HTTP Error ' . $status_code;
11718 -
11719 - $error_type = isset($decoded_response['error']['type'])
11720 - ? $decoded_response['error']['type']
11721 - : 'unknown';
11722 -
11723 - // Handle specific error types
11724 - switch ($error_type) {
11725 - case 'invalid_request_error':
11726 - if (strpos($error_message, 'API key') !== false) {
11727 - return [
11728 - 'error' => esc_html__('Invalid OpenAI API key. Please check your API key configuration.', 'mxchat'),
11729 - 'error_code' => 'openai_invalid_api_key',
11730 - 'provider' => 'openai'
11731 - ];
11732 - }
11733 - break;
11734 -
11735 - case 'authentication_error':
11736 - return [
11737 - 'error' => esc_html__('Authentication failed with OpenAI. Please check your API key.', 'mxchat'),
11738 - 'error_code' => 'openai_auth_error',
11739 - 'provider' => 'openai'
11740 - ];
11741 -
11742 - case 'rate_limit_exceeded':
11743 - return [
11744 - 'error' => esc_html__('OpenAI rate limit exceeded. Please try again later.', 'mxchat'),
11745 - 'error_code' => 'openai_rate_limit',
11746 - 'provider' => 'openai'
11747 - ];
11748 -
11749 - case 'quota_exceeded':
11750 - return [
11751 - 'error' => esc_html__('OpenAI API quota exceeded. Please check your billing details.', 'mxchat'),
11752 - 'error_code' => 'openai_quota_exceeded',
11753 - 'provider' => 'openai'
11754 - ];
11755 - }
11756 -
11757 - // Generic error fallback only — the typed cases above already produce
11758 - // clean messages. Route the raw-tail generic case through the leak-safe
11759 - // helper so visitors never see provider internals. plan 5da59a.
11760 - return [
11761 - 'error' => $this->mxchat_friendly_chat_error($status_code, $error_message, 'OpenAI', $selected_model),
11762 - 'error_code' => 'openai_api_error',
11763 - 'provider' => 'openai',
11764 - 'status_code' => $status_code
11765 - ];
11766 - }
11767 -
11768 - $response_body = wp_remote_retrieve_body($response);
11769 - $decoded_response = json_decode($response_body, true);
11770 -
11771 - if (isset($decoded_response['choices'][0]['message']['content'])) {
11772 - $text = trim($decoded_response['choices'][0]['message']['content']);
11773 - if ($text !== '') {
11774 - return $text;
11775 - }
11776 - return $this->mxchat_empty_completion_error($decoded_response, 'OpenAI');
11777 - } else {
11778 - return [
11779 - 'error' => esc_html__('Unexpected response format from OpenAI.', 'mxchat'),
11780 - 'error_code' => 'openai_response_format_error',
11781 - 'provider' => 'openai'
11782 - ];
11783 - }
11784 - } catch (Exception $e) {
11785 - return [
11786 - 'error' => esc_html__('System error when processing OpenAI request: ', 'mxchat') . esc_html($e->getMessage()),
11787 - 'error_code' => 'openai_exception',
11788 - 'provider' => 'openai'
11789 - ];
11790 - }
11791 -}
11792 -
11793 -private function mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content, $session_id = '') {
11794 - try {
11795 - // Get bot ID from session or request
11796 - $bot_id = $this->get_current_bot_id($session_id);
11797 -
11798 - // Get system prompt instructions using centralized function
11799 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
11800 -
11801 - // Add system prompt to relevant content
11802 - $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
11803 -
11804 - // Prepend system instructions to the conversation history
11805 - array_unshift($conversation_history, [
11806 - 'role' => 'system',
11807 - 'content' => "Here are your instructions: " . $content_with_instructions
11808 - ]);
11809 -
11810 - // Ensure consistency: Replace 'bot' and 'agent' roles with supported values
11811 - foreach ($conversation_history as &$message) {
11812 - if ($message['role'] === 'bot') {
11813 - $message['role'] = 'assistant';
11814 - } elseif ($message['role'] === 'agent') {
11815 - // Tag the message as coming from a live agent
11816 - $message['role'] = 'assistant';
11817 - if (!isset($message['metadata'])) {
11818 - $message['metadata'] = ['source' => 'live_agent'];
11819 - }
11820 - }
11821 -
11822 - // Ensure all roles are valid
11823 - if (!in_array($message['role'], ['system', 'assistant', 'user', 'function', 'tool'])) {
11824 - $message['role'] = 'user'; // Default to 'user'
11825 - }
11826 - }
11827 -
11828 - // Build the request body
11829 - $body = json_encode([
11830 - 'model' => $selected_model,
11831 - 'messages' => $conversation_history,
11832 - 'temperature' => 0.8,
11833 - 'stream' => false
11834 - ]);
11835 -
11836 - // Set up the API request
11837 - $args = [
11838 - 'body' => $body,
11839 - 'headers' => [
11840 - 'Content-Type' => 'application/json',
11841 - 'Authorization' => 'Bearer ' . $xai_api_key,
11842 - ],
11843 - 'timeout' => 60,
11844 - 'redirection' => 5,
11845 - 'blocking' => true,
11846 - 'httpversion' => '1.0',
11847 - 'sslverify' => true,
11848 - ];
11849 -
11850 - // Make the API request
11851 - $response = $this->mxchat_provider_call_with_retry('https://api.x.ai/v1/chat/completions', $args, 'xai');
11852 -
11853 - // Process the response
11854 - if (is_wp_error($response)) {
11855 - $error_message = $response->get_error_message();
11856 - //error_log('X.AI API Error: ' . $error_message);
11857 - return [
11858 - 'error' => $this->mxchat_friendly_chat_error(0, $error_message, 'X.AI', $selected_model),
11859 - 'error_code' => 'xai_connection_error',
11860 - 'provider' => 'xai'
11861 - ];
11862 - }
11863 -
11864 - $status_code = wp_remote_retrieve_response_code($response);
11865 - if ($status_code !== 200) {
11866 - $response_body = wp_remote_retrieve_body($response);
11867 - $decoded_response = json_decode($response_body, true);
11868 -
11869 - // Log the full response for debugging
11870 - //error_log('X.AI Error Response: ' . print_r($decoded_response, true));
11871 -
11872 - // Extract error message from X.AI's specific format
11873 - $error_message = '';
11874 -
11875 - // Check for direct error string (as seen in your logs)
11876 - if (isset($decoded_response['error']) && is_string($decoded_response['error'])) {
11877 - $error_message = $decoded_response['error'];
11878 - }
11879 - // Check for nested error object (OpenAI style)
11880 - elseif (isset($decoded_response['error']['message'])) {
11881 - $error_message = $decoded_response['error']['message'];
11882 - }
11883 - // Check for top-level message
11884 - elseif (isset($decoded_response['message'])) {
11885 - $error_message = $decoded_response['message'];
11886 - }
11887 - // Fallback
11888 - else {
11889 - $error_message = 'HTTP Error ' . $status_code;
11890 - }
11891 -
11892 - //error_log('X.AI API HTTP Error: ' . $status_code . ' - ' . $error_message);
11893 -
11894 - // Check for API key errors using string matching
11895 - if (stripos($error_message, 'api key') !== false ||
11896 - stripos($error_message, 'incorrect api key') !== false ||
11897 - stripos($error_message, 'invalid api key') !== false) {
11898 - return [
11899 - 'error' => esc_html__('Invalid X.AI API key. Please check your API key configuration.', 'mxchat'),
11900 - 'error_code' => 'xai_invalid_api_key',
11901 - 'provider' => 'xai'
11902 - ];
11903 - }
11904 -
11905 - // Authentication errors
11906 - if ($status_code === 401 || $status_code === 403 ||
11907 - stripos($error_message, 'auth') !== false) {
11908 - return [
11909 - 'error' => esc_html__('Authentication failed with X.AI. Please check your API key.', 'mxchat') . ' ' . esc_html($error_message),
11910 - 'error_code' => 'xai_auth_error',
11911 - 'provider' => 'xai'
11912 - ];
11913 - }
11914 -
11915 - // Model errors — keep the canned category text as a prefix, but carry the
11916 - // provider's extracted reason (e.g. "Model not found: <id>") so the owner
11917 - // sees the specific model/reason instead of only the generic category.
11918 - if (stripos($error_message, 'model') !== false) {
11919 - return [
11920 - 'error' => esc_html__('Invalid model specified for X.AI. Please check your model configuration.', 'mxchat') . ' ' . esc_html($error_message),
11921 - 'error_code' => 'xai_invalid_model',
11922 - 'provider' => 'xai'
11923 - ];
11924 - }
11925 -
11926 - // Rate limit errors
11927 - if ($status_code === 429 ||
11928 - stripos($error_message, 'rate') !== false ||
11929 - stripos($error_message, 'limit') !== false) {
11930 - return [
11931 - 'error' => esc_html__('X.AI rate limit exceeded. Please try again later.', 'mxchat'),
11932 - 'error_code' => 'xai_rate_limit',
11933 - 'provider' => 'xai'
11934 - ];
11935 - }
11936 -
11937 - // Quota errors
11938 - if (stripos($error_message, 'quota') !== false ||
11939 - stripos($error_message, 'billing') !== false) {
11940 - return [
11941 - 'error' => esc_html__('X.AI API quota exceeded. Please check your billing details.', 'mxchat'),
11942 - 'error_code' => 'xai_quota_exceeded',
11943 - 'provider' => 'xai'
11944 - ];
11945 - }
11946 -
11947 - // Server errors
11948 - if ($status_code >= 500) {
11949 - return [
11950 - 'error' => esc_html__('X.AI service is currently unavailable. Please try again later.', 'mxchat'),
11951 - 'error_code' => 'xai_service_unavailable',
11952 - 'provider' => 'xai'
11953 - ];
11954 - }
11955 -
11956 - // Generic error fallback. Route the user-facing text through the
11957 - // leak-safe helper (admins get an actionable hint, visitors a generic
11958 - // fallback) instead of echoing raw provider internals. Preserve the
11959 - // structured contract (error_code/provider/status_code) for logging. plan 5da59a.
11960 - return [
11961 - 'error' => $this->mxchat_friendly_chat_error($status_code, $error_message, 'xAI', $selected_model),
11962 - 'error_code' => 'xai_api_error',
11963 - 'provider' => 'xai',
11964 - 'status_code' => $status_code
11965 - ];
11966 - }
11967 -
11968 - $response_body = wp_remote_retrieve_body($response);
11969 - $decoded_response = json_decode($response_body, true);
11970 -
11971 - if (isset($decoded_response['choices'][0]['message']['content'])) {
11972 - $text = trim($decoded_response['choices'][0]['message']['content']);
11973 - if ($text !== '') {
11974 - return $text;
11975 - }
11976 - return $this->mxchat_empty_completion_error($decoded_response, 'X.AI');
11977 - } else {
11978 - //error_log('X.AI API Response Format Error: ' . print_r($decoded_response, true));
11979 - return [
11980 - 'error' => esc_html__('Unexpected response format from X.AI.', 'mxchat'),
11981 - 'error_code' => 'xai_response_format_error',
11982 - 'provider' => 'xai'
11983 - ];
11984 - }
11985 -} catch (Exception $e) {
11986 - //error_log('X.AI Exception: ' . $e->getMessage());
11987 - return [
11988 - 'error' => esc_html__('System error when processing X.AI request: ', 'mxchat') . esc_html($e->getMessage()),
11989 - 'error_code' => 'xai_exception',
11990 - 'provider' => 'xai'
11991 - ];
11992 -}
11993 -
11994 -
11995 -}
11996 -private function mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content, $session_id = '') {
11997 - try {
11998 - // Ensure conversation_history is an array
11999 - if (!is_array($conversation_history)) {
12000 - $conversation_history = array();
12001 - }
12002 -
12003 - // Get bot ID from session or request
12004 - $bot_id = $this->get_current_bot_id($session_id);
12005 -
12006 - // Get system prompt instructions using centralized function
12007 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
12008 -
12009 - // Create a new array for the formatted conversation
12010 - $formatted_conversation = array();
12011 -
12012 - // Add system message first
12013 - $formatted_conversation[] = array(
12014 - 'role' => 'system',
12015 - 'content' => $system_prompt_instructions . " " . $relevant_content
12016 - );
12017 -
12018 - // Add the rest of the conversation history
12019 - foreach ($conversation_history as $message) {
12020 - if (is_array($message) && isset($message['role']) && isset($message['content'])) {
12021 - $role = $message['role'];
12022 -
12023 - // Convert roles to supported format
12024 - if ($role === 'bot' || $role === 'agent') {
12025 - $role = 'assistant';
12026 - }
12027 - if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
12028 - $role = 'user';
12029 - }
12030 -
12031 - $formatted_conversation[] = array(
12032 - 'role' => $role,
12033 - 'content' => $message['content']
12034 - );
12035 - }
12036 - }
12037 -
12038 - $body = json_encode([
12039 - 'model' => $selected_model,
12040 - 'messages' => $formatted_conversation,
12041 - 'temperature' => 0.8,
12042 - 'stream' => false,
12043 - // DeepSeek V4 defaults to thinking mode ON (temperature ignored,
12044 - // slow reasoning-first responses); the widget wants the legacy
12045 - // deepseek-chat semantics = non-thinking.
12046 - 'thinking' => ['type' => 'disabled']
12047 - ]);
12048 -
12049 - $args = [
12050 - 'body' => $body,
12051 - 'headers' => [
12052 - 'Content-Type' => 'application/json',
12053 - 'Authorization' => 'Bearer ' . $deepseek_api_key,
12054 - ],
12055 - 'timeout' => 60,
12056 - 'redirection' => 5,
12057 - 'blocking' => true,
12058 - 'httpversion' => '1.0',
12059 - 'sslverify' => true,
12060 - ];
12061 -
12062 - $response = $this->mxchat_provider_call_with_retry('https://api.deepseek.com/v1/chat/completions', $args, 'openai');
12063 -
12064 - if (is_wp_error($response)) {
12065 - $error_message = $response->get_error_message();
12066 - //error_log('DeepSeek API Error: ' . $error_message);
12067 - return [
12068 - 'error' => $this->mxchat_friendly_chat_error(0, $error_message, 'DeepSeek', $selected_model),
12069 - 'error_code' => 'deepseek_connection_error',
12070 - 'provider' => 'deepseek'
12071 - ];
12072 - }
12073 -
12074 - $status_code = wp_remote_retrieve_response_code($response);
12075 - if ($status_code !== 200) {
12076 - $response_body = wp_remote_retrieve_body($response);
12077 - $decoded_response = json_decode($response_body, true);
12078 -
12079 - $error_message = isset($decoded_response['error']['message'])
12080 - ? $decoded_response['error']['message']
12081 - : 'HTTP Error ' . $status_code;
12082 -
12083 - $error_type = isset($decoded_response['error']['type'])
12084 - ? $decoded_response['error']['type']
12085 - : 'unknown';
12086 -
12087 - //error_log('DeepSeek API HTTP Error: ' . $status_code . ' - ' . $error_message);
12088 -
12089 - // Handle specific error types
12090 - switch ($status_code) {
12091 - case 401:
12092 - return [
12093 - 'error' => esc_html__('Authentication failed with DeepSeek. Please check your API key.', 'mxchat'),
12094 - 'error_code' => 'deepseek_auth_error',
12095 - 'provider' => 'deepseek'
12096 - ];
12097 -
12098 - case 400:
12099 - if (strpos($error_message, 'API key') !== false) {
12100 - return [
12101 - 'error' => esc_html__('Invalid DeepSeek API key. Please check your API key configuration.', 'mxchat'),
12102 - 'error_code' => 'deepseek_invalid_api_key',
12103 - 'provider' => 'deepseek'
12104 - ];
12105 - }
12106 - break;
12107 -
12108 - case 429:
12109 - if (strpos($error_message, 'quota') !== false) {
12110 - return [
12111 - 'error' => esc_html__('DeepSeek API quota exceeded. Please check your billing details.', 'mxchat'),
12112 - 'error_code' => 'deepseek_quota_exceeded',
12113 - 'provider' => 'deepseek'
12114 - ];
12115 - } else {
12116 - return [
12117 - 'error' => esc_html__('DeepSeek rate limit exceeded. Please try again later.', 'mxchat'),
12118 - 'error_code' => 'deepseek_rate_limit',
12119 - 'provider' => 'deepseek'
12120 - ];
12121 - }
12122 -
12123 - case 500:
12124 - case 502:
12125 - case 503:
12126 - case 504:
12127 - return [
12128 - 'error' => esc_html__('DeepSeek service is currently unavailable. Please try again later.', 'mxchat'),
12129 - 'error_code' => 'deepseek_service_unavailable',
12130 - 'provider' => 'deepseek'
12131 - ];
12132 - }
12133 -
12134 - // Generic error fallback — leak-safe helper (see plan 5da59a / 1d3b0f).
12135 - return [
12136 - 'error' => $this->mxchat_friendly_chat_error($status_code, $error_message, 'DeepSeek', $selected_model),
12137 - 'error_code' => 'deepseek_api_error',
12138 - 'provider' => 'deepseek',
12139 - 'status_code' => $status_code
12140 - ];
12141 - }
12142 -
12143 - $response_body = wp_remote_retrieve_body($response);
12144 - $decoded_response = json_decode($response_body, true);
12145 -
12146 - if (isset($decoded_response['choices'][0]['message']['content'])) {
12147 - $text = trim($decoded_response['choices'][0]['message']['content']);
12148 - if ($text !== '') {
12149 - return $text;
12150 - }
12151 - return $this->mxchat_empty_completion_error($decoded_response, 'DeepSeek');
12152 - } else {
12153 - //error_log('DeepSeek API Response Format Error: ' . print_r($decoded_response, true));
12154 - return [
12155 - 'error' => esc_html__('Unexpected response format from DeepSeek.', 'mxchat'),
12156 - 'error_code' => 'deepseek_response_format_error',
12157 - 'provider' => 'deepseek'
12158 - ];
12159 - }
12160 - } catch (Exception $e) {
12161 - //error_log('DeepSeek Exception: ' . $e->getMessage());
12162 - return [
12163 - 'error' => esc_html__('System error when processing DeepSeek request: ', 'mxchat') . esc_html($e->getMessage()),
12164 - 'error_code' => 'deepseek_exception',
12165 - 'provider' => 'deepseek'
12166 - ];
12167 - }
12168 -}
12169 -private function mxchat_generate_response_gemini($selected_model, $gemini_api_key, $conversation_history, $relevant_content, $session_id = '') {
12170 - // Read-time remap: gemini-3-pro-preview was shut down March 9, 2026.
12171 - // Auto-rescue existing installs whose saved model is the dead ID.
12172 - if ($selected_model === 'gemini-3-pro-preview') {
12173 - $selected_model = 'gemini-3.1-pro-preview';
12174 - }
12175 - // Get bot ID from session or request
12176 - $bot_id = $this->get_current_bot_id($session_id);
12177 -
12178 - // Get system prompt instructions using centralized function
12179 - $system_prompt_instructions = $this->get_system_instructions($bot_id, $session_id);
12180 -
12181 - // Add system prompt to relevant content
12182 - $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
12183 -
12184 - // Format messages for Gemini API
12185 - $formatted_messages = [];
12186 -
12187 - // Add system message as the first user message with role prefix
12188 - // Note: Gemini doesn't have a dedicated system role, so we use a prefixed user message
12189 - $formatted_messages[] = [
12190 - 'role' => 'user',
12191 - 'parts' => [
12192 - ['text' => "[System Instructions] " . $content_with_instructions]
12193 - ]
12194 - ];
12195 -
12196 - // Add model response to acknowledge system instructions
12197 - $formatted_messages[] = [
12198 - 'role' => 'model',
12199 - 'parts' => [
12200 - ['text' => "I understand and will follow these instructions."]
12201 - ]
12202 - ];
12203 -
12204 - // Process the rest of the conversation history
12205 - $current_role = null;
12206 - $current_parts = [];
12207 -
12208 - foreach ($conversation_history as $message) {
12209 - // Skip the first system message as we already handled it
12210 - if ($message['role'] === 'system') {
12211 - continue;
12212 - }
12213 -
12214 - // Map roles to Gemini format
12215 - $gemini_role = '';
12216 - if ($message['role'] === 'user') {
12217 - $gemini_role = 'user';
12218 - } else if (in_array($message['role'], ['assistant', 'bot', 'agent'])) {
12219 - $gemini_role = 'model';
12220 - } else {
12221 - // Skip unsupported roles
12222 - continue;
12223 - }
12224 -
12225 - // If we have a new role, add the previous message
12226 - if ($current_role !== null && $current_role !== $gemini_role && !empty($current_parts)) {
12227 - $formatted_messages[] = [
12228 - 'role' => $current_role,
12229 - 'parts' => $current_parts
12230 - ];
12231 - $current_parts = [];
12232 - }
12233 -
12234 - // Set current role and add text to parts
12235 - $current_role = $gemini_role;
12236 - $current_parts[] = ['text' => $message['content']];
12237 - }
12238 -
12239 - // Add the last message if there's content
12240 - if ($current_role !== null && !empty($current_parts)) {
12241 - $formatted_messages[] = [
12242 - 'role' => $current_role,
12243 - 'parts' => $current_parts
12244 - ];
12245 - }
12246 -
12247 - // Built-in Web Search grounding for Gemini (plan 46b9ea).
12248 - // The enable_web_search toggle historically routed ONLY to OpenAI's web_search
12249 - // tool; for a Gemini chat model it was a silent no-op. Gemini grounds natively
12250 - // (and free) via the Google Search tool, so when the toggle is on we attach it
12251 - // here on the PLAIN dispatch path. The function-calling loop (mxchat_fc_loop_gemini)
12252 - // is a SEPARATE path reached only when AI Tools are active, so grounding here
12253 - // never double-fires with function calling.
12254 - $web_search_enabled = isset($this->options['enable_web_search']) && $this->options['enable_web_search'] === 'on';
12255 - // Gemini ids that do NOT support Google Search grounding (none today — every
12256 - // shipped chat model is 2.x/3.x and grounds natively). Kept as the explicit
12257 - // opt-out list mirroring the OpenAI $unsupported_web_search_models pattern.
12258 - $gemini_unsupported_grounding = array();
12259 - $grounding_active = $web_search_enabled && !in_array($selected_model, $gemini_unsupported_grounding, true);
12260 -
12261 - // Build the request body
12262 - $request_payload = [
12263 - 'contents' => $formatted_messages,
12264 - 'generationConfig' => [
12265 - 'temperature' => 0.7,
12266 - 'topP' => 0.95,
12267 - 'topK' => 40,
12268 - 'maxOutputTokens' => 8192,
12269 - ],
12270 - 'safetySettings' => [
12271 - [
12272 - 'category' => 'HARM_CATEGORY_HARASSMENT',
12273 - 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
12274 - ],
12275 - [
12276 - 'category' => 'HARM_CATEGORY_HATE_SPEECH',
12277 - 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
12278 - ],
12279 - [
12280 - 'category' => 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
12281 - 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
12282 - ],
12283 - [
12284 - 'category' => 'HARM_CATEGORY_DANGEROUS_CONTENT',
12285 - 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
12286 - ]
12287 - ]
12288 - ];
12289 -
12290 - if ($grounding_active) {
12291 - // Gemini 1.5 used the older google_search_retrieval shape; 2.0+ uses the
12292 - // bare google_search tool. Branch by model family so a future 1.5 id still
12293 - // grounds (no 1.5 ships today, so this resolves to google_search). The empty
12294 - // tool config must serialize as a JSON object {}, not an array [].
12295 - if (strpos($selected_model, 'gemini-1.5') !== false) {
12296 - $request_payload['tools'] = [ ['google_search_retrieval' => new \stdClass()] ];
12297 - } else {
12298 - $request_payload['tools'] = [ ['google_search' => new \stdClass()] ];
12299 - }
12300 - }
12301 -
12302 - $body = json_encode($request_payload);
12303 -
12304 - // Prepare the API endpoint
12305 - // Use v1beta for preview models (Gemini 3, experimental), v1 for stable models.
12306 - // Grounding (the google_search tool) is a v1beta feature, so force v1beta whenever
12307 - // it's active — otherwise a stable model on v1 would silently drop the tool.
12308 - $api_version = ($grounding_active || strpos($selected_model, 'preview') !== false || strpos($selected_model, 'exp') !== false) ? 'v1beta' : 'v1';
12309 - $api_endpoint = 'https://generativelanguage.googleapis.com/' . $api_version . '/models/' . $selected_model . ':generateContent?key=' . $gemini_api_key;
12310 -
12311 - // Set up the API request
12312 - $args = [
12313 - 'body' => $body,
12314 - 'headers' => [
12315 - 'Content-Type' => 'application/json',
12316 - ],
12317 - 'timeout' => 60,
12318 - 'redirection' => 5,
12319 - 'blocking' => true,
12320 - 'httpversion' => '1.0',
12321 - 'sslverify' => true,
12322 - ];
12323 -
12324 - // Make the API request
12325 - $response = $this->mxchat_provider_call_with_retry($api_endpoint, $args, 'gemini');
12326 -
12327 - // Process the response
12328 - if (is_wp_error($response)) {
12329 - // plan b13282: route the transport-error string through the leak-safe helper
12330 - // (admin-actionable, generic for visitors) instead of echoing the raw WP HTTP
12331 - // error. http_code 0 = no HTTP response, so the helper uses the generic branch.
12332 - return $this->mxchat_friendly_chat_error(0, $response->get_error_message(), 'Gemini', $selected_model);
12333 - }
12334 -
12335 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
12336 -
12337 - // Handle potential errors in the response. Gemini surfaces errors as a
12338 - // 200/non-200 body with an `error` envelope; route the user-facing text
12339 - // through the leak-safe helper (admin-actionable, no visitor leak) rather
12340 - // than echoing the raw provider message. plan 5da59a.
12341 - if (isset($response_body['error'])) {
12342 - //error_log('Gemini API Error: ' . json_encode($response_body['error']));
12343 - $gemini_error_message = isset($response_body['error']['message'])
12344 - ? $response_body['error']['message']
12345 - : 'Unknown error';
12346 - $gemini_http_code = wp_remote_retrieve_response_code($response);
12347 - return $this->mxchat_friendly_chat_error($gemini_http_code, $gemini_error_message, 'Gemini', $selected_model);
12348 - }
12349 -
12350 - // Extract the response text
12351 - if (isset($response_body['candidates'][0]['content']['parts'][0]['text'])) {
12352 - $text = trim($response_body['candidates'][0]['content']['parts'][0]['text']);
12353 - if ($text !== '') {
12354 - return $text;
12355 - }
12356 - return $this->mxchat_empty_completion_error($response_body, 'Gemini');
12357 - } else {
12358 - //error_log('Unexpected Gemini API response format: ' . json_encode($response_body));
12359 - return "Sorry, I couldn't process that request. The response format was unexpected.";
12360 - }
12361 -}
12362 -
12363 -
12364 -public function test_streaming_request() {
12365 - $options = get_option('mxchat_options', []);
12366 - $model = $options['model'] ?? 'gpt-5.6-sol';
12367 -
12368 - // Detect provider from model prefix
12369 - $provider = strtolower(explode('-', $model)[0]);
12370 -
12371 - $sample_prompt = 'Hello! Can you stream this response back to me?';
12372 - $messages = [['role' => 'user', 'content' => $sample_prompt]];
12373 - $headers = [];
12374 - $body = [];
12375 - $url = '';
12376 - $api_key = '';
12377 -
12378 - switch ($provider) {
12379 - case 'gpt':
12380 - case 'o1':
12381 - $api_key = $options['api_key'] ?? '';
12382 - if (empty($api_key)) return '❌ Missing API key for OpenAI';
12383 - $url = 'https://api.openai.com/v1/chat/completions';
12384 - $headers = [
12385 - 'Content-Type: application/json',
12386 - 'Authorization: Bearer ' . $api_key
12387 - ];
12388 - $body = [
12389 - 'model' => $model,
12390 - 'messages' => $messages,
12391 - 'stream' => true
12392 - ];
12393 - break;
12394 -
12395 - case 'claude':
12396 - $api_key = $options['claude_api_key'] ?? '';
12397 - if (empty($api_key)) return '❌ Missing API key for Claude';
12398 - $url = 'https://api.anthropic.com/v1/messages';
12399 - $headers = [
12400 - 'Content-Type: application/json',
12401 - 'x-api-key: ' . $api_key,
12402 - 'anthropic-version: 2023-06-01'
12403 - ];
12404 - $body = [
12405 - 'model' => $model,
12406 - 'messages' => $messages,
12407 - 'max_tokens' => 100,
12408 - 'stream' => true
12409 - ];
12410 - break;
12411 -
12412 - case 'grok':
12413 - $api_key = $options['xai_api_key'] ?? '';
12414 - if (empty($api_key)) return '❌ Missing API key for X.AI';
12415 - $url = 'https://api.x.ai/v1/chat/completions';
12416 - $headers = [
12417 - 'Content-Type: application/json',
12418 - 'Authorization: Bearer ' . $api_key
12419 - ];
12420 - $body = [
12421 - 'model' => $model,
12422 - 'messages' => $messages,
12423 - 'stream' => true
12424 - ];
12425 - break;
12426 -
12427 - case 'deepseek':
12428 - if (empty($deepseek_api_key)) {
12429 - $error_response = [
12430 - 'error' => esc_html__('DeepSeek API key is not configured', 'mxchat'),
12431 - 'error_code' => 'missing_deepseek_api_key'
12432 - ];
12433 - if ($testing_data !== null) {
12434 - $error_response['testing_data'] = $testing_data;
12435 - }
12436 - return $error_response;
12437 - }
12438 - if ($streaming) {
12439 - return $this->mxchat_generate_response_deepseek_stream(
12440 - $selected_model,
12441 - $deepseek_api_key,
12442 - $conversation_history,
12443 - $relevant_content,
12444 - $session_id,
12445 - $testing_data // Pass testing data
12446 - );
12447 - } else {
12448 - $response = $this->mxchat_generate_response_deepseek(
12449 - $selected_model,
12450 - $deepseek_api_key,
12451 - $conversation_history,
12452 - $relevant_content,
12453 - $session_id
12454 - );
12455 - }
12456 - break;
12457 -
12458 - case 'gemini':
12459 - $api_key = $options['gemini_api_key'] ?? '';
12460 - if (empty($api_key)) return '❌ Missing API key for Gemini';
12461 - $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':streamGenerateContent?key=' . $api_key;
12462 - $headers = ['Content-Type: application/json'];
12463 - $body = [
12464 - 'contents' => [['role' => 'user', 'parts' => [['text' => $sample_prompt]]]],
12465 - 'generationConfig' => ['temperature' => 0.7]
12466 - ];
12467 - break;
12468 -
12469 - default:
12470 - return '❌ Unsupported provider: ' . $provider;
12471 - }
12472 -
12473 - // Do the actual streaming test
12474 - $ch = curl_init($url);
12475 - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
12476 - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
12477 - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
12478 - curl_setopt($ch, CURLOPT_TIMEOUT, 15);
12479 - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
12480 -
12481 - $response = curl_exec($ch);
12482 - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
12483 - $error = curl_error($ch);
12484 - curl_close($ch);
12485 -
12486 - if ($error) return "❌ cURL error: $error";
12487 - if ($http_code !== 200) {
12488 - $error_message = json_decode($response, true)['error']['message'] ?? 'Unknown';
12489 - return "❌ HTTP $http_code: $error_message";
12490 - }
12491 -
12492 - return true;
12493 -}
12494 -
12495 -public function mxchat_dismiss_pre_chat_message() {
12496 - // Get and sanitize the user identifier
12497 - $user_id = $this->mxchat_get_user_identifier();
12498 - $user_id = sanitize_key($user_id);
12499 -
12500 - // Set a transient to track that the user has dismissed the pre-chat message
12501 - $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
12502 - set_transient($transient_key, true, DAY_IN_SECONDS);
12503 -
12504 - wp_send_json_success();
12505 -}
12506 -
12507 -public function mxchat_check_pre_chat_message_status() {
12508 - // Get and sanitize the user identifier
12509 - $user_id = $this->mxchat_get_user_identifier();
12510 - $user_id = sanitize_key($user_id);
12511 -
12512 - // Check if the transient exists (i.e., if the message was dismissed)
12513 - $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
12514 - $dismissed = get_transient($transient_key);
12515 -
12516 - // Log the result to see if it's being set correctly
12517 - //error_log("Check pre-chat message dismissed for $user_id: " . ($dismissed ? 'Yes' : 'No'));
12518 -
12519 - if ($dismissed) {
12520 - wp_send_json_success(['dismissed' => true]);
12521 - } else {
12522 - wp_send_json_success(['dismissed' => false]);
12523 - }
12524 -
12525 - wp_die();
12526 -}
12527 -
12528 -/**
12529 - * Keyword leg for hybrid retrieval (plan-38ffa1): ranked keyword query over
12530 - * the WP-DB knowledge table. FULLTEXT when the index is available, LIKE on
12531 - * the top query terms otherwise (capability detected once and cached by
12532 - * MxChat_Utils::mxchat_hybrid_detect_capability). Respects the same bot
12533 - * scoping as the vector query ($bot_filter) and the same role-restriction
12534 - * access rules as vector candidates.
12535 - *
12536 - * @return array[] Ranked hits: [id, source_url, role_restriction, has_access]
12537 - */
12538 -private function mxchat_hybrid_keyword_search($user_query, $system_prompt_table, $bot_filter, $knowledge_manager) {
12539 - global $wpdb;
12540 -
12541 - $capability = get_option('mxchat_hybrid_keyword_capability', '');
12542 - if (!in_array($capability, array('fulltext', 'like'), true)) {
12543 - $capability = MxChat_Utils::mxchat_hybrid_detect_capability();
12544 - }
12545 -
12546 - $limit = 20;
12547 - $rows = array();
12548 -
12549 - if ($capability === 'fulltext') {
12550 - $rows = $wpdb->get_results($wpdb->prepare(
12551 - "SELECT id, source_url, role_restriction,
12552 - MATCH(article_content) AGAINST (%s IN NATURAL LANGUAGE MODE) AS kw_score
12553 - FROM {$system_prompt_table}
12554 - WHERE MATCH(article_content) AGAINST (%s IN NATURAL LANGUAGE MODE) {$bot_filter}
12555 - ORDER BY kw_score DESC, id ASC
12556 - LIMIT %d",
12557 - $user_query,
12558 - $user_query,
12559 - $limit
12560 - ));
12561 - } else {
12562 - // LIKE fallback: length-weighted term scoring. Longer, rarer tokens
12563 - // (the SKU, the error code) must outrank ubiquitous short words — an
12564 - // equal-weight score lets "the" + one common word tie with the exact
12565 - // token and the tie-break pick the wrong row (caught by the 38ffa1
12566 - // verification harness). Stopwords are dropped outright.
12567 - $stopwords = array('the', 'and', 'for', 'you', 'your', 'with', 'this', 'that', 'are', 'was', 'can', 'how', 'what', 'does', 'have', 'has', 'about', 'from', 'not', 'but', 'all', 'any', 'our', 'their');
12568 - $terms = preg_split('/[^\p{L}\p{N}_-]+/u', (string) $user_query, -1, PREG_SPLIT_NO_EMPTY);
12569 - $terms = array_filter($terms, function ($t) use ($stopwords) {
12570 - return mb_strlen($t) >= 3 && !in_array(mb_strtolower($t), $stopwords, true);
12571 - });
12572 - $terms = array_values(array_unique(array_map('mb_strtolower', $terms)));
12573 - usort($terms, function ($a, $b) {
12574 - return mb_strlen($b) <=> mb_strlen($a);
12575 - });
12576 - $terms = array_slice($terms, 0, 5);
12577 - if (empty($terms)) {
12578 - return array();
12579 - }
12580 -
12581 - $score_parts = array();
12582 - $where_parts = array();
12583 - $like_params = array();
12584 - foreach ($terms as $term) {
12585 - $score_parts[] = '((article_content LIKE %s) * ' . (int) mb_strlen($term) . ')';
12586 - $where_parts[] = 'article_content LIKE %s';
12587 - $like_params[] = '%' . $wpdb->esc_like($term) . '%';
12588 - }
12589 - $sql = "SELECT id, source_url, role_restriction, ("
12590 - . implode(' + ', $score_parts)
12591 - . ") AS kw_score FROM {$system_prompt_table} WHERE ("
12592 - . implode(' OR ', $where_parts)
12593 - . ") {$bot_filter} ORDER BY kw_score DESC, id ASC LIMIT %d";
12594 - $rows = $wpdb->get_results($wpdb->prepare(
12595 - $sql,
12596 - array_merge($like_params, $like_params, array($limit))
12597 - ));
12598 - }
12599 -
12600 - $hits = array();
12601 - foreach ((array) $rows as $row) {
12602 - $role_restriction = $row->role_restriction ?? 'public';
12603 - if (!$knowledge_manager->mxchat_user_has_content_access($role_restriction)) {
12604 - continue;
12605 - }
12606 - $hits[] = array(
12607 - 'id' => (int) $row->id,
12608 - 'source_url' => $row->source_url ?? '',
12609 - 'role_restriction' => $role_restriction,
12610 - 'has_access' => true,
12611 - );
12612 - }
12613 - return $hits;
12614 -}
12615 -
12616 -private function mxchat_calculate_cosine_similarity($vectorA, $vectorB) {
12617 - if (!is_array($vectorA) || !is_array($vectorB) || empty($vectorA) || empty($vectorB)) {
12618 - return 0;
12619 - }
12620 -
12621 - $dotProduct = array_sum(array_map(function ($a, $b) {
12622 - return $a * $b;
12623 - }, $vectorA, $vectorB));
12624 - $normA = sqrt(array_sum(array_map(function ($a) {
12625 - return $a * $a;
12626 - }, $vectorA)));
12627 - $normB = sqrt(array_sum(array_map(function ($b) {
12628 - return $b * $b;
12629 - }, $vectorB)));
12630 -
12631 - if ($normA == 0 || $normB == 0) {
12632 - return 0;
12633 - }
12634 -
12635 - return $dotProduct / ($normA * $normB);
12636 - }
12637 -
12638 -
12639 -public function mxchat_enqueue_scripts_styles($force = false) {
12640 - // Idempotency guard (plan-915355): the smart-asset-loading safety net in
12641 - // render_chatbot_shortcode() may invoke this method a second time (or on
12642 - // every shortcode render). Run the body at most once per request so the
12643 - // nonce, dynamic-settings merge, delayed transient write, and wp_footer
12644 - // loader action never happen twice.
12645 - static $did_run = false;
12646 - if ($did_run) {
12647 - return;
12648 - }
12649 -
12650 - // Smart asset loading gate (plan-915355, opt-in, default OFF — toggle in
12651 - // MxChat → Settings → Optimization → Script Loading). When enabled and the
12652 - // shared display decision says the widget won't render on this request,
12653 - // skip all front-end assets. $force (the shortcode safety net) bypasses
12654 - // the gate because at that point the widget IS rendering. Note: bail
12655 - // WITHOUT setting $did_run, so a later forced call can still enqueue.
12656 - if (!$force
12657 - && class_exists('MxChat_Public')
12658 - && MxChat_Public::is_smart_asset_loading_enabled()
12659 - && !MxChat_Public::should_load_assets()) {
12660 - return;
12661 - }
12662 -
12663 - $did_run = true;
12664 -
12665 - // Fetch options from the database first to check loading strategy
12666 - $this->options = get_option('mxchat_options');
12667 - $loading_strategy = isset($this->options['script_loading_strategy']) ? $this->options['script_loading_strategy'] : 'default';
12668 -
12669 - // Always enqueue CSS immediately
12670 - wp_enqueue_style(
12671 - 'mxchat-chat-css',
12672 - plugin_dir_url(__FILE__) . '../css/chat-style.css',
12673 - array(),
12674 - MXCHAT_VERSION
12675 - );
12676 -
12677 - // Handle script loading based on strategy
12678 - if ($loading_strategy === 'default' || $loading_strategy === 'defer') {
12679 - // Enqueue the script normally
12680 - wp_enqueue_script(
12681 - 'mxchat-chat-js',
12682 - plugin_dir_url(__FILE__) . '../js/chat-script.js',
12683 - array('jquery'),
12684 - MXCHAT_VERSION,
12685 - true
12686 - );
12687 -
12688 - // Add defer attribute if strategy is 'defer'
12689 - if ($loading_strategy === 'defer') {
12690 - wp_script_add_data('mxchat-chat-js', 'strategy', 'defer');
12691 - }
12692 - } else {
12693 - // For delay or interaction-based loading, we'll use a custom loader
12694 - // Don't enqueue the main script - we'll load it dynamically
12695 - add_action('wp_footer', array($this, 'mxchat_output_delayed_script_loader'), 99);
12696 - }
12697 -
12698 - $prompts_options = get_option('mxchat_prompts_options', array());
12699 -
12700 - // Check if AI theme is active - if so, skip inline colors in JavaScript
12701 - $theme_options = get_option('mxchat_theme_options', array());
12702 - $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
12703 - $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']);
12704 - $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments;
12705 -
12706 - // Prepare settings for JavaScript
12707 - $style_settings = array(
12708 - 'ajax_url' => admin_url('admin-ajax.php'),
12709 - // The chat-send nonce is now fetched per-request from /wp-json/mxchat/v1/nonce
12710 - // (plan-6a68c9) so it never sits in cached HTML. We still emit a nonce here
12711 - // as a one-shot fallback for the first interaction on a fresh page load
12712 - // (so the very first chat-send doesn't need to wait for a REST round-trip),
12713 - // but the widget refetches before each subsequent send.
12714 - 'nonce' => wp_create_nonce('mxchat_chat_send'),
12715 - 'rest_url' => esc_url_raw(trailingslashit(rest_url('mxchat/v1'))),
12716 - 'contextual_awareness_toggle' => isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off',
12717 - 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
12718 - 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
12719 - 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
12720 - 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
12721 - 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
12722 - 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
12723 - 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
12724 - 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
12725 - 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
12726 - 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
12727 - 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
12728 - 'icon_color' => $this->options['icon_color'] ?? '#fff',
12729 - 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
12730 - 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
12731 - 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off',
12732 - 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
12733 - 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
12734 - 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
12735 - 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
12736 - 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
12737 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
12738 - 'email_collection_enabled' => $this->options['enable_email_block'] ?? 'off', // FIXED
12739 - 'initial_email_state' => null, // Also fixed this undefined variable
12740 - 'skip_email_check' => true,
12741 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1',
12742 - 'skip_inline_colors' => $skip_inline_colors,
12743 - 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array(),
12744 - );
12745 -
12746 - // Behavior gates + labels (model, streaming, rate-limit copy, toolbar,
12747 - // print/transcript, satisfaction rating) come from the shared
12748 - // dynamic-settings method so this inline payload and the first-open
12749 - // refresh endpoint can never drift (plan-32db95).
12750 - $style_settings = array_merge($style_settings, $this->get_dynamic_widget_settings());
12751 -
12752 - // For normal/defer loading, use wp_localize_script.
12753 - // For delayed loading, nothing is localized or stored here: the delayed
12754 - // loader (mxchat_output_delayed_script_loader) rebuilds the full settings
12755 - // array inline from options and never reads any stored copy.
12756 - if ($loading_strategy === 'default' || $loading_strategy === 'defer') {
12757 - wp_localize_script('mxchat-chat-js', 'mxchatChat', $style_settings);
12758 - } else {
12759 - // Late-render fallback (plan-915355): when the shortcode safety net
12760 - // forces this method during/after wp_footer (footer widget areas, late
12761 - // builder regions), the wp_footer:99 loader action registered above may
12762 - // already be past its slot. Emit the loader inline right now; its
12763 - // emitted-once guard prevents double output if :99 still fires.
12764 - if ($force && did_action('wp_footer')) {
12765 - $this->mxchat_output_delayed_script_loader();
12766 - }
12767 - }
12768 -}
12769 -
12770 -/**
12771 - * Output the delayed script loader for performance optimization
12772 - */
12773 -public function mxchat_output_delayed_script_loader() {
12774 - // Emitted-once guard (plan-915355): this can now be reached both via the
12775 - // wp_footer:99 action and via the late-render inline fallback in
12776 - // mxchat_enqueue_scripts_styles(). The loader must print exactly once.
12777 - static $emitted = false;
12778 - if ($emitted) {
12779 - return;
12780 - }
12781 - $emitted = true;
12782 -
12783 - $this->options = get_option('mxchat_options');
12784 - $loading_strategy = isset($this->options['script_loading_strategy']) ? $this->options['script_loading_strategy'] : 'default';
12785 - $script_url = plugin_dir_url(__FILE__) . '../js/chat-script.js?ver=' . MXCHAT_VERSION;
12786 -
12787 - // Get the stored settings
12788 - $prompts_options = get_option('mxchat_prompts_options', array());
12789 - $theme_options = get_option('mxchat_theme_options', array());
12790 - $ai_theme_active = !empty($theme_options['active_ai_theme_css']);
12791 - $has_bot_theme_assignments = !empty($theme_options['bot_theme_assignments']);
12792 - $skip_inline_colors = $ai_theme_active || $has_bot_theme_assignments;
12793 -
12794 - $style_settings = array(
12795 - 'ajax_url' => admin_url('admin-ajax.php'),
12796 - // Per-request nonce — see plan-6a68c9; widget fetches via /wp-json/mxchat/v1/nonce
12797 - // before each send. This inline value is a one-shot fallback for the first interaction.
12798 - 'nonce' => wp_create_nonce('mxchat_chat_send'),
12799 - 'rest_url' => esc_url_raw(trailingslashit(rest_url('mxchat/v1'))),
12800 - 'contextual_awareness_toggle' => isset($this->options['contextual_awareness_toggle']) ? $this->options['contextual_awareness_toggle'] : 'off',
12801 - 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
12802 - 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
12803 - 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
12804 - 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
12805 - 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
12806 - 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
12807 - 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
12808 - 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
12809 - 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
12810 - 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
12811 - 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
12812 - 'icon_color' => $this->options['icon_color'] ?? '#fff',
12813 - 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
12814 - 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
12815 - 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off',
12816 - 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
12817 - 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
12818 - 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
12819 - 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
12820 - 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
12821 - 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
12822 - 'email_collection_enabled' => $this->options['enable_email_block'] ?? 'off',
12823 - 'initial_email_state' => null,
12824 - 'skip_email_check' => true,
12825 - 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1',
12826 - 'skip_inline_colors' => $skip_inline_colors,
12827 - 'bot_theme_assignments' => $theme_options['bot_theme_assignments'] ?? array(),
12828 - );
12829 -
12830 - // Behavior gates + labels (model, streaming, rate-limit copy, toolbar,
12831 - // print/transcript, satisfaction rating) come from the shared
12832 - // dynamic-settings method so this inline payload and the first-open
12833 - // refresh endpoint can never drift (plan-32db95).
12834 - $style_settings = array_merge($style_settings, $this->get_dynamic_widget_settings());
12835 -
12836 - // Determine delay time based on strategy
12837 - $delay_ms = 0;
12838 - switch ($loading_strategy) {
12839 - case 'delay_1s':
12840 - $delay_ms = 1000;
12841 - break;
12842 - case 'delay_3s':
12843 - $delay_ms = 3000;
12844 - break;
12845 - case 'delay_5s':
12846 - $delay_ms = 5000;
12847 - break;
12848 - }
12849 -
12850 - ?>
12851 - <script type="text/javascript">
12852 - (function() {
12853 - var mxchatLoaded = false;
12854 - var mxchatChat = <?php echo wp_json_encode($style_settings); ?>;
12855 - window.mxchatChat = mxchatChat;
12856 -
12857 - function loadMxChatScript() {
12858 - if (mxchatLoaded) return;
12859 - mxchatLoaded = true;
12860 -
12861 - function appendChatScript() {
12862 - var script = document.createElement('script');
12863 - script.src = <?php echo wp_json_encode($script_url); ?>;
12864 - script.type = 'text/javascript';
12865 - document.body.appendChild(script);
12866 - }
12867 -
12868 - if (typeof jQuery !== 'undefined') {
12869 - appendChatScript();
12870 - } else {
12871 - var jq = document.createElement('script');
12872 - jq.src = <?php echo wp_json_encode(includes_url('js/jquery/jquery.min.js')); ?>;
12873 - jq.onload = appendChatScript;
12874 - document.body.appendChild(jq);
12875 - }
12876 - }
12877 -
12878 - <?php if ($loading_strategy === 'on_interaction'): ?>
12879 - // Load on user interaction
12880 - var events = ['scroll', 'mousemove', 'touchstart', 'keydown', 'click'];
12881 - events.forEach(function(evt) {
12882 - window.addEventListener(evt, loadMxChatScript, {once: true, passive: true});
12883 - });
12884 - // Fallback: load after 8 seconds if no interaction
12885 - setTimeout(loadMxChatScript, 8000);
12886 - <?php else: ?>
12887 - // Load after specified delay
12888 - setTimeout(loadMxChatScript, <?php echo intval($delay_ms); ?>);
12889 - <?php endif; ?>
12890 - })();
12891 - </script>
12892 - <?php
12893 -}
12894 -
12895 -/**
12896 - * Setup the cron jobs for rate limits with guard against multiple calls
12897 - */
12898 -public function setup_rate_limit_cron_jobs() {
12899 - // Add a guard to prevent multiple rapid calls
12900 - $last_setup = get_transient('mxchat_cron_setup_guard');
12901 - if ($last_setup && (time() - $last_setup) < 60) {
12902 - // Don't run again if we ran less than 60 seconds ago
12903 - return;
12904 - }
12905 -
12906 - // Set the guard
12907 - set_transient('mxchat_cron_setup_guard', time(), 300); // 5 minutes
12908 -
12909 - try {
12910 - // First, check if WordPress cron is disabled
12911 - if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
12912 - //error_log('MxChat: WordPress cron is disabled (DISABLE_WP_CRON = true), using fallback system');
12913 - $this->setup_fallback_rate_limit_system();
12914 - return;
12915 - }
12916 -
12917 - // Check if cron is already scheduled - if so, don't mess with it
12918 - if (wp_next_scheduled('mxchat_reset_rate_limits')) {
12919 - //error_log('MxChat: Rate limit cron already scheduled, skipping setup');
12920 - return;
12921 - }
12922 -
12923 - // Clear any orphaned hooks (but don't loop indefinitely)
12924 - $hooks_to_clear = [
12925 - 'mxchat_reset_rate_limits',
12926 - 'mxchat_reset_hourly_rate_limits',
12927 - 'mxchat_reset_daily_rate_limits',
12928 - 'mxchat_reset_weekly_rate_limits',
12929 - 'mxchat_reset_monthly_rate_limits'
12930 - ];
12931 -
12932 - foreach ($hooks_to_clear as $hook) {
12933 - // Only clear a maximum of 3 instances to prevent infinite loops
12934 - $cleared = 0;
12935 - while (wp_next_scheduled($hook) && $cleared < 3) {
12936 - wp_clear_scheduled_hook($hook);
12937 - $cleared++;
12938 - }
12939 - }
12940 -
12941 - // Small delay after clearing
12942 - usleep(100000); // 0.1 seconds
12943 -
12944 - // Try to schedule the event
12945 - $initial_time = time() + 300; // Start in 5 minutes
12946 - $result = wp_schedule_event($initial_time, 'hourly', 'mxchat_reset_rate_limits');
12947 -
12948 - if ($result === false) {
12949 - //error_log('MxChat: Failed to schedule cron, using fallback system');
12950 - $this->setup_fallback_rate_limit_system();
12951 - } else {
12952 - if (defined('MXCHAT_DEV_MODE') && MXCHAT_DEV_MODE) {
12953 - error_log('MxChat: rate-limit reset cron event was missing and has been re-scheduled');
12954 - }
12955 - }
12956 -
12957 - } catch (Exception $e) {
12958 - //error_log('MxChat: Cron setup exception: ' . $e->getMessage());
12959 - $this->setup_fallback_rate_limit_system();
12960 - }
12961 -}
12962 -
12963 -/**
12964 - * Try alternative cron scheduling methods
12965 - */
12966 -private function try_alternative_cron_scheduling($initial_time) {
12967 - try {
12968 - // Method 1: Try with current time instead of future time
12969 - $result1 = wp_schedule_event(time(), 'hourly', 'mxchat_reset_rate_limits');
12970 - if ($result1 !== false) {
12971 - //error_log('MxChat: Alternative method 1 (current time) succeeded');
12972 - return true;
12973 - }
12974 -
12975 - // Method 2: Try with a different interval
12976 - $result2 = wp_schedule_event($initial_time, 'daily', 'mxchat_reset_rate_limits');
12977 - if ($result2 !== false) {
12978 - //error_log('MxChat: Alternative method 2 (daily interval) succeeded');
12979 - return true;
12980 - }
12981 -
12982 - // Method 3: Try wp_schedule_single_event first, then recurring
12983 - $result3 = wp_schedule_single_event($initial_time, 'mxchat_reset_rate_limits');
12984 - if ($result3 !== false) {
12985 - //error_log('MxChat: Alternative method 3 (single event) succeeded');
12986 - // Schedule the next one manually in the handler
12987 - return true;
12988 - }
12989 -
12990 - return false;
12991 -
12992 - } catch (Exception $e) {
12993 - //error_log('MxChat: Alternative cron scheduling exception: ' . $e->getMessage());
12994 - return false;
12995 - }
12996 -}
12997 -
12998 -/**
12999 - * Enhanced fallback rate limit system
13000 - */
13001 -private function setup_fallback_rate_limit_system() {
13002 - // Idempotence matters here: with setup_rate_limit_cron_jobs() hooked to
13003 - // admin_init, a DISABLE_WP_CRON site reaches this on every guard pass.
13004 - // Unconditionally rewriting mxchat_next_rate_limit_check to now+3600 would
13005 - // slide the deadline forward forever and the fallback reset would never
13006 - // fire. Only initialize the deadline on a genuine transition into fallback
13007 - // mode (or if it's somehow missing).
13008 - $already_active = get_option('mxchat_use_fallback_rate_limits', false);
13009 -
13010 - // Set a flag to use database-based rate limit cleanup
13011 - update_option('mxchat_use_fallback_rate_limits', true);
13012 -
13013 - // Schedule a one-time check to happen on the next plugin load
13014 - if (!$already_active || !get_option('mxchat_next_rate_limit_check', 0)) {
13015 - update_option('mxchat_next_rate_limit_check', time() + 3600);
13016 - }
13017 -
13018 - // Also set up a more frequent fallback check (every 4 hours)
13019 - update_option('mxchat_fallback_check_interval', 4 * 3600);
13020 -
13021 - //error_log('MxChat: Fallback rate limit system activated');
13022 -}
13023 -
13024 -/**
13025 - * Enhanced fallback check method
13026 - * NOTE: mxchat_check_fallback_rate_limits() in mxchat-basic.php is a second
13027 - * implementation of this same check — if either changes, change both.
13028 - */
13029 -public function check_fallback_rate_limits() {
13030 - $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
13031 -
13032 - if (!$use_fallback) {
13033 - return; // Regular cron is working
13034 - }
13035 -
13036 - $next_check = get_option('mxchat_next_rate_limit_check', 0);
13037 - $check_interval = get_option('mxchat_fallback_check_interval', 3600);
13038 -
13039 - if (time() >= $next_check) {
13040 - //error_log('MxChat: Running fallback rate limit cleanup');
13041 - $this->mxchat_reset_rate_limits();
13042 -
13043 - // Schedule next check
13044 - update_option('mxchat_next_rate_limit_check', time() + $check_interval);
13045 - }
13046 -}
13047 -/**
13048 - * Enhanced rate limit check that includes fallback cleanup and bot-specific rate limits
13049 - */
13050 -public function check_rate_limit() {
13051 - // Check if we need to run fallback cleanup
13052 - $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
13053 - $next_check = get_option('mxchat_next_rate_limit_check', 0);
13054 -
13055 - if ($use_fallback && time() >= $next_check) {
13056 - $this->mxchat_reset_rate_limits();
13057 - update_option('mxchat_next_rate_limit_check', time() + 3600); // Next hour
13058 - }
13059 -
13060 - // Get bot ID from current request context
13061 - $bot_id = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
13062 -
13063 - // Get bot-specific options (includes rate limits if overridden)
13064 - $bot_options = $this->get_bot_options($bot_id);
13065 - $current_options = !empty($bot_options) ? $bot_options : $this->options;
13066 -
13067 - // Use bot-specific rate limits if available, otherwise fall back to default
13068 - $rate_limits_source = isset($current_options['rate_limits']) ? $current_options['rate_limits'] : get_option('mxchat_options', [])['rate_limits'] ?? [];
13069 -
13070 - // -------------------------------------------------------------------
13071 - // Whole-chatbot global cap (independent of role). Evaluated FIRST so
13072 - // it acts as a hard ceiling across all users + all roles. Default is
13073 - // 'unlimited' so existing installs are unchanged. Counter key drops
13074 - // both <role> and <user_id> segments — single pool per bot.
13075 - // -------------------------------------------------------------------
13076 - $global_cfg = isset($current_options['rate_limits_global']) && is_array($current_options['rate_limits_global'])
13077 - ? $current_options['rate_limits_global']
13078 - : (isset(get_option('mxchat_options', [])['rate_limits_global']) ? get_option('mxchat_options', [])['rate_limits_global'] : []);
13079 - $global_limit_raw = isset($global_cfg['limit']) ? (string) $global_cfg['limit'] : 'unlimited';
13080 - $global_timeframe = isset($global_cfg['timeframe']) ? (string) $global_cfg['timeframe'] : 'daily';
13081 - if ($global_limit_raw !== '' && $global_limit_raw !== 'unlimited' && (int) $global_limit_raw >= 1) {
13082 - $bot_id_for_global = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
13083 - $safe_bot_global = preg_replace('/[^a-zA-Z0-9_]/', '_', $bot_id_for_global);
13084 - $global_option = 'mxchat_chat_limit_' . $safe_bot_global . '_global';
13085 - $global_data = get_option($global_option, ['count' => 0, 'timestamp' => time()]);
13086 - if ((int) $global_data['count'] === 0) {
13087 - $global_data['timestamp'] = time();
13088 - update_option($global_option, $global_data);
13089 - }
13090 - $now = time();
13091 - $ts = (int) $global_data['timestamp'];
13092 - $reset = false;
13093 - switch ($global_timeframe) {
13094 - case 'hourly': $reset = ($now - $ts) >= 3600; break;
13095 - case 'daily': $reset = ($now - $ts) >= 86400; break;
13096 - case 'weekly': $reset = ($now - $ts) >= 604800; break;
13097 - case 'monthly': $reset = ($now - $ts) >= 2592000; break;
13098 - }
13099 - if ($reset) {
13100 - $global_data = ['count' => 0, 'timestamp' => $now];
13101 - update_option($global_option, $global_data);
13102 - }
13103 - if ((int) $global_data['count'] >= (int) $global_limit_raw) {
13104 - $global_msg = !empty($global_cfg['message'])
13105 - ? $global_cfg['message']
13106 - : __('This chatbot has reached its message limit. Please try again later.', 'mxchat');
13107 - return [
13108 - 'error' => true,
13109 - 'message' => $this->process_rate_limit_message_html($global_msg),
13110 - ];
13111 - }
13112 - // Reserve the slot for this request. Per-role check below also increments
13113 - // its own counter — that is intentional, both ceilings apply independently.
13114 - $global_data['count']++;
13115 - update_option($global_option, $global_data);
13116 - }
13117 -
13118 - // Determine user role or if logged out
13119 - if (is_user_logged_in()) {
13120 - $user = wp_get_current_user();
13121 - $user_id = $user->ID;
13122 -
13123 - // Get the user's primary role using reset() to safely get the first element
13124 - $user_roles = $user->roles;
13125 -
13126 - // Safely get the first role regardless of array key structure
13127 - if (!empty($user_roles) && is_array($user_roles)) {
13128 - $role = reset($user_roles); // This safely gets the first element regardless of key
13129 - } else {
13130 - $role = 'subscriber'; // Default to subscriber if no role found
13131 - }
13132 - } else {
13133 - $role = 'logged_out';
13134 - // Use IP address for non-logged-in users
13135 - $user_id = $this->get_client_ip();
13136 - }
13137 -
13138 - // Check if rate limits are configured for this role
13139 - if (!isset($rate_limits_source[$role])) {
13140 - return true; // No limit set for this role
13141 - }
13142 -
13143 - $limit = $rate_limits_source[$role]['limit'];
13144 -
13145 - // If unlimited, return true immediately
13146 - if ($limit === 'unlimited') {
13147 - return true;
13148 - }
13149 -
13150 - // Get the option name for this user/role with safer naming (include bot_id for bot-specific limits)
13151 - $safe_role = preg_replace('/[^a-zA-Z0-9_]/', '_', $role);
13152 - $safe_user_id = preg_replace('/[^a-zA-Z0-9_]/', '_', $user_id);
13153 - $safe_bot_id = preg_replace('/[^a-zA-Z0-9_]/', '_', $bot_id);
13154 -
13155 - // Include bot_id in option name so each bot has separate rate limits
13156 - $option_name = 'mxchat_chat_limit_' . $safe_bot_id . '_' . $safe_role . '_' . $safe_user_id;
13157 -
13158 - // Get the counter data
13159 - $limit_data = get_option($option_name, ['count' => 0, 'timestamp' => time()]);
13160 -
13161 - // If first request or counter reset needed, set the initial timestamp
13162 - if ($limit_data['count'] === 0) {
13163 - $limit_data['timestamp'] = time();
13164 - update_option($option_name, $limit_data);
13165 - }
13166 -
13167 - // Get the timeframe
13168 - $timeframe = isset($rate_limits_source[$role]['timeframe']) ?
13169 - $rate_limits_source[$role]['timeframe'] : 'daily';
13170 -
13171 - // Check if the counter needs to be reset based on timeframe
13172 - $current_time = time();
13173 - $timestamp = $limit_data['timestamp'];
13174 - $should_reset = false;
13175 -
13176 - switch ($timeframe) {
13177 - case 'hourly':
13178 - $should_reset = ($current_time - $timestamp) >= 3600; // 1 hour
13179 - break;
13180 - case 'daily':
13181 - $should_reset = ($current_time - $timestamp) >= 86400; // 24 hours
13182 - break;
13183 - case 'weekly':
13184 - $should_reset = ($current_time - $timestamp) >= 604800; // 7 days
13185 - break;
13186 - case 'monthly':
13187 - $should_reset = ($current_time - $timestamp) >= 2592000; // 30 days
13188 - break;
13189 - }
13190 -
13191 - // Reset the counter if the timeframe has passed
13192 - if ($should_reset) {
13193 - $limit_data = ['count' => 0, 'timestamp' => $current_time];
13194 - update_option($option_name, $limit_data);
13195 - }
13196 -
13197 - // Check if user has exceeded their limit
13198 - if ($limit_data['count'] >= intval($limit)) {
13199 - // Get the custom message for this role
13200 - $message = !empty($rate_limits_source[$role]['message'])
13201 - ? $rate_limits_source[$role]['message']
13202 - : __('Rate limit exceeded. Please try again later.', 'mxchat');
13203 -
13204 - // Add timeframe information to the message if placeholders exist
13205 - $timeframe_label = '';
13206 - switch ($timeframe) {
13207 - case 'hourly':
13208 - $timeframe_label = __('hour', 'mxchat');
13209 - break;
13210 - case 'daily':
13211 - $timeframe_label = __('day', 'mxchat');
13212 - break;
13213 - case 'weekly':
13214 - $timeframe_label = __('week', 'mxchat');
13215 - break;
13216 - case 'monthly':
13217 - $timeframe_label = __('month', 'mxchat');
13218 - break;
13219 - }
13220 -
13221 - // Replace placeholders in the message
13222 - $message = str_replace(
13223 - ['{limit}', '{count}', '{remaining}', '{timeframe}'],
13224 - [intval($limit), $limit_data['count'], max(0, intval($limit) - $limit_data['count']), $timeframe_label],
13225 - $message
13226 - );
13227 -
13228 - // Process HTML links in the message
13229 - $message = $this->process_rate_limit_message_html($message);
13230 -
13231 - // Return error with the processed message
13232 - return [
13233 - 'error' => true,
13234 - 'message' => $message
13235 - ];
13236 - }
13237 -
13238 - // Increment the counter
13239 - $limit_data['count']++;
13240 - update_option($option_name, $limit_data);
13241 -
13242 - return true;
13243 -}
13244 -
13245 -/**
13246 - * Enhanced rate limit reset with better error handling
13247 - */
13248 -public function mxchat_reset_rate_limits() {
13249 - try {
13250 - global $wpdb;
13251 - $all_options = get_option('mxchat_options', []);
13252 - $current_time = time();
13253 -
13254 - // Get rate limit options with a safer query and limit
13255 - $option_names = $wpdb->get_col(
13256 - $wpdb->prepare(
13257 - "SELECT option_name FROM {$wpdb->options}
13258 - WHERE option_name LIKE %s
13259 - LIMIT 1000",
13260 - 'mxchat_chat_limit_%'
13261 - )
13262 - );
13263 -
13264 - if (empty($option_names)) {
13265 - return;
13266 - }
13267 -
13268 - $processed_count = 0;
13269 - $max_processing_time = 30; // Maximum 30 seconds
13270 - $start_time = time();
13271 -
13272 - foreach ($option_names as $option_name) {
13273 - // Check processing time limit
13274 - if ((time() - $start_time) > $max_processing_time) {
13275 - //error_log('MxChat: Rate limit reset timeout after processing ' . $processed_count . ' entries');
13276 - break;
13277 - }
13278 -
13279 - // Parse the option name more safely
13280 - if (!preg_match('/^mxchat_chat_limit_(.+)_(.+)$/', $option_name, $matches)) {
13281 - continue;
13282 - }
13283 -
13284 - $role_and_user = $matches[1] . '_' . $matches[2];
13285 - $parts = explode('_', $role_and_user);
13286 -
13287 - if (count($parts) < 2) {
13288 - continue;
13289 - }
13290 -
13291 - // Extract role (everything except the last part which is user ID)
13292 - $user_id_part = array_pop($parts);
13293 - $role = implode('_', $parts);
13294 -
13295 - // Skip if role doesn't exist in our settings
13296 - if (!isset($all_options['rate_limits'][$role])) {
13297 - // Clean up orphaned entries
13298 - delete_option($option_name);
13299 - continue;
13300 - }
13301 -
13302 - $timeframe = $all_options['rate_limits'][$role]['timeframe'] ?? 'daily';
13303 - $limit_data = get_option($option_name);
13304 -
13305 - if (!$limit_data || !is_array($limit_data) || !isset($limit_data['timestamp'])) {
13306 - // Clean up invalid entries
13307 - delete_option($option_name);
13308 - continue;
13309 - }
13310 -
13311 - $timestamp = $limit_data['timestamp'];
13312 - $should_reset = false;
13313 -
13314 - // Determine if we should reset based on the timeframe
13315 - switch ($timeframe) {
13316 - case 'hourly':
13317 - $should_reset = ($current_time - $timestamp) >= 3600;
13318 - break;
13319 - case 'daily':
13320 - $should_reset = ($current_time - $timestamp) >= 86400;
13321 - break;
13322 - case 'weekly':
13323 - $should_reset = ($current_time - $timestamp) >= 604800;
13324 - break;
13325 - case 'monthly':
13326 - $should_reset = ($current_time - $timestamp) >= 2592000;
13327 - break;
13328 - }
13329 -
13330 - // Reset the counter if the timeframe has passed
13331 - if ($should_reset) {
13332 - delete_option($option_name);
13333 - wp_cache_delete($option_name, 'options');
13334 - $processed_count++;
13335 - }
13336 - }
13337 -
13338 - // Clean up any orphaned cache entries
13339 - wp_cache_delete('mxchat_all_chat_limits', 'options');
13340 -
13341 - //error_log("MxChat: Rate limit reset completed. Processed {$processed_count} entries.");
13342 -
13343 - } catch (Exception $e) {
13344 - //error_log('MxChat: Rate limit reset error: ' . $e->getMessage());
13345 - }
13346 -}
13347 -
13348 -
13349 -/**
13350 - * Process HTML links in rate limit messages
13351 - *
13352 - * @param string $message The rate limit message
13353 - * @return string The processed message with safe HTML links
13354 - */
13355 -private function process_rate_limit_message_html($message) {
13356 - // Return original message if empty
13357 - if (empty($message)) {
13358 - return $message;
13359 - }
13360 -
13361 - // First, convert markdown links to HTML
13362 - $message = $this->convert_markdown_links($message);
13363 -
13364 - // Then, auto-convert any remaining plain URLs to links
13365 - $message = $this->auto_link_urls($message);
13366 -
13367 - // Allow basic HTML tags for links and formatting
13368 - $allowed_tags = [
13369 - 'a' => [
13370 - 'href' => true,
13371 - 'target' => true,
13372 - 'rel' => true,
13373 - 'title' => true,
13374 - 'class' => true
13375 - ],
13376 - 'strong' => [],
13377 - 'em' => [],
13378 - 'br' => [],
13379 - 'b' => [],
13380 - 'i' => [],
13381 - 'span' => ['class' => true]
13382 - ];
13383 -
13384 - // Sanitize but allow the specified HTML tags
13385 - $processed_message = wp_kses($message, $allowed_tags);
13386 -
13387 - // If wp_kses stripped everything, return the original message as plain text
13388 - if (empty($processed_message) && !empty($message)) {
13389 - // Strip all HTML and return plain text as fallback
13390 - return wp_strip_all_tags($message);
13391 - }
13392 -
13393 - return $processed_message;
13394 -}
13395 -
13396 -/**
13397 - * Convert markdown links to HTML
13398 - *
13399 - * @param string $text The text to process
13400 - * @return string The text with markdown links converted to HTML
13401 - */
13402 -private function convert_markdown_links($text) {
13403 - // Return original text if empty
13404 - if (empty($text)) {
13405 - return $text;
13406 - }
13407 -
13408 - // Pattern to match markdown links: [text](url)
13409 - $pattern = '/\[([^\]]+)\]\(([^)]+)\)/';
13410 -
13411 - $processed_text = preg_replace_callback($pattern, function($matches) {
13412 - $link_text = $matches[1];
13413 - $url = $matches[2];
13414 -
13415 - // Clean up any trailing punctuation from the URL
13416 - $url = rtrim($url, '.,;:!?');
13417 -
13418 - // Sanitize the link text and URL
13419 - $safe_text = esc_html($link_text);
13420 - $safe_url = esc_url($url);
13421 -
13422 - // Create the HTML link
13423 - return '<a href="' . $safe_url . '" target="_blank" rel="noopener noreferrer">' . $safe_text . '</a>';
13424 - }, $text);
13425 -
13426 - // If preg_replace_callback failed, return original text
13427 - if ($processed_text === null) {
13428 - return $text;
13429 - }
13430 -
13431 - return $processed_text;
13432 -}
13433 -
13434 -/**
13435 - * Auto-convert plain URLs to clickable links
13436 - *
13437 - * @param string $text The text to process
13438 - * @return string The text with URLs converted to links
13439 - */
13440 -private function auto_link_urls($text) {
13441 - // Return original text if empty
13442 - if (empty($text)) {
13443 - return $text;
13444 - }
13445 -
13446 - // Simple pattern that avoids complex lookbehinds
13447 - // This will match URLs that are not already inside href attributes or markdown links
13448 - $pattern = '/(?<!href=["\'])(?<!\]\()https?:\/\/[^\s<>"\')\]]+/i';
13449 -
13450 - $processed_text = preg_replace_callback($pattern, function($matches) {
13451 - $url = $matches[0];
13452 - // Clean up any trailing punctuation that might have been captured
13453 - $url = rtrim($url, '.,;:!?');
13454 -
13455 - // Add target="_blank" and rel="noopener noreferrer" for security
13456 - return '<a href="' . esc_url($url) . '" target="_blank" rel="noopener noreferrer">' . esc_html($url) . '</a>';
13457 - }, $text);
13458 -
13459 - // If preg_replace_callback failed, return original text
13460 - if ($processed_text === null) {
13461 - return $text;
13462 - }
13463 -
13464 - return $processed_text;
13465 -}
13466 -
13467 -
13468 -// Helper function to get client IP address
13469 -private function get_client_ip() {
13470 - // Check for shared internet/ISP IP
13471 - if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
13472 - return sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
13473 - }
13474 -
13475 - // Check for IPs passing through proxies
13476 - if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
13477 - // Use the first value in the comma-separated list
13478 - $forwarded_for = explode(',', sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']));
13479 - return trim($forwarded_for[0]);
13480 - }
13481 -
13482 - if (!empty($_SERVER['REMOTE_ADDR'])) {
13483 - return sanitize_text_field($_SERVER['REMOTE_ADDR']);
13484 - }
13485 -
13486 - // Fallback
13487 - return 'unknown';
13488 -}
13489 -
13490 -/**
13491 - * AJAX handler to get system information for testing panel
13492 - */
13493 -/**
13494 - * AJAX handler to get system information for testing panel
13495 - */
13496 -public function mxchat_get_system_info() {
13497 - // Verify nonce for security
13498 - if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
13499 - wp_send_json_error(['message' => 'Invalid nonce']);
13500 - return;
13501 - }
13502 -
13503 - // Only allow admin users
13504 - if (!current_user_can('administrator')) {
13505 - wp_send_json_error(['message' => 'Unauthorized']);
13506 - return;
13507 - }
13508 -
13509 - // Get system prompt from options
13510 - $system_prompt = isset($this->options['system_prompt_instructions'])
13511 - ? $this->options['system_prompt_instructions']
13512 - : 'No system prompt configured';
13513 -
13514 - // Get selected model
13515 - $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-5.6-sol';
13516 -
13517 - // Check if OpenRouter is being used
13518 - $is_openrouter = ($selected_model === 'openrouter');
13519 - $openrouter_model = '';
13520 -
13521 - if ($is_openrouter) {
13522 - // Get the actual OpenRouter model that's selected
13523 - $openrouter_model = isset($this->options['openrouter_selected_model'])
13524 - ? $this->options['openrouter_selected_model']
13525 - : 'No OpenRouter model selected';
13526 -
13527 - // Update selected_model display to show both
13528 - $selected_model = 'OpenRouter: ' . $openrouter_model;
13529 - }
13530 -
13531 - // Get API key status (just check if they exist, don't expose the keys)
13532 - $api_status = [];
13533 - $api_status['openai'] = !empty($this->options['api_key']);
13534 - $api_status['claude'] = !empty($this->options['claude_api_key']);
13535 - $api_status['gemini'] = !empty($this->options['gemini_api_key']);
13536 - $api_status['xai'] = !empty($this->options['xai_api_key']);
13537 - $api_status['deepseek'] = !empty($this->options['deepseek_api_key']);
13538 - $api_status['openrouter'] = !empty($this->options['openrouter_api_key']);
13539 -
13540 - wp_send_json_success([
13541 - 'system_prompt' => $system_prompt,
13542 - 'selected_model' => $selected_model,
13543 - 'is_openrouter' => $is_openrouter,
13544 - 'openrouter_model' => $openrouter_model,
13545 - 'api_status' => $api_status
13546 - ]);
13547 -}
13548 -
13549 -/**
13550 - * AJAX handler to get similarity threshold
13551 - */
13552 -public function mxchat_get_similarity_threshold() {
13553 - // Verify nonce for security
13554 - if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
13555 - wp_send_json_error(['message' => 'Invalid nonce']);
13556 - return;
13557 - }
13558 -
13559 - // Only allow admin users
13560 - if (!current_user_can('administrator')) {
13561 - wp_send_json_error(['message' => 'Unauthorized']);
13562 - return;
13563 - }
13564 -
13565 - // Get similarity threshold from main options (default 35%)
13566 - $similarity_threshold = isset($this->options['similarity_threshold'])
13567 - ? ((int) $this->options['similarity_threshold']) / 100
13568 - : 0.35;
13569 -
13570 - wp_send_json_success([
13571 - 'threshold' => $similarity_threshold,
13572 - 'threshold_percentage' => ($similarity_threshold * 100) . '%'
13573 - ]);
13574 -}
13575 -
13576 -/**
13577 - * AJAX handler to get knowledge base status
13578 - */
13579 -public function mxchat_get_kb_status() {
13580 - // Verify nonce for security
13581 - if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
13582 - wp_send_json_error(['message' => 'Invalid nonce']);
13583 - return;
13584 - }
13585 -
13586 - // Only allow admin users
13587 - if (!current_user_can('administrator')) {
13588 - wp_send_json_error(['message' => 'Unauthorized']);
13589 - return;
13590 - }
13591 -
13592 - // Check OpenAI Vector Store first (takes priority)
13593 - $vectorstore_options = get_option('mxchat_openai_vectorstore_options', array());
13594 - $use_vectorstore = (isset($vectorstore_options['mxchat_use_openai_vectorstore']) && $vectorstore_options['mxchat_use_openai_vectorstore'] === '1');
13595 -
13596 - if ($use_vectorstore) {
13597 - $vectorstore_ids = $vectorstore_options['mxchat_vectorstore_ids'] ?? '';
13598 - $id_count = !empty($vectorstore_ids) ? count(array_filter(array_map('trim', explode(',', $vectorstore_ids)))) : 0;
13599 -
13600 - $kb_info = [
13601 - 'type' => 'OpenAI Vector Store',
13602 - 'status' => 'Active',
13603 - 'documents' => $id_count > 0 ? $id_count . ' vector store' . ($id_count > 1 ? 's' : '') . ' configured' : 'No vector stores configured'
13604 - ];
13605 -
13606 - wp_send_json_success($kb_info);
13607 - return;
13608 - }
13609 -
13610 - // Check Pinecone vs WordPress
13611 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
13612 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1');
13613 -
13614 - $kb_info = [
13615 - 'type' => $use_pinecone ? 'Pinecone' : 'WordPress Database',
13616 - 'status' => 'Active'
13617 - ];
13618 -
13619 - // Get document count
13620 - if ($use_pinecone) {
13621 - $kb_info['documents'] = 'Connected to Pinecone';
13622 - $kb_info['api_configured'] = !empty($addon_options['mxchat_pinecone_api_key']);
13623 - } else {
13624 - // Count documents in WordPress database
13625 - global $wpdb;
13626 - $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
13627 - $count = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
13628 - $kb_info['documents'] = $count ? $count . ' documents' : 'No documents';
13629 - }
13630 -
13631 - wp_send_json_success($kb_info);
13632 -}
13633 -
13634 -/**
13635 - * AJAX handler to start a completely fresh session (NEW - replaces old clear session)
13636 - */
13637 -public function mxchat_start_fresh_session() {
13638 - // Verify nonce for security
13639 - if (!wp_verify_nonce($_POST['nonce'], 'mxchat_test_nonce')) {
13640 - wp_send_json_error(['message' => 'Invalid nonce']);
13641 - return;
13642 - }
13643 -
13644 - // Only allow admin users
13645 - if (!current_user_can('administrator')) {
13646 - wp_send_json_error(['message' => 'Unauthorized']);
13647 - return;
13648 - }
13649 -
13650 - $old_session_id = isset($_POST['old_session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['old_session_id'])) : '';
13651 - $new_session_id = isset($_POST['new_session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['new_session_id'])) : '';
13652 -
13653 - if (empty($old_session_id)) {
13654 - wp_send_json_error(['message' => 'Old session ID required']);
13655 - return;
13656 - }
13657 -
13658 - // If no new session ID provided, generate one
13659 - if (empty($new_session_id)) {
13660 - // Cryptographically strong session id (plan-0c17b5). Prefix preserved
13661 - // exactly (other code pattern-matches on 'mxchat_chat_'). random_bytes
13662 - // is guaranteed on all supported PHP (7+).
13663 - $new_session_id = 'mxchat_chat_' . bin2hex(random_bytes(16));
13664 - }
13665 -
13666 - // Clear ALL data associated with the old session
13667 - $this->clear_complete_session_data($old_session_id);
13668 -
13669 - // Initialize the new session
13670 - $this->initialize_fresh_session($new_session_id);
13671 -
13672 - wp_send_json_success([
13673 - 'message' => 'Fresh session started successfully',
13674 - 'new_session_id' => $new_session_id,
13675 - 'old_session_id' => $old_session_id
13676 - ]);
13677 -}
13678 -
13679 -/**
13680 - * Clear ALL data associated with a session (ENHANCED)
13681 - */
13682 -private function clear_complete_session_data($session_id) {
13683 - // Clear chat history. The option is a pre-3.2.19 leftover only (839c4c);
13684 - // the transcript rows for the abandoned session id deliberately stay —
13685 - // they are the admin's conversation record, and the fresh session gets a
13686 - // new id so the widget never replays them.
13687 - delete_option("mxchat_history_{$session_id}");
13688 - MxChat_Utils::flush_session_history_cache($session_id);
13689 -
13690 - // Clear any PDF/Word transients
13691 - $this->clear_pdf_transients($session_id);
13692 - if (method_exists($this, 'clear_word_transients')) {
13693 - $this->clear_word_transients($session_id);
13694 - }
13695 -
13696 - // Archive the session's per-conversation Slack channel before its option
13697 - // is deleted (plan 7458a7 — covers transcript-retention cleanup paths).
13698 - // Toggle-gated + shared-channel-guarded inside the helper; best-effort.
13699 - $stale_channel = MxChat_Session_Store::get($session_id, 'channel', '');
13700 - if ($stale_channel !== '') {
13701 - $this->mxchat_maybe_archive_conversation_channel($session_id, $stale_channel);
13702 - }
13703 -
13704 - // Clear agent-related data. delete_session() drops the whole session row —
13705 - // mode, channel, owner, originating_page and (since 5658f2) the visitor
13706 - // identity + agent name — plus every legacy option key for installs still
13707 - // mid-migration. The old per-key deletes for agent_name/email are covered
13708 - // by that legacy sweep now.
13709 - MxChat_Session_Store::delete_session($session_id);
13710 - delete_option("mxchat_thread_{$session_id}");
13711 -
13712 - // Clear any recommendation flow state
13713 - delete_option("mxchat_sr_flow_state_{$session_id}");
13714 -
13715 - // Clear any cached embeddings or context
13716 - delete_transient("mxchat_context_{$session_id}");
13717 - delete_transient("mxchat_last_query_{$session_id}");
13718 -
13719 - // Clear any testing data
13720 - delete_transient("mxchat_testing_data_{$session_id}");
13721 -
13722 - // Clear any rate limiting data for this session
13723 - delete_transient("mxchat_rate_limit_{$session_id}");
13724 -
13725 - // Clear any other session-specific transients
13726 - delete_transient("mxchat_waiting_for_pdf_url_{$session_id}");
13727 - delete_transient("mxchat_include_pdf_in_context_{$session_id}");
13728 - delete_transient("mxchat_include_word_in_context_{$session_id}");
13729 -
13730 - // Clear form addon state (pending forms and submitted forms)
13731 - delete_option("mxchat_pending_form_{$session_id}");
13732 - delete_option("mxchat_submitted_forms_{$session_id}");
13733 -
13734 - //error_log("MxChat: Cleared all data for session: {$session_id}");
13735 -}
13736 -
13737 -/**
13738 - * Initialize a fresh session with default data
13739 - */
13740 -private function initialize_fresh_session($session_id) {
13741 - // Set default chat mode
13742 - MxChat_Session_Store::set($session_id, 'mode', 'ai');
13743 -
13744 - //error_log("MxChat: Initialized fresh session: {$session_id}");
13745 -}
13746 -
13747 -/**
13748 - * Helper method to clear Word document transients (if you have Word support)
13749 - */
13750 -private function clear_word_transients($session_id) {
13751 - delete_transient('mxchat_word_url_' . $session_id);
13752 - delete_transient('mxchat_word_filename_' . $session_id);
13753 - delete_transient('mxchat_word_embeddings_' . $session_id);
13754 - delete_transient('mxchat_include_word_in_context_' . $session_id);
13755 -}
13756 -
13757 -/**
13758 - * Simplified testing data capture method (CLEANED UP)
13759 - */
13760 -private function capture_testing_data($user_embedding, $message, $session_id) {
13761 - // Only capture for admin users
13762 - if (!current_user_can('administrator')) {
13763 - return null;
13764 - }
13765 -
13766 - $testing_data = [
13767 - 'query' => $message,
13768 - 'timestamp' => time(),
13769 - 'top_matches' => [],
13770 - 'action_matches' => [] // Add action matches
13771 - ];
13772 -
13773 - // Get similarity threshold
13774 - $similarity_threshold = isset($this->options['similarity_threshold'])
13775 - ? ((int) $this->options['similarity_threshold']) / 100
13776 - : 0.35;
13777 -
13778 - $testing_data['similarity_threshold'] = $similarity_threshold;
13779 -
13780 - // Use the real similarity analysis if available
13781 - if ($this->last_similarity_analysis !== null) {
13782 - $testing_data['knowledge_base_type'] = $this->last_similarity_analysis['knowledge_base_type'];
13783 - $testing_data['top_matches'] = $this->last_similarity_analysis['top_matches'];
13784 - $testing_data['total_documents_checked'] = $this->last_similarity_analysis['total_checked'] ?? 0;
13785 - } else {
13786 - // Fallback: determine knowledge base type
13787 - $addon_options = get_option('mxchat_pinecone_addon_options', array());
13788 - $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1');
13789 -
13790 - $testing_data['knowledge_base_type'] = $use_pinecone ? 'Pinecone' : 'WordPress Database';
13791 - }
13792 -
13793 - // Include action analysis if available
13794 - if (isset($this->last_action_analysis) && !empty($this->last_action_analysis)) {
13795 - $testing_data['action_matches'] = $this->last_action_analysis;
13796 -
13797 - // Clear it after capturing to avoid stale data
13798 - $this->last_action_analysis = null;
13799 - }
13800 -
13801 - return $testing_data;
13802 -}
13803 -
13804 -
13805 -/**
13806 - * Track URL clicks from chatbot responses
13807 - */
13808 -public function mxchat_track_url_click() {
13809 - // Verify nonce for security
13810 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce($_POST['nonce'])) {
13811 - wp_send_json_error(['message' => 'Invalid nonce']);
13812 - wp_die();
13813 - }
13814 -
13815 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
13816 - $clicked_url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : '';
13817 - $message_context = isset($_POST['message_context']) ? sanitize_textarea_field($_POST['message_context']) : '';
13818 -
13819 - if (empty($session_id) || empty($clicked_url)) {
13820 - wp_send_json_error(['message' => 'Missing required data']);
13821 - wp_die();
13822 - }
13823 -
13824 - global $wpdb;
13825 - $table_name = $wpdb->prefix . 'mxchat_url_clicks';
13826 -
13827 - // Insert click tracking record
13828 - $wpdb->insert(
13829 - $table_name,
13830 - [
13831 - 'session_id' => $session_id,
13832 - 'clicked_url' => $clicked_url,
13833 - 'message_context' => $message_context,
13834 - 'click_timestamp' => current_time('mysql', 1),
13835 - 'user_ip' => $_SERVER['REMOTE_ADDR'],
13836 - 'user_agent' => $_SERVER['HTTP_USER_AGENT']
13837 - ]
13838 - );
13839 -
13840 - // Opportunistic retention sweep on the write path — click rows must not
13841 - // accumulate identifiers unboundedly, and WP-Cron cannot be relied on
13842 - // (plan 23c4a1). Time-gated + batched inside, so this stays cheap.
13843 - if (class_exists('MxChat_Privacy')) {
13844 - MxChat_Privacy::maybe_sweep_url_clicks();
13845 - }
13846 -
13847 - wp_send_json_success(['message' => 'Click tracked']);
13848 - wp_die();
13849 -}
13850 -
13851 -/**
13852 - * Get URL click analytics for a session
13853 - */
13854 -public function mxchat_get_url_clicks($session_id) {
13855 - global $wpdb;
13856 - $table_name = $wpdb->prefix . 'mxchat_url_clicks';
13857 -
13858 - $clicks = $wpdb->get_results($wpdb->prepare(
13859 - "SELECT * FROM $table_name WHERE session_id = %s ORDER BY click_timestamp ASC",
13860 - $session_id
13861 - ));
13862 -
13863 - return $clicks;
13864 -}
13865 -/**
13866 - * Track the originating page where chat was started
13867 - */
13868 -public function mxchat_track_originating_page() {
13869 - // Verify nonce
13870 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce($_POST['nonce'])) {
13871 - wp_send_json_error(['message' => 'Invalid nonce']);
13872 - wp_die();
13873 - }
13874 -
13875 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
13876 - $page_url = isset($_POST['page_url']) ? esc_url_raw($_POST['page_url']) : '';
13877 - $page_title = isset($_POST['page_title']) ? sanitize_text_field($_POST['page_title']) : '';
13878 -
13879 - if (empty($session_id)) {
13880 - wp_send_json_error(['message' => 'Missing session ID']);
13881 - wp_die();
13882 - }
13883 -
13884 - global $wpdb;
13885 - $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
13886 -
13887 - // Check if we've already tracked for this session
13888 - $existing = $wpdb->get_var($wpdb->prepare(
13889 - "SELECT COUNT(*) FROM $table_name
13890 - WHERE session_id = %s
13891 - AND originating_page_url IS NOT NULL",
13892 - $session_id
13893 - ));
13894 -
13895 - if ($existing > 0) {
13896 - wp_send_json_success(['message' => 'Already tracked']);
13897 - wp_die();
13898 - }
13899 -
13900 - // Update the first message in this session with originating page info
13901 - $wpdb->query($wpdb->prepare(
13902 - "UPDATE $table_name
13903 - SET originating_page_url = %s,
13904 - originating_page_title = %s
13905 - WHERE session_id = %s
13906 - ORDER BY timestamp ASC
13907 - LIMIT 1",
13908 - $page_url,
13909 - $page_title,
13910 - $session_id
13911 - ));
13912 -
13913 - wp_send_json_success(['message' => 'Originating page tracked']);
13914 - wp_die();
13915 -}
13916 -
13917 -/**
13918 - * Validate and clean URLs from AI response
13919 - * Removes any URLs that aren't in the knowledge base
13920 - *
13921 - * @param string $response_text The AI-generated response
13922 - * @param array $valid_urls Array of URLs from the knowledge base
13923 - * @return string Cleaned response with invalid URLs removed/flagged
13924 - */
13925 -private function validate_and_clean_urls($response_text, $valid_urls, $session_id = null, $bot_id = null) {
13926 - /**
13927 - * Filter the list of URLs treated as valid (allowlisted) BEFORE the
13928 - * response URL sanitizer strips any link not in the list. Lets a site
13929 - * owner / developer whitelist links their custom function-calling tools
13930 - * return (e.g. session or speaker pages), which are otherwise absent from
13931 - * the RAG/system-prompt-derived list and get stripped to plain text.
13932 - *
13933 - * Purely additive: with no hook registered, apply_filters returns
13934 - * $valid_urls untouched, so there is zero behavior change for anyone who
13935 - * does not use the filter. Applied before the empty-check so a hooked
13936 - * allowlist can participate. (plan-mxchat-20260710-13a471)
13937 - *
13938 - * @param array $valid_urls URLs already known-valid (RAG + system prompt).
13939 - * @param string|null $session_id Current chat session id, if available.
13940 - * @param string|null $bot_id Current bot id, if available.
13941 - */
13942 - $valid_urls = apply_filters('mxchat_valid_urls', $valid_urls, $session_id, $bot_id);
13943 -
13944 - // A bad mu-plugin returning a non-array (or non-string entries) must never
13945 - // fatal the response path — coerce defensively before any use.
13946 - if (!is_array($valid_urls)) {
13947 - $valid_urls = array();
13948 - }
13949 - $valid_urls = array_values(array_filter($valid_urls, static function ($u) {
13950 - return is_string($u) && $u !== '';
13951 - }));
13952 -
13953 - // If no valid URLs provided or empty response, return as-is
13954 - if (empty($valid_urls) || empty($response_text)) {
13955 - //error_log("Validation skipped - empty valid_urls or response");
13956 - return $response_text;
13957 - }
13958 -
13959 - // Extract all URLs from the AI response
13960 - // This regex matches http:// and https:// URLs
13961 - preg_match_all(
13962 - '#\bhttps?://[^\s<>"\')\]]+#i',
13963 - $response_text,
13964 - $matches
13965 - );
13966 -
13967 - // If no URLs found in response, return as-is
13968 - if (empty($matches[0])) {
13969 - //error_log("No URLs found in response");
13970 - return $response_text;
13971 - }
13972 -
13973 - $found_urls = $matches[0];
13974 - $cleaned_response = $response_text;
13975 - $removed_count = 0;
13976 -
13977 - // Normalize valid URLs for comparison (remove trailing slashes, fragments, etc.)
13978 - $normalized_valid_urls = array_map(function($url) {
13979 - // Remove trailing slash
13980 - $url = rtrim($url, '/');
13981 - // Remove URL fragments (#section)
13982 - $url = preg_replace('/#.*$/', '', $url);
13983 - // Remove trailing punctuation that might have been captured
13984 - $url = rtrim($url, '.,;:!?');
13985 - return $url;
13986 - }, $valid_urls);
13987 -
13988 - //error_log("Normalized valid URLs: " . print_r($normalized_valid_urls, true));
13989 -
13990 - foreach ($found_urls as $found_url) {
13991 - // Clean up the found URL (remove trailing punctuation that might have been captured)
13992 - $clean_found_url = rtrim($found_url, '.,;:!?)');
13993 -
13994 - // DEBUG: Log each URL being checked
13995 - //error_log("Checking found URL: " . $found_url);
13996 -
13997 - // Normalize for comparison
13998 - $normalized_found = rtrim($clean_found_url, '/');
13999 - $normalized_found = preg_replace('/#.*$/', '', $normalized_found);
14000 -
14001 - //error_log("Normalized found URL: " . $normalized_found);
14002 -
14003 - // Check if this URL exists in our valid URLs list
14004 - $is_valid = false;
14005 -
14006 - //error_log("Starting validation checks for: " . $normalized_found);
14007 -
14008 - // First, try exact match
14009 - if (in_array($normalized_found, $normalized_valid_urls)) {
14010 - $is_valid = true;
14011 - //error_log("EXACT MATCH FOUND");
14012 - } else {
14013 - //error_log("No exact match, checking variations...");
14014 - // If no exact match, check if it's a variation (with query params, etc.)
14015 - foreach ($normalized_valid_urls as $valid_url) {
14016 - //error_log(" Comparing against valid URL: " . $valid_url);
14017 -
14018 - // Check if the found URL starts with a valid URL (handles query params)
14019 - if (strpos($normalized_found, $valid_url) === 0) {
14020 - // Check what comes after the valid URL
14021 - $remainder = substr($normalized_found, strlen($valid_url));
14022 -
14023 - // Only valid if:
14024 - // 1. Exact match (remainder is empty)
14025 - // 2. Query params (starts with ?)
14026 - // 3. Fragment (starts with #)
14027 - if (empty($remainder) || $remainder[0] === '?' || $remainder[0] === '#') {
14028 - $is_valid = true;
14029 - //error_log(" MATCH: Found URL is valid variation of base URL");
14030 - break;
14031 - } else {
14032 - //error_log(" NOT A MATCH: Found URL extends path beyond valid URL (remainder: " . $remainder . ")");
14033 - }
14034 - }
14035 - // Also check the reverse (in case valid URL has query params)
14036 - if (strpos($valid_url, $normalized_found) === 0) {
14037 - $is_valid = true;
14038 - //error_log(" MATCH: Valid URL starts with found URL");
14039 - break;
14040 - }
14041 - }
14042 -
14043 - if (!$is_valid) {
14044 - //error_log("NO MATCH FOUND - URL should be removed");
14045 - }
14046 - }
14047 -
14048 - // If URL is not valid, remove it from the response
14049 - if (!$is_valid) {
14050 - // Log the removal for debugging
14051 - //error_log("MxChat: Removed hallucinated URL: " . $found_url);
14052 - //error_log("MxChat: Valid URLs were: " . implode(', ', array_slice($normalized_valid_urls, 0, 5)));
14053 -
14054 - $removed_count++;
14055 -
14056 - // Check if URL is part of a markdown link: [text](url)
14057 - $markdown_pattern = '/\[([^\]]+)\]\(' . preg_quote($found_url, '/') . '\)/';
14058 - if (preg_match($markdown_pattern, $cleaned_response)) {
14059 - //error_log("Found markdown link, removing but keeping text");
14060 - // Remove the markdown link but keep the text
14061 - $cleaned_response = preg_replace($markdown_pattern, '$1', $cleaned_response);
14062 - }
14063 - // Check if URL is part of an HTML link: <a href="url">text</a>
14064 - else if (preg_match('/<a[^>]*href=["\']' . preg_quote($found_url, '/') . '["\'][^>]*>(.*?)<\/a>/i', $cleaned_response, $link_match)) {
14065 - //error_log("Found HTML link, removing but keeping text");
14066 - // Remove the HTML link but keep the text
14067 - $link_text = $link_match[1];
14068 - $cleaned_response = preg_replace(
14069 - '/<a[^>]*href=["\']' . preg_quote($found_url, '/') . '["\'][^>]*>.*?<\/a>/i',
14070 - $link_text,
14071 - $cleaned_response
14072 - );
14073 - }
14074 - // Otherwise just remove the bare URL
14075 - else {
14076 - //error_log("Removing bare URL");
14077 - $cleaned_response = str_replace($found_url, '', $cleaned_response);
14078 - }
14079 - }
14080 - }
14081 -
14082 - // Log summary if any URLs were removed
14083 - if ($removed_count > 0) {
14084 - //error_log("MxChat: URL Validation Summary - Removed {$removed_count} hallucinated URL(s)");
14085 - } else {
14086 - //error_log("MxChat: URL Validation Summary - No URLs removed, all were valid");
14087 - }
14088 -
14089 - // Clean up any double spaces or awkward punctuation left behind
14090 - // IMPORTANT: Only collapse horizontal whitespace (spaces/tabs), preserve newlines for markdown formatting
14091 - $cleaned_response = preg_replace('/[^\S\n]+/', ' ', $cleaned_response); // Collapse spaces/tabs but NOT newlines
14092 - $cleaned_response = preg_replace('/[^\S\n]+([.,;:!?])/', '$1', $cleaned_response); // Same for punctuation cleanup
14093 -
14094 - //error_log("Final cleaned response: " . $cleaned_response);
14095 -
14096 - return trim($cleaned_response);
14097 -}
14098 -
14099 -/**
14100 - * AJAX handler to get current chat mode for a session
14101 - */
14102 -public function mxchat_get_current_chat_mode() {
14103 - // Verify nonce for security
14104 - if (!isset($_POST['nonce']) || !MxChat_Integrator::mxchat_verify_chat_send_nonce($_POST['nonce'])) {
14105 - wp_send_json_error(['message' => 'Invalid nonce']);
14106 - wp_die();
14107 - }
14108 -
14109 - $session_id = isset($_POST['session_id']) ? MxChat_Utils::sanitize_session_id(wp_unslash($_POST['session_id'])) : '';
14110 -
14111 - if (empty($session_id)) {
14112 - wp_send_json_error(['message' => 'Session ID missing']);
14113 - wp_die();
14114 - }
14115 -
14116 - // Get the current chat mode for this session
14117 - $chat_mode = MxChat_Session_Store::get($session_id, 'mode', 'ai');
14118 -
14119 - wp_send_json_success([
14120 - 'chat_mode' => $chat_mode
14121 - ]);
14122 - wp_die();
14123 -}
14124 -
14125 -
14126 -
14127 -}
14128 -?>
1 +<?php
2 +if (!defined('ABSPATH')) {
3 + exit;
4 +}
5 +
6 +class MxChat_Integrator {
7 + private $options;
8 + private $prompts_options;
9 + private $chat_count;
10 + private $fallbackResponse;
11 + private $productCardHtml;
12 + private $word_handler;
13 +
14 +/**
15 + * Setup the cron jobs for rate limits
16 + */
17 +public function setup_rate_limit_cron_jobs() {
18 + // Clear previous schedules
19 + wp_clear_scheduled_hook('mxchat_reset_rate_limits');
20 + wp_clear_scheduled_hook('mxchat_reset_hourly_rate_limits');
21 + wp_clear_scheduled_hook('mxchat_reset_daily_rate_limits');
22 + wp_clear_scheduled_hook('mxchat_reset_weekly_rate_limits');
23 + wp_clear_scheduled_hook('mxchat_reset_monthly_rate_limits');
24 +
25 + // Schedule the main rate limit reset check (runs hourly)
26 + if (!wp_next_scheduled('mxchat_reset_rate_limits')) {
27 + wp_schedule_event(time(), 'hourly', 'mxchat_reset_rate_limits');
28 + }
29 +}
30 +
31 +/**
32 + * Class constructor
33 + */
34 +public function __construct() {
35 + $this->options = get_option('mxchat_options');
36 + $this->prompts_options = get_option('mxchat_prompts_options', array());
37 + $this->chat_count = get_option('mxchat_chat_count', 0);
38 + $this->word_handler = new MXChat_Word_Handler($this->options);
39 +
40 + // Setup the cron jobs for rate limits
41 + $this->setup_rate_limit_cron_jobs();
42 +
43 + // Add all action hooks
44 + add_action('wp_enqueue_scripts', array($this, 'mxchat_enqueue_scripts_styles'));
45 + add_action('wp_ajax_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
46 + add_action('wp_ajax_nopriv_mxchat_handle_chat_request', array($this, 'mxchat_handle_chat_request'));
47 + add_action('wp_ajax_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
48 + add_action('wp_ajax_nopriv_mxchat_dismiss_pre_chat_message', array($this, 'mxchat_dismiss_pre_chat_message'));
49 +
50 + // Add the AJAX actions for checking if the pre-chat message was dismissed
51 + add_action('wp_ajax_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
52 + add_action('wp_ajax_nopriv_mxchat_check_pre_chat_message_status', array($this, 'mxchat_check_pre_chat_message_status'));
53 + add_action('wp_ajax_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
54 + add_action('wp_ajax_nopriv_mxchat_fetch_conversation_history', [$this, 'mxchat_fetch_conversation_history']);
55 + add_action('wp_ajax_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
56 + add_action('wp_ajax_nopriv_mxchat_add_to_cart', [$this, 'mxchat_add_to_cart']);
57 +
58 + // Add REST API routes registration
59 + add_action('rest_api_init', array($this, 'register_routes'));
60 + add_action('wp_ajax_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
61 + add_action('wp_ajax_nopriv_mxchat_fetch_new_messages', array($this, 'mxchat_fetch_new_messages'));
62 +
63 + // Rate limit action - notice we removed the old schedule setup
64 + add_action('mxchat_reset_rate_limits', array($this, 'mxchat_reset_rate_limits'));
65 +
66 + // File upload and handling actions
67 + add_action('wp_ajax_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
68 + add_action('wp_ajax_nopriv_mxchat_upload_pdf', [$this, 'handle_pdf_upload']);
69 + add_action('wp_ajax_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
70 + add_action('wp_ajax_nopriv_mxchat_remove_pdf', [$this, 'handle_pdf_remove']);
71 +
72 + // Word document handling actions
73 + add_action('wp_ajax_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
74 + add_action('wp_ajax_nopriv_mxchat_upload_word', array($this, 'mxchat_handle_word_upload'));
75 + add_action('wp_ajax_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
76 + add_action('wp_ajax_nopriv_mxchat_remove_word', array($this, 'mxchat_handle_word_remove'));
77 + add_action('wp_ajax_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
78 + add_action('wp_ajax_nopriv_mxchat_check_word_status', array($this, 'mxchat_check_word_status'));
79 +
80 + // Email handling actions
81 + add_action('wp_ajax_nopriv_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
82 + add_action('wp_ajax_mxchat_handle_save_email_and_response', [$this, 'mxchat_handle_save_email_and_response']);
83 + add_action('wp_ajax_nopriv_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
84 + add_action('wp_ajax_mxchat_check_email_provided', [$this, 'mxchat_check_email_provided']);
85 +}
86 +
87 +
88 + private function mxchat_increment_chat_count() {
89 + $chat_count = get_option('mxchat_chat_count', 0);
90 + $chat_count++;
91 + update_option('mxchat_chat_count', $chat_count);
92 + }
93 +
94 +function mxchat_fetch_conversation_history() {
95 + if (empty($_POST['session_id'])) {
96 + wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
97 + wp_die();
98 + }
99 +
100 + $session_id = sanitize_text_field($_POST['session_id']);
101 + $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history
102 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai'); // Get current chat mode
103 +
104 + if (empty($history)) {
105 + // Even if history is empty, return the chat mode
106 + wp_send_json_success([
107 + 'conversation' => [],
108 + 'chat_mode' => $chat_mode
109 + ]);
110 + wp_die();
111 + }
112 +
113 + wp_send_json_success([
114 + 'conversation' => $history,
115 + 'chat_mode' => $chat_mode
116 + ]);
117 + wp_die();
118 +}
119 +private function mxchat_fetch_conversation_history_for_ajax($session_id) {
120 + $history = get_option("mxchat_history_{$session_id}", []); // Retrieve stored history based on session ID
121 + $formatted_history = [];
122 +
123 + // Format the history to align with the expected structure for OpenAI
124 + foreach ($history as $entry) {
125 + $formatted_history[] = [
126 + 'role' => $entry['role'], // Ensure this matches 'user' or 'assistant'
127 + 'content' => $entry['content']
128 + ];
129 + }
130 +
131 + return $formatted_history;
132 +}
133 +
134 +
135 +private function mxchat_fetch_conversation_history_for_ai($session_id) {
136 + $history = get_option("mxchat_history_{$session_id}", []);
137 + $formatted_history = [];
138 +
139 + // Adjusted for code-heavy conversations
140 + $max_tokens = 120000; // Context window size
141 + $reserved_tokens = 5000; // Space for system prompts + current query
142 + $current_token_count = 0;
143 +
144 + // Allowed HTML tags for content sanitization
145 + $allowed_tags = [
146 + 'pre' => ['class' => true],
147 + 'code' => ['class' => true],
148 + 'span' => ['class' => true],
149 + 'div' => ['class' => true],
150 + 'strong' => [],
151 + 'em' => []
152 + ];
153 +
154 + foreach (array_reverse($history) as $entry) {
155 + // Preserve code blocks while sanitizing other HTML
156 + $clean_content = wp_kses($entry['content'], $allowed_tags);
157 +
158 + // Detect code blocks in content
159 + $has_code = false;
160 +// Replace the HTML check with:
161 +// Allow messages that contain code blocks or are plain text
162 +if (strpos($clean_content, '<pre') === false &&
163 + strpos($clean_content, '<code') === false &&
164 + $clean_content !== strip_tags($entry['content'])) {
165 + continue;
166 +}
167 +
168 + // Skip entries that lost significant content during sanitization
169 + if (!$has_code && $clean_content !== strip_tags($entry['content'])) {
170 + continue;
171 + }
172 +
173 + // More accurate token estimation (1 token ≈ 4 characters)
174 + $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
175 +
176 + // Check token budget with the new estimate
177 + if (($current_token_count + $token_estimate + $reserved_tokens) > $max_tokens) {
178 + // Try to fit partial content if it's the first entry
179 + if (empty($formatted_history)) {
180 + $clean_content = mb_substr($clean_content, 0, ($max_tokens - $reserved_tokens) * 4);
181 + $token_estimate = ceil(mb_strlen($clean_content, 'UTF-8') / 4);
182 + } else {
183 + break;
184 + }
185 + }
186 +
187 + // Add to formatted history
188 + $formatted_history[] = [
189 + 'role' => $entry['role'],
190 + 'content' => $clean_content
191 + ];
192 +
193 + $current_token_count += $token_estimate;
194 + }
195 +
196 + // Reverse back to maintain chronological order
197 + $formatted_history = array_reverse($formatted_history);
198 +
199 + // Add system message about code context
200 + array_unshift($formatted_history, [
201 + 'role' => 'system',
202 + 'content' => 'Preserved code blocks are marked with [CODE BLOCK PRESERVED]. '
203 + . 'Maintain formatting and syntax highlighting when referencing code.'
204 + ]);
205 +
206 + return $formatted_history;
207 +}
208 +
209 +public function register_routes() {
210 + //error_log(esc_html__('Registering MxChat REST routes', 'mxchat'));
211 +
212 + register_rest_route('mxchat/v1', '/stream', [
213 + 'methods' => 'GET',
214 + 'callback' => [$this, 'mxchat_stream_events'],
215 + 'permission_callback' => [$this, 'verify_chat_session'],
216 + ]);
217 +
218 + register_rest_route('mxchat/v1', '/agent-response', [
219 + 'methods' => 'POST',
220 + 'callback' => [$this, 'mxchat_handle_agent_response'],
221 + 'permission_callback' => [$this, 'verify_slack_request'],
222 + ]);
223 +
224 + register_rest_route('mxchat/v1', '/slack-interaction', [
225 + 'methods' => 'POST',
226 + 'callback' => [$this, 'handle_slack_interaction'],
227 + 'permission_callback' => [$this, 'verify_slack_request'],
228 + ]);
229 +
230 + //error_log(esc_html__('MxChat REST routes registered', 'mxchat'));
231 +}
232 +
233 +/**
234 + * Verify valid chat session
235 + */
236 +public function verify_chat_session($request) {
237 + $session_id = $request->get_param('session_id');
238 + if (empty($session_id)) {
239 + //error_log(esc_html__('Empty session ID in chat request', 'mxchat'));
240 + return false;
241 + }
242 +
243 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
244 + return $chat_mode === 'agent';
245 +}
246 +
247 +/**
248 + * Verify request is coming from Slack.
249 + *
250 + * @param WP_REST_Request $request
251 + * @return bool True if valid, false otherwise.
252 + */
253 +public function verify_slack_request($request) {
254 + // Get the Slack signing secret from your plugin options
255 + $valid_key = $this->options['live_agent_secret_key'] ?? '';
256 +
257 + if (empty($valid_key)) {
258 + //error_log(esc_html__('Slack signing secret not configured', 'mxchat'));
259 + return false;
260 + }
261 +
262 + $timestamp = $request->get_header('X-Slack-Request-Timestamp');
263 + $slack_signature = $request->get_header('X-Slack-Signature');
264 +
265 + // Verify timestamp to prevent replay attacks
266 + if (abs(time() - intval($timestamp)) > 300) {
267 + //error_log(esc_html__('Slack request timestamp too old', 'mxchat'));
268 + return false;
269 + }
270 +
271 + // Get raw request body
272 + $request_body = file_get_contents('php://input');
273 +
274 + // Create the signature base string
275 + $sig_basestring = "v0:{$timestamp}:{$request_body}";
276 +
277 + // Calculate expected signature
278 + $my_signature = 'v0=' . hash_hmac('sha256', $sig_basestring, $valid_key);
279 +
280 + // Compare signatures
281 + return hash_equals($my_signature, $slack_signature);
282 +}
283 +public function mxchat_stream_events(WP_REST_Request $request) {
284 + header('Content-Type: text/event-stream');
285 + header('Cache-Control: no-cache');
286 + header('Connection: keep-alive');
287 +
288 + $session_id = sanitize_text_field($request->get_param('session_id'));
289 + $last_seen_id = sanitize_text_field($request->get_param('last_seen_id')) ?: '';
290 +
291 + if (empty($session_id)) {
292 + echo esc_html__("event: error\ndata: ", 'mxchat') . esc_html__('Missing session_id', 'mxchat') . "\n\n";
293 + flush();
294 + exit;
295 + }
296 +
297 + $history = get_option("mxchat_history_{$session_id}", []);
298 +
299 + // Filter only new messages
300 + $new_messages = array_filter($history, function ($message) use ($last_seen_id) {
301 + return !empty($message['id']) && $message['id'] > $last_seen_id;
302 + });
303 +
304 + // Send new messages if available
305 + if (!empty($new_messages)) {
306 + echo esc_html__("event: newMessages\ndata: ", 'mxchat') . json_encode(array_values($new_messages)) . "\n\n";
307 + } else {
308 + // Keep the connection alive
309 + echo esc_html__("event: keepAlive\ndata: ", 'mxchat') . "{}\n\n";
310 + }
311 + flush();
312 + exit;
313 +}
314 +
315 +
316 +
317 +
318 +private function mxchat_save_chat_message($session_id, $role, $message) {
319 + global $wpdb;
320 +
321 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
322 + //error_log("[DEBUG] mxchat_save_chat_message -> START for session_id: {$session_id}, role: {$role}");
323 +
324 + // 1) Extract agent name if present
325 + $agent_name = '';
326 + if (preg_match('/^Agent: (.*?) - /', $message, $matches)) {
327 + $agent_name = $matches[1];
328 + $message = str_replace("Agent: $agent_name - ", '', $message);
329 +
330 + $session_meta_key = "mxchat_agent_name_{$session_id}";
331 + if (empty(get_option($session_meta_key))) {
332 + update_option($session_meta_key, $agent_name);
333 + //error_log("[DEBUG] mxchat_save_chat_message -> Stored agent_name in option: {$session_meta_key} => {$agent_name}");
334 + }
335 + }
336 +
337 + // 2) Generate unique message_id
338 + $message_id = uniqid();
339 + //error_log("[DEBUG] mxchat_save_chat_message -> Generated message_id: {$message_id}");
340 +
341 + // 3) Determine user_id
342 + $user_id = is_user_logged_in() ? get_current_user_id() : 0;
343 +
344 + // 4) Determine user_identifier
345 + $user_identifier = $agent_name
346 + ? $agent_name
347 + : MxChat_User::mxchat_get_user_identifier();
348 +
349 + // 5) Determine displayed_name
350 + $user_email = MxChat_User::mxchat_get_user_email();
351 + $displayed_name = $agent_name ? $agent_name : ($user_email ?: $user_identifier);
352 +
353 + // 6) Check for a saved email in wp_options
354 + $email_option_key = "mxchat_email_{$session_id}";
355 + $saved_email = get_option($email_option_key);
356 + //error_log("[DEBUG] mxchat_save_chat_message -> Checking wp_options for email_option_key: {$email_option_key}, found: {$saved_email}");
357 +
358 + // If found, update DB user_email
359 + if ($saved_email) {
360 + $update_res = $wpdb->update(
361 + $table_name,
362 + ['user_email' => $saved_email],
363 + ['session_id' => $session_id],
364 + ['%s'],
365 + ['%s']
366 + );
367 + //error_log("[DEBUG] mxchat_save_chat_message -> Attempted DB user_email update for session_id {$session_id}. update_res: {$update_res}");
368 + }
369 +
370 + // 7) Save to session history in wp_options
371 + $history_key = "mxchat_history_{$session_id}";
372 + $history = get_option($history_key, []);
373 + $history[] = [
374 + 'id' => $message_id,
375 + 'role' => $role,
376 + 'content' => $message,
377 + 'timestamp' => round(microtime(true) * 1000),
378 + 'agent_name' => $displayed_name,
379 + ];
380 + update_option($history_key, $history);
381 + //error_log("[DEBUG] mxchat_save_chat_message -> Updated session history in option: {$history_key}");
382 +
383 + // 8) Save the message to DB (INSERT)
384 + $insert_data = [
385 + 'user_id' => $user_id,
386 + 'user_identifier'=> $user_identifier,
387 + 'user_email' => $saved_email ?: $user_email,
388 + 'session_id' => $session_id,
389 + 'role' => $role,
390 + 'message' => $message,
391 + 'timestamp' => current_time('mysql', 1),
392 + ];
393 + $wpdb->insert($table_name, $insert_data);
394 + //error_log("[DEBUG] mxchat_save_chat_message -> Inserted message into DB. row_id: {$wpdb->insert_id}, data: " . print_r($insert_data, true));
395 +
396 + //error_log("[DEBUG] mxchat_save_chat_message -> END for session_id: {$session_id}");
397 + return $message_id;
398 +}
399 +
400 +public function mxchat_handle_save_email_and_response() {
401 + //error_log('[DEBUG] ---------- mxchat_handle_save_email_and_response START ----------');
402 +
403 + // Validate nonce
404 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
405 + //error_log(esc_html__('[ERROR] Invalid nonce in mxchat_handle_save_email_and_response', 'mxchat'));
406 + wp_send_json_error(['message' => esc_html__('Invalid nonce.', 'mxchat')]);
407 + wp_die();
408 + }
409 +
410 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
411 + $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
412 +
413 + //error_log("[DEBUG] handle_save_email_and_response -> session_id: {$session_id}, email: {$email}");
414 +
415 + if (empty($session_id) || empty($email)) {
416 + //error_log("[ERROR] Missing session_id or email: session_id={$session_id}, email={$email}");
417 + wp_send_json_error(['message' => esc_html__('Session ID or email is missing.', 'mxchat')]);
418 + wp_die();
419 + }
420 +
421 + // 1) Always store in wp_options
422 + $option_key = "mxchat_email_{$session_id}";
423 + update_option($option_key, $email);
424 + //error_log("[DEBUG] handle_save_email_and_response -> updated option: {$option_key} => {$email}");
425 +
426 + // 2) (Optional) Also store in DB if a row already exists
427 + global $wpdb;
428 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
429 +
430 + // Make sure we have a valid placeholder in prepare
431 + $sql = $wpdb->prepare("SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s", $session_id);
432 + $session_count = $wpdb->get_var($sql);
433 +
434 + //error_log("[DEBUG] handle_save_email_and_response -> session_count for {$session_id}: {$session_count} (SQL: {$sql})");
435 +
436 + if ($session_count) {
437 + // Update user_email if row(s) exist
438 + $update_sql = $wpdb->prepare(
439 + "UPDATE {$table_name} SET user_email = %s WHERE session_id = %s",
440 + $email,
441 + $session_id
442 + );
443 + $wpdb->query($update_sql);
444 + //error_log("[DEBUG] handle_save_email_and_response -> DB updated: {$update_sql}");
445 + } else {
446 + //error_log("[INFO] handle_save_email_and_response -> No DB entry for {$session_id}, so email is only in wp_options.");
447 + }
448 +
449 + // Provide success response
450 + $bot_message = __('Thanks for providing your email! You can continue chatting now.', 'mxchat');
451 + //error_log("[DEBUG] handle_save_email_and_response -> success, returning bot_message: {$bot_message}");
452 + wp_send_json_success(['message' => $bot_message]);
453 + wp_die();
454 +}
455 +
456 +public function mxchat_check_email_provided() {
457 + //error_log('[DEBUG] ---------- mxchat_check_email_provided START ----------');
458 +
459 + if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_chat_nonce')) {
460 + //error_log('[ERROR] Invalid nonce in mxchat_check_email_provided');
461 + wp_send_json_error(['message' => esc_html__('Invalid nonce', 'mxchat')]);
462 + }
463 +
464 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
465 + if (empty($session_id)) {
466 + //error_log('[ERROR] No session ID provided in mxchat_check_email_provided');
467 + wp_send_json_error(['message' => esc_html__('No session ID provided', 'mxchat')]);
468 + }
469 +
470 + // Check if the user is logged in
471 + if (is_user_logged_in()) {
472 + $current_user = wp_get_current_user();
473 + //error_log("[DEBUG] User is logged in as {$current_user->user_email}");
474 + wp_send_json_success(['logged_in' => true, 'email' => $current_user->user_email]);
475 + }
476 +
477 + $option_key = "mxchat_email_{$session_id}";
478 + $stored_email = get_option($option_key, '');
479 +
480 + //error_log("[DEBUG] mxchat_check_email_provided -> Checking option: {$option_key}, found: {$stored_email}");
481 +
482 + if (!empty($stored_email)) {
483 + //error_log("[DEBUG] mxchat_check_email_provided -> Email found, returning success");
484 + wp_send_json_success(['email' => $stored_email]);
485 + } else {
486 + //error_log("[DEBUG] mxchat_check_email_provided -> No email found, returning error");
487 + wp_send_json_error(['message' => esc_html__('No email found', 'mxchat')]);
488 + }
489 +}
490 +
491 +// Add this to your plugin's main PHP file
492 +public function mxchat_check_new_messages() {
493 + if (!isset($_POST['session_id']) || !isset($_POST['last_seen_id'])) {
494 + wp_send_json_error(['message' => 'Missing required parameters']);
495 + wp_die();
496 + }
497 +
498 + $session_id = sanitize_text_field($_POST['session_id']);
499 + $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
500 +
501 + // Get chat history
502 + $history = get_option("mxchat_history_{$session_id}", []);
503 +
504 + if (empty($history)) {
505 + wp_send_json_success([
506 + 'hasNewMessages' => false,
507 + 'new_messages' => []
508 + ]);
509 + wp_die();
510 + }
511 +
512 + // Filter new messages
513 + $new_messages = array_filter($history, function($message) use ($last_seen_id) {
514 + return isset($message['id']) && $message['id'] > $last_seen_id;
515 + });
516 +
517 + // Sort by ID to ensure proper order
518 + usort($new_messages, function($a, $b) {
519 + return $a['id'] <=> $b['id'];
520 + });
521 +
522 + wp_send_json_success([
523 + 'hasNewMessages' => !empty($new_messages),
524 + 'new_messages' => array_values($new_messages),
525 + 'latestMessageId' => end($new_messages)['id'] ?? $last_seen_id
526 + ]);
527 + wp_die();
528 +}
529 +
530 +public function mxchat_handle_chat_request() {
531 + global $wpdb;
532 +
533 +
534 + // Check if MX Chat Moderation is active
535 + if (class_exists('MX_Chat_Moderation')) {
536 + // Get user email and IP
537 + $user_email = '';
538 + $user_ip = $_SERVER['REMOTE_ADDR'];
539 +
540 + // If user is logged in, get their email
541 + if (is_user_logged_in()) {
542 + $current_user = wp_get_current_user();
543 + $user_email = $current_user->user_email;
544 + }
545 +
546 + // Create ban handler instance
547 + $ban_handler = new MX_Chat_Ban_Handler();
548 +
549 + // Check if user is banned by IP
550 + if ($ban_handler->check_ban($user_ip, 'ip')) {
551 + wp_send_json([
552 + 'success' => false,
553 + 'message' => esc_html__('Access denied. Your IP address has been banned.', 'mxchat'),
554 + 'status' => 'banned'
555 + ]);
556 + wp_die();
557 + }
558 +
559 + // If user is logged in, also check email
560 + if (!empty($user_email) && $ban_handler->check_ban($user_email, 'email')) {
561 + wp_send_json([
562 + 'success' => false,
563 + 'message' => esc_html__('Access denied. Your email address has been banned.', 'mxchat'),
564 + 'status' => 'banned'
565 + ]);
566 + wp_die();
567 + }
568 + }
569 +
570 +$this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
571 +$this->productCardHtml = '';
572 +
573 +// Get the actual WordPress user ID if logged in
574 +$is_logged_in = is_user_logged_in();
575 +if ($is_logged_in) {
576 + $user_id = get_current_user_id(); // This will get the actual WordPress user ID
577 +} else {
578 + // For logged-out users, use your existing identifier method
579 + $user_id = $this->mxchat_get_user_identifier();
580 +}
581 +
582 +// Get and sanitize the user identifier
583 +$user_id = sanitize_key($user_id);
584 +
585 +// Check rate limit using new settings structure
586 +$rate_limit_result = $this->check_rate_limit();
587 +
588 +// Add this at the start of your rate limit checking in mxchat_handle_chat_request()
589 +//error_log('MXChat Rate Limit: Starting rate limit check in handle_chat_request()');
590 +
591 +// Then right after checking the result:
592 +if ($rate_limit_result !== true) {
593 + //error_log('MXChat Rate Limit: Rate limit exceeded, returning error');
594 + wp_send_json([
595 + 'success' => false,
596 + 'message' => $rate_limit_result['message'],
597 + 'status' => 'rate_limit_exceeded'
598 + ]);
599 + wp_die();
600 +} else {
601 + //error_log('MXChat Rate Limit: Check passed successfully');
602 +}
603 +
604 + // Rest of your existing code...
605 + $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
606 + //error_log("Session ID: $session_id");
607 +
608 + if (empty($session_id)) {
609 + //error_log("Error: Session ID is missing.");
610 + wp_send_json_error(esc_html__('Session ID is missing.', 'mxchat'));
611 + wp_die();
612 + }
613 +
614 + // Validate and sanitize the incoming message
615 + if (empty($_POST['message'])) {
616 + //error_log("Error: No message received.");
617 + wp_send_json_error(esc_html__('No message received.', 'mxchat'));
618 + wp_die();
619 + }
620 +
621 +
622 +// Modify the message sanitization to preserve PHP tags in code blocks
623 +$allowed_tags = [
624 + 'pre' => [],
625 + 'code' => ['class' => true],
626 + 'span' => ['class' => true],
627 + 'div' => ['class' => true],
628 +];
629 +
630 +// First preserve code blocks
631 +$message = preg_replace_callback('/<pre><code.*?>.*?<\/code><\/pre>/s', function($matches) {
632 + return htmlspecialchars_decode($matches[0]);
633 +}, $_POST['message']);
634 +
635 +// Then apply sanitization
636 +$message = wp_kses($message, $allowed_tags);
637 +
638 +// Decode code blocks
639 +$message = preg_replace_callback('/(&lt;pre&gt;&lt;code.*?&gt;.*?&lt;\/code&gt;&lt;\/pre&gt;)/s', function($matches) {
640 + return htmlspecialchars_decode($matches[1]);
641 +}, $message);
642 +
643 +$message = trim($message);
644 +
645 +// Preserve code blocks from markdown conversion
646 +$message = preg_replace('/```(\w+)?\s*([\s\S]+?)```/s', '<pre><code class="$1">$2</code></pre>', $message);
647 +
648 +// Check if any add-ons want to pre-process this message (for web search etc.)
649 +$pre_processed_result = apply_filters('mxchat_pre_process_message', $message, $user_id, $session_id);
650 +
651 +// If the pre-processing returned a result (not the original message), use it directly
652 +if (is_array($pre_processed_result) && isset($pre_processed_result['text'])) {
653 + // Save the AI response
654 + $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['text']);
655 +
656 + // Save HTML content if provided
657 + if (!empty($pre_processed_result['html'])) {
658 + $this->mxchat_save_chat_message($session_id, 'bot', $pre_processed_result['html']);
659 + }
660 +
661 + // Return the response
662 + wp_send_json([
663 + 'text' => $pre_processed_result['text'],
664 + 'html' => $pre_processed_result['html'] ?? '',
665 + 'session_id' => $session_id
666 + ]);
667 + wp_die();
668 +}
669 +
670 + // Save the user's message
671 + $this->mxchat_save_chat_message($session_id, 'user', $message);
672 +
673 + // Check if the message is an email address
674 + if (is_email($message)) {
675 + // Add the email to Loops
676 + $this->add_email_to_loops($message);
677 +
678 + // Send success response
679 + $response_message = $this->options['email_capture_response'] ??
680 + esc_html__('Thank you! Your coupon is on the way!', 'mxchat');
681 +
682 + wp_send_json([
683 + 'success' => true,
684 + 'status' => 'email_captured',
685 + 'message' => $response_message
686 + ]);
687 + wp_die();
688 + }
689 +
690 + $intent_info = '';
691 +
692 + // Check chat mode
693 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
694 + //error_log("Chat Mode: $chat_mode");
695 +
696 + // Handle agent mode
697 + if ($chat_mode === 'agent') {
698 + // First, check for switch intent before doing anything else
699 + $intent_matched = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
700 +
701 + // If we matched an intent and it's the switch intent, handle it
702 + if ($intent_matched && !empty($this->fallbackResponse['text'])) {
703 + //error_log("Switch to chatbot intent detected");
704 +
705 + // Update chat mode first
706 + update_option("mxchat_mode_{$session_id}", 'ai');
707 +
708 + // Clear any existing PDF context to start fresh
709 + $this->clear_pdf_transients($session_id);
710 +
711 + // Prepare clean switch response
712 + $response_data = [
713 + 'text' => $this->fallbackResponse['text'],
714 + 'html' => '',
715 + 'session_id' => $session_id,
716 + 'chat_mode' => 'ai'
717 + ];
718 +
719 + // Save the mode switch message
720 + $this->mxchat_save_chat_message($session_id, 'system', esc_html__('Switched to AI chat mode', 'mxchat'));
721 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['text']);
722 +
723 + // Send response and exit
724 + wp_send_json($response_data);
725 + wp_die();
726 + } elseif (!$intent_matched) {
727 + // No intent matched, handle live agent message
728 + try {
729 + $this->mxchat_send_user_message_to_agent($message, $user_id, $session_id);
730 + //error_log("Message sent to agent.");
731 +
732 + wp_send_json_success([
733 + 'status' => 'waiting_for_agent',
734 + 'message' => esc_html__('Message sent to live agent.', 'mxchat')
735 + ]);
736 + } catch (\Exception $e) {
737 + //error_log("Error sending message to agent: " . $e->getMessage());
738 + wp_send_json_error(esc_html__('Failed to send message to agent', 'mxchat'));
739 + }
740 + wp_die();
741 + }
742 + }
743 +
744 + // Step 1: Check for new PDF URL in the message
745 + if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
746 + $new_pdf_url = $matches[0];
747 +
748 + // Check if this is likely a PDF-related request
749 + $pdf_keywords = ['pdf', 'document', 'read', 'analyze'];
750 + $is_pdf_request = false;
751 +
752 + foreach ($pdf_keywords as $keyword) {
753 + if (stripos($message, $keyword) !== false) {
754 + $is_pdf_request = true;
755 + break;
756 + }
757 + }
758 +
759 + // If it looks like a PDF request or we're waiting for a PDF URL
760 + if ($is_pdf_request || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
761 + // Validate HTTPS
762 + if (wp_http_validate_url($new_pdf_url) && parse_url($new_pdf_url, PHP_URL_SCHEME) === 'https') {
763 + // Extract filename from URL
764 + $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
765 +
766 + // Clear previous PDF transients
767 + $this->clear_pdf_transients($session_id);
768 +
769 + // Process new PDF
770 + $max_pages = $this->options['pdf_max_pages'] ?? 69;
771 + $embeddings = $this->fetch_and_split_pdf_pages($new_pdf_url, $max_pages);
772 +
773 + if ($embeddings === 'too_many_pages') {
774 + $error_text = sprintf(
775 + $this->options['pdf_intent_error_text'] ??
776 + esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
777 + $max_pages
778 + );
779 + $this->fallbackResponse['text'] = $error_text;
780 + } elseif ($embeddings) {
781 + // Store new PDF information
782 + // Create a more meaningful filename from URL
783 + $pdf_filename = basename(parse_url($new_pdf_url, PHP_URL_PATH));
784 +
785 + // If the filename is generic (like results_download.php), create a more descriptive one
786 + if (in_array($pdf_filename, ['results_download.php', 'download.php', 'view.php', 'pdf.php']) ||
787 + strpos($pdf_filename, '.php') !== false) {
788 + // Create a timestamp-based name
789 + $pdf_filename = 'Document_' . date('Y-m-d_H-i') . '.pdf';
790 + }
791 +
792 + set_transient('mxchat_pdf_url_' . $session_id, $new_pdf_url, HOUR_IN_SECONDS);
793 + set_transient('mxchat_pdf_filename_' . $session_id, $pdf_filename, HOUR_IN_SECONDS);
794 + set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
795 + set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
796 +
797 + $success_text = $this->options['pdf_intent_success_text'] ??
798 + esc_html__("I've processed the new PDF '{$pdf_filename}'. What questions do you have about it?", 'mxchat');
799 +
800 + // Return success with filename for UI update
801 + wp_send_json([
802 + 'success' => true,
803 + 'message' => $success_text,
804 + 'data' => [
805 + 'filename' => $pdf_filename
806 + ]
807 + ]);
808 + wp_die();
809 + } else {
810 + $error_text = $this->options['pdf_intent_error_text'] ??
811 + esc_html__("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
812 + $this->fallbackResponse['text'] = $error_text;
813 + }
814 +
815 + wp_send_json([
816 + 'success' => false,
817 + 'message' => $this->fallbackResponse['text']
818 + ]);
819 + wp_die();
820 + }
821 + }
822 + }
823 +
824 +
825 +// Add this before the intent check section (before Step 2) in mxchat_handle_chat_request
826 +// Check if there's an active recommendation flow session
827 +$flow_state = get_option("mxchat_sr_flow_state_{$session_id}", array());
828 +if (!empty($flow_state) && isset($flow_state['flow_id'])) {
829 + //error_log('MXCHAT DEBUG: Detected active recommendation flow, routing directly');
830 +
831 + // Create a dummy intent object that matches the original intent
832 + $dummy_intent = new stdClass();
833 + $dummy_intent->intent_label = 'Recommendation Flow ' . $flow_state['flow_id'];
834 + $dummy_intent->phrases = ''; // Empty phrases to avoid matching the original trigger
835 +
836 + // Call the recommendation flow handler directly
837 + $response_data = apply_filters('mxchat_sr_recommendation_flow', false, $message, $user_id, $session_id, $dummy_intent);
838 +
839 + // If the handler returned a response, send it
840 + if (is_array($response_data) && (isset($response_data['text']) || isset($response_data['html']))) {
841 + // Save the bot's response to the chat history
842 + if (!empty($response_data['text'])) {
843 + $this->mxchat_save_chat_message($session_id, 'bot', $response_data['text']);
844 + }
845 + if (!empty($response_data['html'])) {
846 + $this->mxchat_save_chat_message($session_id, 'bot', $response_data['html']);
847 + }
848 +
849 + // Send the response
850 + wp_send_json($response_data);
851 + wp_die();
852 + }
853 +
854 + // If we reach here, the flow handler didn't provide a usable response
855 + // We'll continue with regular processing
856 + //error_log('MXCHAT DEBUG: Recommendation flow handler did not provide a usable response');
857 +}
858 +
859 + // Step 2: Detect intent and handle intent-based responses
860 +$intent_result = $this->mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id);
861 +//error_log("Intent Result Type: " . gettype($intent_result));
862 +
863 +// Step 3: Handle the intent result appropriately
864 +if ($intent_result !== false) {
865 + // The intent was matched and handled
866 + //error_log("Intent was matched and handled.");
867 +
868 + if (is_array($intent_result) && (isset($intent_result['text']) || isset($intent_result['html']))) {
869 + // Intent returned a direct response array
870 + //error_log("Intent returned a direct response.");
871 + $response_data = [
872 + 'text' => $intent_result['text'] ?? '',
873 + 'html' => $intent_result['html'] ?? '',
874 + 'session_id' => $session_id
875 + ];
876 +
877 + wp_send_json($response_data);
878 + wp_die();
879 + }
880 + else if ($intent_result === true && (!empty($this->fallbackResponse['text']) || !empty($this->fallbackResponse['html']))) {
881 + // Intent returned true and set fallbackResponse
882 + //error_log("Intent returned true with fallbackResponse set.");
883 + $response_data = [
884 + 'text' => $this->fallbackResponse['text'] ?? '',
885 + 'html' => $this->fallbackResponse['html'] ?? '',
886 + 'session_id' => $session_id
887 + ];
888 +
889 + wp_send_json($response_data);
890 + wp_die();
891 + }
892 +
893 + // Intent was matched but no usable response was provided
894 + // This shouldn't happen with proper intent implementation
895 + //error_log("Warning: Intent matched but no response provided.");
896 +}
897 +
898 + // If we get here, no intent matched OR the intent didn't provide a usable response
899 + //error_log("No matching intent or usable response. Generating AI response.");
900 +
901 + // Step 4: Generate AI response
902 + $conversation_history = $this->mxchat_fetch_conversation_history_for_ai($session_id);
903 + $this->mxchat_increment_chat_count();
904 +
905 + // Generate embedding for the user's query
906 + $user_message_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
907 +
908 + // Check if the embedding generation returned an error
909 + if (is_array($user_message_embedding) && isset($user_message_embedding['error'])) {
910 + $error_message = $user_message_embedding['error'];
911 + $error_code = $user_message_embedding['error_code'] ?? 'embedding_error';
912 +
913 + //error_log("Embedding error for session $session_id: $error_message (Code: $error_code)");
914 +
915 + // Important: Structure the error data correctly for wp_send_json_error
916 + wp_send_json_error([
917 + 'error_message' => $error_message,
918 + 'error_code' => $error_code
919 + ]);
920 + wp_die();
921 + }
922 +
923 + // Check if the embedding is valid
924 + if (!is_array($user_message_embedding) || empty($user_message_embedding)) {
925 + //error_log("Failed to generate message embedding for session $session_id");
926 + wp_send_json_error([
927 + 'error_message' => esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat'),
928 + 'error_code' => 'invalid_embedding'
929 + ]);
930 + wp_die();
931 + }
932 +
933 + // Build context with both knowledge base and PDF content if available
934 + $context_content = "User asked: '{$message}'\n\n";
935 +
936 +
937 + // Get relevant content from knowledge base
938 + $relevant_content = $this->mxchat_find_relevant_content($user_message_embedding);
939 + if (!empty($relevant_content)) {
940 + $context_content .= "Relevant content from knowledge database:\n" . $relevant_content . "\n\n";
941 + }
942 +
943 +
944 + // Check for and include PDF content
945 + $pdf_url = get_transient('mxchat_pdf_url_' . $session_id);
946 + $pdf_embeddings = get_transient('mxchat_pdf_embeddings_' . $session_id);
947 + $pdf_filename = get_transient('mxchat_pdf_filename_' . $session_id);
948 + if ($pdf_url && $pdf_embeddings && get_transient('mxchat_include_pdf_in_context_' . $session_id)) {
949 + $relevant_pdf_pages = $this->find_relevant_pdf_pages($user_message_embedding, $pdf_embeddings);
950 + if (!empty($relevant_pdf_pages)) {
951 + $context_content .= "Relevant content from PDF document '{$pdf_filename}':\n";
952 + foreach ($relevant_pdf_pages as $page_data) {
953 + $context_content .= "Page {$page_data['page_number']} of '{$pdf_filename}': {$page_data['text']}\n";
954 + }
955 + $context_content .= "\n";
956 + }
957 + }
958 +
959 + // Check for and include Word content
960 + $word_url = get_transient('mxchat_word_url_' . $session_id);
961 + $word_embeddings = get_transient('mxchat_word_embeddings_' . $session_id);
962 + $word_filename = get_transient('mxchat_word_filename_' . $session_id);
963 + if ($word_url && $word_embeddings && get_transient('mxchat_include_word_in_context_' . $session_id)) {
964 + $relevant_word_chunks = $this->word_handler->mxchat_find_relevant_word_chunks($user_message_embedding, $word_embeddings);
965 + if (!empty($relevant_word_chunks)) {
966 + $context_content .= "Relevant content from Word document '{$word_filename}':\n";
967 + foreach ($relevant_word_chunks as $chunk_data) {
968 + $context_content .= "Section {$chunk_data['chunk_number']} of '{$word_filename}': {$chunk_data['text']}\n";
969 + }
970 + $context_content .= "\n";
971 + }
972 + }
973 +
974 + $context_content = apply_filters('mxchat_prepare_context', $context_content, $session_id);
975 +
976 + // Generate the response using the full context
977 + $response = $this->mxchat_generate_response(
978 + $context_content,
979 + $this->options['api_key'],
980 + $this->options['xai_api_key'],
981 + $this->options['claude_api_key'],
982 + $this->options['deepseek_api_key'],
983 + $this->options['gemini_api_key'],
984 + $conversation_history
985 + );
986 +
987 + // Check if the response is an error array
988 + if (is_array($response) && isset($response['error'])) {
989 + //error_log("AI Response Error: " . $response['error'] . " (Code: " . ($response['error_code'] ?? 'unknown') . ")");
990 +
991 + // Send a user-friendly error message
992 + wp_send_json_error([
993 + 'error_message' => $response['error'],
994 + 'error_code' => $response['error_code'] ?? 'api_error'
995 + ]);
996 + wp_die();
997 + }
998 +
999 + // If we get here, the response is valid text
1000 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
1001 +
1002 + // Step 5: Save additional content if available
1003 + if (!empty($this->productCardHtml)) {
1004 + $this->mxchat_save_chat_message($session_id, 'bot', $this->productCardHtml);
1005 + }
1006 +
1007 + if (!empty($this->fallbackResponse['html'])) {
1008 + $this->mxchat_save_chat_message($session_id, 'bot', $this->fallbackResponse['html']);
1009 + }
1010 +
1011 + // Step 6: Return the response
1012 + $response_data = [
1013 + 'text' => $response,
1014 + 'html' => !empty($this->productCardHtml) ? $this->productCardHtml : ($this->fallbackResponse['html'] ?? ''),
1015 + 'session_id' => $session_id
1016 + ];
1017 +
1018 + wp_send_json($response_data);
1019 + wp_die();
1020 +}
1021 +
1022 +// Updated function to check intents and invoke the callback function
1023 +private function mxchat_check_intent_and_invoke_callback($message, $user_id, $session_id) {
1024 + global $wpdb;
1025 + $chat_mode = get_option("mxchat_mode_{$session_id}", 'ai');
1026 +
1027 + //error_log('🔍 MXCHAT DEBUG: Intent Check Started ==================');
1028 + //error_log("🔍 MXCHAT DEBUG: Message: '$message'");
1029 + //error_log("🔍 MXCHAT DEBUG: Chat Mode: $chat_mode");
1030 +
1031 + // Generate the user embedding
1032 + //error_log('🔄 MXCHAT DEBUG: Generating user embedding');
1033 + $user_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
1034 +
1035 + // Check if embedding generation returned an error
1036 + if (is_array($user_embedding) && isset($user_embedding['error'])) {
1037 + $error_message = $user_embedding['error'];
1038 + $error_code = $user_embedding['error_code'] ?? 'embedding_error';
1039 +
1040 + //error_log("❌ MXCHAT DEBUG: Embedding error: $error_message (Code: $error_code)");
1041 +
1042 + // Send the error to the frontend
1043 + wp_send_json_error([
1044 + 'error_message' => $error_message,
1045 + 'error_code' => $error_code
1046 + ]);
1047 + wp_die();
1048 + }
1049 +
1050 + // Check if embedding is valid (not an error and is an array)
1051 + if (!is_array($user_embedding) || empty($user_embedding)) {
1052 + //error_log('❌ MXCHAT DEBUG: Failed to generate user embedding');
1053 +
1054 + // Send a generic error to the frontend
1055 + wp_send_json_error([
1056 + 'error_message' => esc_html__('Unable to process your message. The embedding service is not responding correctly.', 'mxchat'),
1057 + 'error_code' => 'invalid_embedding'
1058 + ]);
1059 + wp_die();
1060 + }
1061 +
1062 + //error_log('✅ MXCHAT DEBUG: User embedding generated successfully');
1063 +
1064 + // Fetch intents from the database
1065 + $table_name = $wpdb->prefix . 'mxchat_intents';
1066 + if ($chat_mode === 'agent') {
1067 + //error_log('🔍 MXCHAT DEBUG: Agent mode - fetching only chatbot switch intent');
1068 + $query = $wpdb->prepare(
1069 + "SELECT * FROM $table_name WHERE callback_function = %s AND (enabled = 1 OR enabled IS NULL)",
1070 + 'mxchat_handle_switch_to_chatbot_intent'
1071 + );
1072 + $intents = $wpdb->get_results($query);
1073 + } else {
1074 + //error_log('🔍 MXCHAT DEBUG: AI mode - fetching all enabled intents');
1075 + // Only fetch enabled intents (either explicitly enabled with 1 or implicitly enabled with NULL for backward compatibility)
1076 + $intents = $wpdb->get_results("SELECT * FROM $table_name WHERE enabled = 1 OR enabled IS NULL");
1077 + }
1078 +
1079 + //error_log('🔍 MXCHAT DEBUG: Found ' . count($intents) . ' enabled intents to check');
1080 +
1081 + if (empty($intents)) {
1082 + //error_log('❌ MXCHAT DEBUG: No enabled intents found in database');
1083 + return false;
1084 + }
1085 +
1086 + $highest_similarity = -INF;
1087 + $matched_intent = null;
1088 +
1089 + //error_log('📊 MXCHAT DEBUG: Intent Similarity Scores ==================');
1090 + foreach ($intents as $intent) {
1091 + //error_log("🔄 MXCHAT DEBUG: Checking intent: '{$intent->intent_label}' (callback: {$intent->callback_function})");
1092 +
1093 + // Additional check for enabled state in case database structure was modified
1094 + $is_enabled = isset($intent->enabled) ? (bool)$intent->enabled : true;
1095 + if (!$is_enabled) {
1096 + //error_log("⚠️ MXCHAT DEBUG: Skipping disabled intent: {$intent->intent_label}");
1097 + continue;
1098 + }
1099 +
1100 + $intent_embedding_serialized = $intent->embedding_vector;
1101 + $intent_embedding = $intent_embedding_serialized
1102 + ? unserialize($intent_embedding_serialized, ['allowed_classes' => false])
1103 + : null;
1104 +
1105 + if (!is_array($intent_embedding)) {
1106 + //error_log("❌ MXCHAT DEBUG: Invalid embedding for intent: {$intent->intent_label}");
1107 + continue;
1108 + }
1109 +
1110 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $intent_embedding);
1111 + $intent_threshold = isset($intent->similarity_threshold) ? $intent->similarity_threshold : 0.85;
1112 +
1113 + //error_log("📊 MXCHAT DEBUG: Intent '{$intent->intent_label}' similarity: {$similarity}, threshold: {$intent_threshold}");
1114 +
1115 + if ($similarity >= $intent_threshold && $similarity > $highest_similarity) {
1116 + $highest_similarity = $similarity;
1117 + $matched_intent = $intent;
1118 + //error_log("✅ MXCHAT DEBUG: New best match: '{$intent->intent_label}' with similarity {$similarity}");
1119 + }
1120 + }
1121 + //error_log('📊 MXCHAT DEBUG: End Intent Scores ==================');
1122 +
1123 + if ($matched_intent) {
1124 + //error_log("🎯 MXCHAT DEBUG: Final Intent Match: '{$matched_intent->intent_label}'");
1125 + //error_log("🔄 MXCHAT DEBUG: Invoking callback: {$matched_intent->callback_function}");
1126 +
1127 + // If the callback is a method on this instance (core callback), call it directly
1128 + if (method_exists($this, $matched_intent->callback_function)) {
1129 + //error_log('🔍 MXCHAT DEBUG: Using direct method call for core callback');
1130 + $callback_result = call_user_func(
1131 + [$this, $matched_intent->callback_function],
1132 + $message,
1133 + $user_id,
1134 + $session_id,
1135 + $matched_intent,
1136 + $user_context
1137 + );
1138 + } else {
1139 + //error_log('🔍 MXCHAT DEBUG: Using apply_filters for add-on callback');
1140 + // Otherwise, use apply_filters for add-on callbacks
1141 + $callback_result = apply_filters(
1142 + $matched_intent->callback_function,
1143 + false, // default return value
1144 + $message,
1145 + $user_id,
1146 + $session_id,
1147 + $matched_intent
1148 + );
1149 + }
1150 +
1151 + //error_log('🔍 MXCHAT DEBUG: Callback result type: ' . gettype($callback_result));
1152 + if ($callback_result !== false) {
1153 + //error_log('✅ MXCHAT DEBUG: Intent handled successfully');
1154 + $this->fallbackResponse = $callback_result;
1155 + return true;
1156 + }
1157 + //error_log('❌ MXCHAT DEBUG: Callback returned false');
1158 + } else {
1159 + //error_log('❌ MXCHAT DEBUG: No matching intent found');
1160 + }
1161 +
1162 + //error_log('🔍 MXCHAT DEBUG: Intent Check Completed ==================');
1163 + return false;
1164 +}
1165 +
1166 +
1167 +
1168 +
1169 +// Helper function to clear PDF and Word document related transients
1170 +private function clear_pdf_transients($session_id) {
1171 + // PDF transients
1172 + delete_transient('mxchat_pdf_url_' . $session_id);
1173 + delete_transient('mxchat_pdf_embeddings_' . $session_id);
1174 + delete_transient('mxchat_include_pdf_in_context_' . $session_id);
1175 + delete_transient('mxchat_waiting_for_pdf_url_' . $session_id);
1176 +
1177 + // Word document transients
1178 + delete_transient('mxchat_word_url_' . $session_id);
1179 + delete_transient('mxchat_word_filename_' . $session_id);
1180 + delete_transient('mxchat_word_embeddings_' . $session_id);
1181 + delete_transient('mxchat_include_word_in_context_' . $session_id);
1182 + delete_transient('mxchat_waiting_for_word_' . $session_id);
1183 +}
1184 +
1185 +
1186 +
1187 +//verified good
1188 +public function mxchat_handle_email_capture($message, $user_id, $session_id) {
1189 + // Log the message safely
1190 + //error_log("Triggered email capture intent for message: " . sanitize_text_field($message));
1191 +
1192 + // Initiate email capture flow
1193 + $response = esc_html($this->options['triggered_phrase_response'] ?? esc_html__("Would you like to join our mailing list? Please provide your email below.", 'mxchat'));
1194 +
1195 + set_transient('mxchat_email_capture_' . $user_id, true, 5 * MINUTE_IN_SECONDS);
1196 + $this->mxchat_save_chat_message($session_id, 'bot', $response);
1197 +
1198 + // Respond to the user
1199 + wp_send_json(['message' => $response]);
1200 + wp_die();
1201 +}
1202 +
1203 +public function mxchat_generate_image($message, $user_id, $session_id) {
1204 + //error_log("Starting image generation for message: " . $message);
1205 +
1206 + // Prepare a prompt for DALL-E
1207 + $prompt = esc_html__('Create an image of ', 'mxchat') . sanitize_text_field($message);
1208 +
1209 + // Use the existing OpenAI API key
1210 + $openai_api_key = sanitize_text_field($this->options['api_key']);
1211 +
1212 + // Call DALL-E to generate an image
1213 + $image_response = $this->mxchat_generate_dalle_image($prompt, $openai_api_key);
1214 +
1215 + // Check if the response contains an image URL
1216 + if (isset($image_response['imageUrl'])) {
1217 + $image_url = esc_url_raw($image_response['imageUrl']);
1218 +
1219 + // Construct the HTML with a CSS class instead of inline styles
1220 + $response_html = '<img src="' . esc_url($image_url) . '" alt="' . esc_attr__('Generated Image', 'mxchat') . '" class="mxchat-generated-image" />';
1221 + $response_text = esc_html__('Here is the image I generated:', 'mxchat');
1222 +
1223 + // Save the bot message with both text and HTML
1224 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
1225 + $this->mxchat_save_chat_message($session_id, 'bot', $response_html);
1226 +
1227 + // Set the fallback response for the chat handler
1228 + $this->fallbackResponse = [
1229 + 'text' => $response_text,
1230 + 'html' => $response_html,
1231 + 'images' => [$image_url]
1232 + ];
1233 +
1234 + // For debugging/verification - Use json_encode to verify what's being set
1235 + //error_log("Image generation successful - fallbackResponse set: " . json_encode($this->fallbackResponse));
1236 +
1237 + // Return the response directly instead of relying on the property
1238 + return $this->fallbackResponse;
1239 + } else {
1240 + $response_text = esc_html__("I'm sorry, but I couldn't generate an image based on your request.", 'mxchat');
1241 +
1242 + // Save the error message
1243 + $this->mxchat_save_chat_message($session_id, 'bot', $response_text);
1244 +
1245 + // Set the fallback response for the chat handler
1246 + $this->fallbackResponse = [
1247 + 'text' => $response_text,
1248 + 'html' => '',
1249 + 'images' => []
1250 + ];
1251 +
1252 + //error_log("DALL-E image generation error: " . esc_html($image_response['error'] ?? 'Unknown error.'));
1253 + //error_log("Error fallbackResponse set: " . json_encode($this->fallbackResponse));
1254 +
1255 + // Return the response directly instead of relying on the property
1256 + return $this->fallbackResponse;
1257 + }
1258 +}
1259 +private function mxchat_generate_dalle_image($prompt, $api_key, $model = 'dall-e-3', $timeout = 60) {
1260 + $api_url = 'https://api.openai.com/v1/images/generations';
1261 + $body = json_encode([
1262 + 'prompt' => sanitize_text_field($prompt),
1263 + 'n' => 1,
1264 + 'size' => '1024x1024',
1265 + 'model' => sanitize_text_field($model),
1266 + ]);
1267 +
1268 + $args = [
1269 + 'body' => $body,
1270 + 'headers' => [
1271 + 'Content-Type' => 'application/json',
1272 + 'Authorization' => 'Bearer ' . sanitize_text_field($api_key),
1273 + ],
1274 + 'method' => 'POST',
1275 + 'timeout' => absint($timeout),
1276 + ];
1277 +
1278 + $response = wp_remote_post($api_url, $args);
1279 +
1280 + if (is_wp_error($response)) {
1281 + //error_log("DALL-E request failed: " . $response->get_error_message());
1282 + return ['error' => esc_html__('Error generating image: ', 'mxchat') . $response->get_error_message()];
1283 + }
1284 +
1285 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
1286 +
1287 + if (isset($response_body['data'][0]['url'])) {
1288 + return ['imageUrl' => esc_url_raw($response_body['data'][0]['url'])];
1289 + } else {
1290 + //error_log("DALL-E response error: " . wp_remote_retrieve_body($response));
1291 + return ['error' => esc_html__('Failed to generate image.', 'mxchat')];
1292 + }
1293 +}
1294 +
1295 +/**
1296 + * Handle web search requests.
1297 + *
1298 + * Sends the refined search query to the Brave Search API and uses the
1299 + * results to generate a conversational response with the AI model.
1300 + *
1301 + * @since 1.0.0
1302 + * @param string $message The user's search query.
1303 + * @param string $user_id The user identifier.
1304 + * @param string $session_id The current session ID.
1305 + * @return array Response array containing text with embedded HTML links
1306 + */
1307 +public function mxchat_handle_search_request($message, $user_id, $session_id) {
1308 + // Step 1: Interpret and refine the search query
1309 + $refined_search_query = $this->mxchat_interpret_search_query($message);
1310 + if (empty($refined_search_query)) {
1311 + return array(
1312 + 'text' => esc_html__('I apologize, but could you please rephrase your search request?', 'mxchat'),
1313 + 'html' => ''
1314 + );
1315 + }
1316 +
1317 + // Retrieve and validate API settings
1318 + $options = get_option('mxchat_options');
1319 + $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
1320 + $results_count = isset($options['brave_results_count']) ? absint($options['brave_results_count']) : 5;
1321 +
1322 + if (empty($api_key)) {
1323 + return array(
1324 + 'text' => esc_html__('Search functionality is temporarily unavailable. Please try again later.', 'mxchat'),
1325 + 'html' => ''
1326 + );
1327 + }
1328 +
1329 + // Build the API request URL
1330 + $api_url = add_query_arg(
1331 + array(
1332 + 'q' => rawurlencode($refined_search_query),
1333 + 'count' => $results_count,
1334 + 'text_decorations' => 'true',
1335 + 'rich_data' => 'true',
1336 + ),
1337 + 'https://api.search.brave.com/res/v1/web/search'
1338 + );
1339 +
1340 + // Attempt to retrieve cached results first
1341 + $transient_key = 'mxchat_search_' . md5($refined_search_query);
1342 + $results = get_transient($transient_key);
1343 +
1344 + if (false === $results) {
1345 + // Fetch new results from the Brave Search API
1346 + $response = wp_remote_get(
1347 + $api_url,
1348 + array(
1349 + 'headers' => array(
1350 + 'Accept' => 'application/json',
1351 + 'Accept-Encoding' => 'gzip',
1352 + 'X-Subscription-Token'=> $api_key,
1353 + ),
1354 + 'timeout' => 10,
1355 + )
1356 + );
1357 +
1358 + if (is_wp_error($response)) {
1359 + return array(
1360 + 'text' => esc_html__('I encountered an error while searching. Please try again.', 'mxchat'),
1361 + 'html' => ''
1362 + );
1363 + }
1364 +
1365 + $results = json_decode(wp_remote_retrieve_body($response), true);
1366 +
1367 + if (json_last_error() !== JSON_ERROR_NONE) {
1368 + return array(
1369 + 'text' => esc_html__('I received an invalid response from the search service.', 'mxchat'),
1370 + 'html' => ''
1371 + );
1372 + }
1373 +
1374 + // Cache results for one hour
1375 + set_transient($transient_key, $results, HOUR_IN_SECONDS);
1376 + }
1377 +
1378 + // Process results
1379 + if (!empty($results['web']['results']) && is_array($results['web']['results'])) {
1380 + // Create a more straightforward summary with HTML links
1381 + $search_results_text = '';
1382 +
1383 + // Add a simple intro
1384 + $search_results_text .= sprintf(
1385 + esc_html__("Here's what I found about '%s':", 'mxchat'),
1386 + esc_html($refined_search_query)
1387 + );
1388 +
1389 + // Add the top results with HTML links
1390 + foreach (array_slice($results['web']['results'], 0, 5) as $result) {
1391 + $title = isset($result['title']) ? wp_strip_all_tags($result['title']) : '';
1392 + $url = isset($result['url']) ? esc_url($result['url']) : '';
1393 + $description = isset($result['description']) ? wp_strip_all_tags($result['description']) : '';
1394 +
1395 + // Add a line break after the intro
1396 + $search_results_text .= '<br><br>';
1397 +
1398 + // Add title as a link
1399 + $search_results_text .= sprintf(
1400 + '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a><br>',
1401 + $url,
1402 + $title
1403 + );
1404 +
1405 + // Add a condensed description
1406 + $search_results_text .= sprintf("%s", $description);
1407 + }
1408 +
1409 + // Save to chat history
1410 + $this->mxchat_save_chat_message($session_id, 'bot', $search_results_text);
1411 +
1412 + // Return the formatted text with embedded HTML links
1413 + return array(
1414 + 'text' => $search_results_text,
1415 + 'html' => ''
1416 + );
1417 + } else {
1418 + return array(
1419 + 'text' => sprintf(
1420 + esc_html__('I searched for "%s" but couldn\'t find any relevant results. Would you like to try different search terms?', 'mxchat'),
1421 + esc_html($refined_search_query)
1422 + ),
1423 + 'html' => ''
1424 + );
1425 + }
1426 +}
1427 +/**
1428 + * Format search results into a natural text summary.
1429 + *
1430 + * @since 1.0.0
1431 + * @param array $results The search results from the API.
1432 + * @param string $query The original search query.
1433 + * @return string The text summary of the top results.
1434 + */
1435 +private function format_search_results( $results, $query ) {
1436 + $summary = sprintf(
1437 + esc_html__( 'Here are the most relevant results for "%s":', 'mxchat' ),
1438 + esc_html( $query )
1439 + ) . "\n\n";
1440 +
1441 + $max_results = min( count( $results ), 3 );
1442 + for ( $i = 0; $i < $max_results; $i++ ) {
1443 + $result = $results[ $i ];
1444 + $title = isset( $result['title'] ) ? wp_strip_all_tags( $result['title'] ) : '';
1445 + $description = isset( $result['description'] ) ? wp_strip_all_tags( $result['description'] ) : '';
1446 +
1447 + // Append title and description to the summary
1448 + $summary .= sprintf(
1449 + "%s\n%s\n\n",
1450 + esc_html( $title ),
1451 + esc_html( $description )
1452 + );
1453 + }
1454 +
1455 + return $summary;
1456 +}
1457 +
1458 +/**
1459 + * Generate HTML markup for search results.
1460 + *
1461 + * @since 1.0.0
1462 + * @param array $results The search results from the API.
1463 + * @param string $query The user-refined query.
1464 + * @return string The HTML markup for displaying the results.
1465 + */
1466 +private function generate_search_results_html( $results, $query ) {
1467 + ob_start();
1468 + ?>
1469 + <div class="mxchat-search-results">
1470 + <?php foreach ( $results as $result ) :
1471 + $title = isset( $result['title'] ) ? wp_strip_all_tags( $result['title'] ) : '';
1472 + $url = isset( $result['url'] ) ? esc_url( $result['url'] ) : '#';
1473 + $description = isset( $result['description'] ) ? wp_strip_all_tags( $result['description'] ) : '';
1474 + $favicon = isset( $result['meta_url']['favicon'] ) ? esc_url( $result['meta_url']['favicon'] ) : '';
1475 + $thumbnail = isset( $result['thumbnail']['src'] ) ? esc_url( $result['thumbnail']['src'] ) : '';
1476 + $domain = parse_url( $url, PHP_URL_HOST );
1477 + ?>
1478 + <div class="mxchat-search-item">
1479 + <div class="mxchat-search-header">
1480 + <?php if ( $favicon ) : ?>
1481 + <img
1482 + src="<?php echo esc_url( $favicon ); ?>"
1483 + class="mxchat-site-icon"
1484 + alt="<?php echo esc_attr__( 'Site icon', 'mxchat' ); ?>"
1485 + width="16"
1486 + height="16"
1487 + />
1488 + <?php endif; ?>
1489 + <div class="mxchat-site-url"><?php echo esc_html( $domain ); ?></div>
1490 + </div>
1491 +
1492 + <div class="mxchat-search-content">
1493 + <h3 class="mxchat-search-title">
1494 + <a href="<?php echo esc_url( $url ); ?>"
1495 + target="_blank"
1496 + rel="noopener noreferrer"
1497 + >
1498 + <?php echo esc_html( $title ); ?>
1499 + </a>
1500 + </h3>
1501 +
1502 + <?php if ( $thumbnail ) : ?>
1503 + <div class="mxchat-search-thumbnail">
1504 + <img
1505 + src="<?php echo esc_url( $thumbnail ); ?>"
1506 + alt="<?php echo esc_attr__( 'Thumbnail image', 'mxchat' ); ?>"
1507 + loading="lazy"
1508 + />
1509 + </div>
1510 + <?php endif; ?>
1511 +
1512 + <div class="mxchat-search-description">
1513 + <?php echo esc_html( $description ); ?>
1514 + </div>
1515 + </div>
1516 + </div>
1517 + <?php endforeach; ?>
1518 + </div>
1519 + <?php
1520 + return ob_get_clean();
1521 +}
1522 +
1523 +
1524 +//very good
1525 +public function mxchat_handle_image_search_request($message, $user_id, $session_id) {
1526 +
1527 + // Step 1: Interpret the search query for better results
1528 + $refined_search_query = $this->mxchat_interpret_search_query($message);
1529 +
1530 +
1531 + // If no query was interpreted, return a fallback message
1532 + if (empty($refined_search_query)) {
1533 + $this->fallbackResponse = [
1534 + 'text' => __("I'm sorry, I couldn't interpret your search query. Please specify what you'd like to see images of.", 'mxchat'),
1535 + 'html' => "",
1536 + ];
1537 + return;
1538 + }
1539 +
1540 + // Brave API URL
1541 + $api_url = 'https://api.search.brave.com/res/v1/images/search';
1542 +
1543 + // Retrieve Brave API settings
1544 + $options = get_option('mxchat_options');
1545 + $api_key = isset($options['brave_api_key']) ? sanitize_text_field($options['brave_api_key']) : '';
1546 +
1547 + if (empty($api_key)) {
1548 +/*
1549 + if (defined('WP_DEBUG') && WP_DEBUG) {
1550 + //error_log("Brave API key is missing.");
1551 + }
1552 +*/
1553 +
1554 + $this->fallbackResponse = [
1555 + 'text' => __("API key is not configured. Please set it in the Brave Search Settings.", 'mxchat'),
1556 + 'html' => "",
1557 + ];
1558 + return;
1559 + }
1560 +
1561 + $image_count = isset($options['brave_image_count']) ? intval($options['brave_image_count']) : 4;
1562 + $safe_search = isset($options['brave_safe_search']) ? sanitize_text_field($options['brave_safe_search']) : 'strict';
1563 +
1564 + // Append query parameters based on settings
1565 + $api_url = add_query_arg([
1566 + 'q' => rawurlencode($refined_search_query),
1567 + 'count' => $image_count,
1568 + 'safesearch' => $safe_search,
1569 + ], $api_url);
1570 +
1571 +/*
1572 + // Log the final API URL for the search
1573 + if (defined('WP_DEBUG') && WP_DEBUG) {
1574 + //error_log("Final API URL for Brave Image Search: " . esc_url_raw($api_url));
1575 + }
1576 +*/
1577 +
1578 +
1579 + // Implement caching
1580 + $transient_key = 'mxchat_image_search_' . md5($refined_search_query);
1581 + $body = get_transient($transient_key);
1582 +
1583 + if (false === $body) {
1584 + $args = [
1585 + 'headers' => [
1586 + 'Accept' => 'application/json',
1587 + 'Accept-Encoding' => 'gzip',
1588 + 'X-Subscription-Token' => $api_key,
1589 + ],
1590 + 'timeout' => 10,
1591 + ];
1592 +
1593 + $response = wp_remote_get($api_url, $args);
1594 +
1595 + if (is_wp_error($response)) {
1596 +/*
1597 + if (defined('WP_DEBUG') && WP_DEBUG) {
1598 + //error_log("Brave Image API request failed: " . $response->get_error_message());
1599 + }
1600 +*/
1601 +
1602 + $this->fallbackResponse = [
1603 + 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
1604 + 'html' => "",
1605 + ];
1606 + return;
1607 + }
1608 +
1609 + $body = json_decode(wp_remote_retrieve_body($response), true);
1610 + set_transient($transient_key, $body, HOUR_IN_SECONDS);
1611 + }
1612 +
1613 + // Process the API response
1614 + if (isset($body['results']) && is_array($body['results']) && count($body['results']) > 0) {
1615 + $html_output = '<div class="mxchat-image-gallery">';
1616 +
1617 + foreach ($body['results'] as $image) {
1618 + $image_url = isset($image['url']) ? esc_url($image['url']) : '';
1619 + $thumbnail_url = isset($image['thumbnail']['src']) ? esc_url($image['thumbnail']['src']) : '';
1620 + $title = isset($image['title']) ? esc_html($image['title']) : esc_html__('Image', 'mxchat');
1621 +
1622 + if ($image_url && $thumbnail_url) {
1623 + $html_output .= '<div class="mxchat-image-item">';
1624 + $html_output .= '<strong class="mxchat-image-title">' . $title . '</strong>';
1625 + $html_output .= '<a href="' . $image_url . '" target="_blank" rel="noopener noreferrer" class="mxchat-image-link">';
1626 + $html_output .= '<img src="' . $thumbnail_url . '" alt="' . $title . '" class="mxchat-image-thumbnail">';
1627 + $html_output .= '</a></div>';
1628 + }
1629 + }
1630 +
1631 + $html_output .= '</div>';
1632 +
1633 + $this->fallbackResponse = [
1634 + 'text' => "",
1635 + 'html' => $html_output,
1636 + ];
1637 +
1638 + // Save response in chat history
1639 + $this->mxchat_save_chat_message($session_id, 'bot', $html_output);
1640 +
1641 + } else {
1642 +/*
1643 + if (defined('WP_DEBUG') && WP_DEBUG) {
1644 + //error_log("Brave Image API response did not contain expected data structure or was empty: " . print_r($body, true));
1645 + }
1646 +*/
1647 +
1648 + $this->fallbackResponse = [
1649 + 'text' => __("I'm sorry, I couldn't retrieve any images based on your request.", 'mxchat'),
1650 + 'html' => "",
1651 + ];
1652 + }
1653 +}
1654 +public function mxchat_interpret_search_query($user_query) {
1655 + $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');
1656 +
1657 + // Retrieve OpenAI API key using 'api_key' as the option key
1658 + $api_key = isset($this->options['api_key']) ? sanitize_text_field($this->options['api_key']) : sanitize_text_field(get_option('mxchat_options')['api_key']);
1659 +
1660 + /*
1661 + // Log the API key check, without exposing the key
1662 + if (defined('WP_DEBUG') && WP_DEBUG) {
1663 + //error_log("Retrieved OpenAI API Key: " . ($api_key ? "Present" : "Missing"));
1664 + }
1665 + */
1666 +
1667 + if (empty($api_key)) {
1668 + //error_log("OpenAI API key is missing.");
1669 + return sanitize_text_field($user_query); // Default to the original query if API key is missing
1670 + }
1671 +
1672 + $url = 'https://api.openai.com/v1/chat/completions';
1673 + $args = [
1674 + 'headers' => [
1675 + 'Authorization' => 'Bearer ' . $api_key,
1676 + 'Content-Type' => 'application/json',
1677 + ],
1678 + 'body' => wp_json_encode([
1679 + 'model' => 'gpt-3.5-turbo',
1680 + 'messages' => [
1681 + ['role' => 'system', 'content' => $system_prompt],
1682 + ['role' => 'user', 'content' => sanitize_text_field($user_query)],
1683 + ],
1684 + 'temperature' => 0.2,
1685 + 'max_tokens' => 20,
1686 + ]),
1687 + 'method' => 'POST',
1688 + ];
1689 +
1690 + $response = wp_remote_post($url, $args);
1691 +
1692 + if (is_wp_error($response)) {
1693 + //error_log("OpenAI request failed: " . $response->get_error_message());
1694 + return sanitize_text_field($user_query); // Fallback to the original query if there's an error
1695 + }
1696 +
1697 + $body = json_decode(wp_remote_retrieve_body($response), true);
1698 +
1699 + // Check for a valid response and sanitize output
1700 + if (isset($body['choices'][0]['message']['content'])) {
1701 + $interpreted_query = sanitize_text_field(trim($body['choices'][0]['message']['content']));
1702 +
1703 + /*
1704 + // Log the interpreted query for debugging
1705 + if (defined('WP_DEBUG') && WP_DEBUG) {
1706 + //error_log("Interpreted search query: " . $interpreted_query);
1707 + }
1708 + */
1709 +
1710 + return $interpreted_query;
1711 + } else {
1712 + //error_log("Unexpected API response format: " . print_r($body, true));
1713 + return sanitize_text_field($user_query);
1714 + }
1715 +}
1716 +
1717 +
1718 +
1719 +private function find_product_in_message($message) {
1720 + global $wpdb;
1721 +
1722 + // Get embedding for the search query
1723 + $query_embedding = $this->mxchat_generate_embedding($message, $this->options['api_key']);
1724 +
1725 + // Check if embedding generation returned an error
1726 + if (is_array($query_embedding) && isset($query_embedding['error'])) {
1727 + $error_message = $query_embedding['error'];
1728 + $error_code = $query_embedding['error_code'] ?? 'embedding_error';
1729 +
1730 + //error_log("Product search embedding error: $error_message (Code: $error_code)");
1731 +
1732 + // Set a user-friendly fallback response
1733 + $this->fallbackResponse['text'] = esc_html__("I'm having trouble processing your product search. Please try again later or contact support if this persists.", 'mxchat');
1734 +
1735 + // Also store the technical error for admin users
1736 + $this->fallbackResponse['admin_error'] = $error_message;
1737 + $this->fallbackResponse['error_code'] = $error_code;
1738 +
1739 + return null;
1740 + }
1741 +
1742 + // Check if embedding is valid
1743 + if (!is_array($query_embedding) || empty($query_embedding)) {
1744 + //error_log("Failed to generate embedding for product search");
1745 + $this->fallbackResponse['text'] = esc_html__("I couldn't process your product search. Please try again with different wording.", 'mxchat');
1746 + return null;
1747 + }
1748 +
1749 + // Get relevant content as string
1750 + $relevant_content = $this->mxchat_find_relevant_products($query_embedding);
1751 + if (empty($relevant_content)) {
1752 + // Return null to indicate no results and set fallback response
1753 + $this->fallbackResponse['text'] = esc_html__("I couldn't find any relevant products based on your query. Could you please be more specific about the product you're looking for?", 'mxchat');
1754 + return null;
1755 + }
1756 +
1757 +
1758 + // Extract product URLs from the content
1759 + preg_match_all('/https?:\/\/[^\s<>"\']+?\/product\/[^\s<>"\']+/', $relevant_content, $matches);
1760 +
1761 + if (!empty($matches[0])) {
1762 + // Try each URL found
1763 + foreach ($matches[0] as $url) {
1764 + // Clean the URL
1765 + $url = rtrim($url, '/."\']');
1766 +
1767 + // Get the product slug
1768 + $path = parse_url($url, PHP_URL_PATH);
1769 + $slug = basename(rtrim($path, '/'));
1770 +
1771 + // Find product by slug
1772 + $args = array(
1773 + 'post_type' => 'product',
1774 + 'post_status' => 'publish',
1775 + 'name' => $slug,
1776 + 'posts_per_page' => 1
1777 + );
1778 +
1779 + $products = get_posts($args);
1780 +
1781 + if (!empty($products)) {
1782 + $product_id = $products[0]->ID;
1783 + $product = wc_get_product($product_id);
1784 +
1785 + if ($product && $product->is_purchasable()) {
1786 + return $product_id;
1787 + }
1788 + }
1789 + }
1790 + }
1791 +
1792 + // Fallback: Look for product names in the content
1793 + $products = wc_get_products([
1794 + 'status' => 'publish',
1795 + 'limit' => -1,
1796 + 'return' => 'all'
1797 + ]);
1798 +
1799 + foreach ($products as $product) {
1800 + $name = $product->get_name();
1801 + if (stripos($relevant_content, $name) !== false) {
1802 + if ($product->is_purchasable()) {
1803 + return $product->get_id();
1804 + }
1805 + }
1806 + }
1807 +
1808 + // If no product is found after all checks, set the fallback response
1809 + $this->fallbackResponse['text'] = esc_html__("I couldn't find any relevant products based on your query. Try to be more specific", 'mxchat');
1810 + return null;
1811 +}
1812 +
1813 +// New method to handle intent responses
1814 +private function generate_intent_response($context_content, $session_id) {
1815 + // Convert the context array to a structured string for the AI
1816 + $context_string = $this->format_intent_context($context_content);
1817 + // Generate AI response using the context
1818 + $response = $this->mxchat_generate_response(
1819 + $context_string,
1820 + $this->options['api_key'],
1821 + $this->options['xai_api_key'],
1822 + $this->options['claude_api_key'],
1823 + $this->options['deepseek_api_key'],
1824 + $this->options['gemini_api_key'], // Added Gemini API key
1825 + $this->mxchat_fetch_conversation_history_for_ai($session_id)
1826 + );
1827 + $this->fallbackResponse['text'] = $response;
1828 + return true;
1829 +}
1830 +
1831 +// Helper method to format intent context
1832 +private function format_intent_context($context) {
1833 + $context_string = esc_html__("INTENT CONTEXT:\n", 'mxchat');
1834 +
1835 + switch ($context['intent']) {
1836 + case 'add_to_cart':
1837 + if ($context['status'] === 'success') {
1838 + $context_string .= esc_html__("Action: Successfully added product to cart\n", 'mxchat');
1839 + $context_string .= sprintf(esc_html__("Product: %s\n", 'mxchat'), $context['product']['name']);
1840 + $context_string .= esc_html__("Available actions: ", 'mxchat') . implode(', ', $context['available_actions']) . "\n";
1841 + $context_string .= sprintf(esc_html__("Cart URL: %s\n", 'mxchat'), $context['cart_url']);
1842 + $context_string .= esc_html__("\nPlease inform the user of the successful addition and their available options.", 'mxchat');
1843 + } else {
1844 + $context_string .= esc_html__("Action: Failed to add product to cart\n", 'mxchat');
1845 + $context_string .= sprintf(esc_html__("Reason: %s\n", 'mxchat'), $context['reason']);
1846 + switch ($context['reason']) {
1847 + case 'woocommerce_not_available':
1848 + $context_string .= esc_html__("\nPlease inform the user that shopping features are not available.", 'mxchat');
1849 + break;
1850 + case 'no_product_context':
1851 + $context_string .= esc_html__("\nPlease ask the user to specify which product they want to add.", 'mxchat');
1852 + break;
1853 + case 'product_not_found':
1854 + $context_string .= esc_html__("\nPlease inform the user that the product couldn't be found and ask them to try again.", 'mxchat');
1855 + break;
1856 + case 'add_to_cart_failed':
1857 + $context_string .= esc_html__("\nPlease apologize to the user and suggest they try again or ask for assistance.", 'mxchat');
1858 + break;
1859 + }
1860 + }
1861 + break;
1862 + }
1863 +
1864 + return $context_string;
1865 +}
1866 +
1867 +
1868 +//very good
1869 +private function add_email_to_loops($email) {
1870 + // Sanitize the email
1871 + $email = sanitize_email($email);
1872 +
1873 + // Retrieve and sanitize options
1874 + $api_key = isset($this->options['loops_api_key']) ? sanitize_text_field($this->options['loops_api_key']) : '';
1875 + $mailing_list_id = isset($this->options['loops_mailing_list']) ? sanitize_text_field($this->options['loops_mailing_list']) : '';
1876 +
1877 + // Check for missing API key or mailing list ID
1878 + if (empty($api_key) || empty($mailing_list_id)) {
1879 + //error_log(esc_html__('Loops API key or mailing list ID is missing.', 'mxchat'));
1880 + return;
1881 + }
1882 +
1883 + $data = array(
1884 + 'email' => $email,
1885 + 'subscribed' => true,
1886 + 'source' => __('MxChat AI Chatbot', 'mxchat'),
1887 + 'mailingLists' => array($mailing_list_id => true),
1888 + );
1889 +
1890 + $url = 'https://app.loops.so/api/v1/contacts/create';
1891 + $args = array(
1892 + 'body' => wp_json_encode($data),
1893 + 'headers' => array(
1894 + 'Authorization' => 'Bearer ' . $api_key,
1895 + 'Content-Type' => 'application/json',
1896 + ),
1897 + 'method' => 'POST',
1898 + 'timeout' => 45,
1899 + );
1900 +
1901 + $response = wp_remote_post($url, $args);
1902 +
1903 + // Handle errors in the API request
1904 + if (is_wp_error($response)) {
1905 + //error_log(esc_html__('Error adding email to Loops: ', 'mxchat') . $response->get_error_message());
1906 + return;
1907 + }
1908 +
1909 + // Check for non-200 HTTP responses
1910 + $response_code = wp_remote_retrieve_response_code($response);
1911 + if ($response_code != 200) {
1912 + $response_body = wp_remote_retrieve_body($response);
1913 + //error_log(esc_html__('Loops API responded with code ', 'mxchat') . $response_code . ': ' . $response_body);
1914 + }
1915 +}
1916 +
1917 +public function mxchat_handle_pdf_discussion($message, $user_id, $session_id) {
1918 + // Get the maximum number of pages allowed from admin settings
1919 + $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
1920 +
1921 + // Retrieve options for dynamic texts
1922 + $trigger_text = $this->options['pdf_intent_trigger_text'] ?? __("Please provide the URL to the PDF you'd like to discuss.", 'mxchat');
1923 + $success_text = $this->options['pdf_intent_success_text'] ?? __("I've processed the PDF. What questions do you have about it?", 'mxchat');
1924 + $error_text = $this->options['pdf_intent_error_text'] ?? __("Sorry, I couldn't process the PDF. Please ensure it's a valid file.", 'mxchat');
1925 +
1926 + // Check for explicit request for new PDF
1927 + $new_pdf_requested = stripos($message, 'new') !== false ||
1928 + stripos($message, 'another') !== false ||
1929 + stripos($message, 'different') !== false;
1930 +
1931 + // If user mentions adding/reading a PDF, set waiting flag
1932 + if (stripos($message, 'pdf') !== false ||
1933 + stripos($message, 'document') !== false ||
1934 + stripos($message, 'read') !== false) {
1935 + set_transient('mxchat_waiting_for_pdf_url_' . $session_id, true, HOUR_IN_SECONDS);
1936 + $this->fallbackResponse['text'] = $trigger_text;
1937 + return;
1938 + }
1939 +
1940 + // If we're waiting for a URL or user requested new PDF
1941 + if ($new_pdf_requested || get_transient('mxchat_waiting_for_pdf_url_' . $session_id)) {
1942 + if (preg_match('/https?:\/\/[^\s"]+/i', $message, $matches)) {
1943 + // Process URL... (rest of your existing URL processing code)
1944 + } else {
1945 + $this->fallbackResponse['text'] = $trigger_text;
1946 + }
1947 + return;
1948 + }
1949 +
1950 + // Default to proceeding with conversation if no specific PDF action is needed
1951 + $this->fallbackResponse['text'] = '';
1952 +}
1953 +
1954 +
1955 +private function fetch_and_split_pdf_pages($pdf_source, $max_pages) {
1956 + $upload_dir = wp_upload_dir();
1957 + $temp_file = null;
1958 +
1959 + try {
1960 + // Handle URL vs local file
1961 + if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
1962 + // Validate and download the file from URL
1963 + $temp_file = wp_tempnam($pdf_source); // Safe temporary file name
1964 + $response = wp_remote_get($pdf_source, ['timeout' => 60]);
1965 +
1966 + if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
1967 + //error_log(esc_html__("Failed to download PDF. Error: ", 'mxchat') . print_r($response, true));
1968 + return false;
1969 + }
1970 +
1971 + file_put_contents($temp_file, wp_remote_retrieve_body($response));
1972 +
1973 + // Validate that the downloaded file is a PDF
1974 + $mime_type = mime_content_type($temp_file);
1975 + if ($mime_type !== 'application/pdf') {
1976 + //error_log(esc_html__("Invalid MIME type detected for PDF: ", 'mxchat') . $mime_type);
1977 + unlink($temp_file);
1978 + return false;
1979 + }
1980 + } else {
1981 + // For local files, use the provided path directly
1982 + $temp_file = $pdf_source;
1983 + }
1984 +
1985 + // Parse and process the PDF
1986 + $parser = new \Smalot\PdfParser\Parser();
1987 + $pdf = $parser->parseFile($temp_file);
1988 + $pages = $pdf->getPages();
1989 +
1990 + if (count($pages) > $max_pages) {
1991 + //error_log(esc_html__("PDF exceeds the maximum allowed pages: ", 'mxchat') . count($pages));
1992 + if (filter_var($pdf_source, FILTER_VALIDATE_URL)) {
1993 + unlink($temp_file);
1994 + }
1995 + return esc_html__('too_many_pages', 'mxchat');
1996 + }
1997 +
1998 + $embeddings = [];
1999 + foreach ($pages as $page_number => $page) {
2000 + $text = $page->getText();
2001 +
2002 + // Ensure text is non-empty before generating embeddings
2003 + if (empty(trim($text))) {
2004 + //error_log(esc_html__("Skipping empty page: ", 'mxchat') . ($page_number + 1));
2005 + continue;
2006 + }
2007 +
2008 + $embedding = $this->mxchat_generate_embedding(
2009 + esc_html__("Page ", 'mxchat') . ($page_number + 1) . ": " . $text,
2010 + $this->options['api_key']
2011 + );
2012 +
2013 + if ($embedding) {
2014 + $embeddings[] = [
2015 + 'page_number' => $page_number + 1,
2016 + 'embedding' => $embedding,
2017 + 'text' => $text,
2018 + ];
2019 + } else {
2020 + //error_log(esc_html__("Failed to generate embedding for page ", 'mxchat') . ($page_number + 1));
2021 + }
2022 + }
2023 +
2024 + // Clean up downloaded file if it was from URL
2025 + if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file) {
2026 + unlink($temp_file);
2027 + }
2028 +
2029 + return $embeddings;
2030 +
2031 + } catch (\Exception $e) {
2032 + // //error_log(esc_html__("Error parsing or processing PDF: ", 'mxchat') . $e->getMessage());
2033 +
2034 + // Cleanup in case of exception
2035 + if (filter_var($pdf_source, FILTER_VALIDATE_URL) && $temp_file && file_exists($temp_file)) {
2036 + unlink($temp_file);
2037 + }
2038 +
2039 + return false;
2040 + }
2041 +}
2042 +private function find_relevant_pdf_pages($query_embedding, $embeddings) {
2043 + //error_log(esc_html__("find_relevant_pdf_pages called.", 'mxchat'));
2044 +
2045 + $most_relevant = null;
2046 + $highest_similarity = -INF;
2047 +
2048 + foreach ($embeddings as $page_data) {
2049 + $similarity = $this->mxchat_calculate_cosine_similarity($query_embedding, $page_data['embedding']);
2050 +
2051 + if ($similarity > $highest_similarity) {
2052 + $highest_similarity = $similarity;
2053 + $most_relevant = $page_data['page_number'];
2054 + }
2055 + }
2056 +
2057 + if (!is_null($most_relevant)) {
2058 + $page_numbers = range(max(1, $most_relevant - 1), min(count($embeddings), $most_relevant + 1));
2059 + return array_filter($embeddings, function ($page) use ($page_numbers) {
2060 + return in_array($page['page_number'], $page_numbers);
2061 + });
2062 + }
2063 +
2064 + return [];
2065 +}
2066 +// Add this to your class
2067 +public function handle_pdf_upload() {
2068 + check_ajax_referer('mxchat_chat_nonce', 'nonce');
2069 +
2070 + if (!isset($_FILES['pdf_file']) || !isset($_POST['session_id'])) {
2071 + wp_send_json_error(esc_html__('Missing required parameters.', 'mxchat'));
2072 + return;
2073 + }
2074 +
2075 + $file = $_FILES['pdf_file'];
2076 + $session_id = sanitize_text_field($_POST['session_id']);
2077 + $original_filename = sanitize_text_field($file['name']);
2078 +
2079 + $file_type = wp_check_filetype($file['name'], ['pdf' => 'application/pdf']);
2080 + if ($file_type['type'] !== 'application/pdf') {
2081 + wp_send_json_error(esc_html__('Invalid file type. Only PDF files are allowed.', 'mxchat'));
2082 + return;
2083 + }
2084 +
2085 + $upload_dir = wp_upload_dir();
2086 + $pdf_filename = 'mxchat_' . $session_id . '_' . time() . '.pdf';
2087 + $pdf_path = $upload_dir['path'] . '/' . $pdf_filename;
2088 +
2089 + if (!move_uploaded_file($file['tmp_name'], $pdf_path)) {
2090 + wp_send_json_error(esc_html__('Failed to upload file.', 'mxchat'));
2091 + return;
2092 + }
2093 +
2094 + $this->clear_pdf_transients($session_id);
2095 +
2096 + $max_pages = isset($this->options['pdf_max_pages']) ? intval($this->options['pdf_max_pages']) : 69;
2097 + $embeddings = $this->fetch_and_split_pdf_pages($pdf_path, $max_pages);
2098 +
2099 + if ($embeddings === 'too_many_pages') {
2100 + unlink($pdf_path);
2101 + $error_message = sprintf(
2102 + $this->options['pdf_intent_error_text'] ??
2103 + esc_html__("The provided PDF exceeds the maximum allowed limit of %d pages. Please provide a smaller document.", 'mxchat'),
2104 + $max_pages
2105 + );
2106 + wp_send_json_error($error_message);
2107 + return;
2108 + }
2109 +
2110 + if ($embeddings === false || empty($embeddings)) {
2111 + unlink($pdf_path);
2112 + $error_message = $this->options['pdf_intent_error_text'] ??
2113 + esc_html__('The uploaded PDF appears to be empty or contains unsupported content.', 'mxchat');
2114 + wp_send_json_error($error_message);
2115 + return;
2116 + }
2117 +
2118 + if (!empty($embeddings)) {
2119 + set_transient('mxchat_pdf_url_' . $session_id, $pdf_path, HOUR_IN_SECONDS);
2120 + set_transient('mxchat_pdf_filename_' . $session_id, $original_filename, HOUR_IN_SECONDS);
2121 + set_transient('mxchat_pdf_embeddings_' . $session_id, $embeddings, HOUR_IN_SECONDS);
2122 + set_transient('mxchat_include_pdf_in_context_' . $session_id, true, HOUR_IN_SECONDS);
2123 +
2124 + $success_message = $this->options['pdf_intent_success_text'] ??
2125 + esc_html__("I've processed the PDF. What questions do you have about it?", 'mxchat');
2126 +
2127 + wp_send_json_success([
2128 + 'message' => $success_message,
2129 + 'filename' => $original_filename
2130 + ]);
2131 + return;
2132 + }
2133 +
2134 + unlink($pdf_path);
2135 + $error_message = $this->options['pdf_intent_error_text'] ??
2136 + esc_html__('Sorry, I couldn\'t process the PDF. Please ensure it\'s a valid file.', 'mxchat');
2137 + wp_send_json_error($error_message);
2138 + return;
2139 +}
2140 +public function handle_pdf_remove() {
2141 + check_ajax_referer('mxchat_chat_nonce', 'nonce');
2142 +
2143 + if (empty($_POST['session_id'])) {
2144 + wp_send_json_error(esc_html__('Session ID missing.', 'mxchat'));
2145 + wp_die();
2146 + }
2147 +
2148 + $session_id = sanitize_text_field($_POST['session_id']);
2149 + $pdf_path = get_transient('mxchat_pdf_url_' . $session_id);
2150 +
2151 + if ($pdf_path && file_exists($pdf_path)) {
2152 + unlink($pdf_path);
2153 + }
2154 +
2155 + $this->clear_pdf_transients($session_id);
2156 +
2157 + wp_send_json_success([
2158 + 'message' => esc_html__('PDF removed successfully.', 'mxchat')
2159 + ]);
2160 + wp_die();
2161 +}
2162 +
2163 +
2164 +
2165 +
2166 +function mxchat_fetch_new_messages() {
2167 + $session_id = sanitize_text_field($_POST['session_id']);
2168 + $last_seen_id = sanitize_text_field($_POST['last_seen_id']);
2169 + $persistence_enabled = $_POST['persistence_enabled'] === 'true';
2170 + $initial_timestamp = isset($_POST['initial_timestamp']) ? intval($_POST['initial_timestamp']) : 0;
2171 +
2172 + if (empty($session_id)) {
2173 + //error_log(esc_html__('Fetch new messages error: Session ID missing.', 'mxchat'));
2174 + wp_send_json_error(['message' => esc_html__('Session ID missing.', 'mxchat')]);
2175 + wp_die();
2176 + }
2177 +
2178 + $history = get_option("mxchat_history_{$session_id}", []);
2179 +
2180 + $new_messages = array_filter($history, function ($message) use ($last_seen_id, $persistence_enabled, $initial_timestamp) {
2181 + // If persistence is enabled, show all new messages
2182 + if ($persistence_enabled) {
2183 + return !empty($message['id']) &&
2184 + strcmp($message['id'], $last_seen_id) > 0 &&
2185 + $message['role'] === 'agent';
2186 + }
2187 +
2188 + // If persistence is disabled, only show messages after initial timestamp
2189 + return !empty($message['id']) &&
2190 + $message['role'] === 'agent' &&
2191 + $message['timestamp'] > $initial_timestamp;
2192 + });
2193 +
2194 + //error_log(esc_html__("New agent messages fetched for session $session_id. Last seen ID: $last_seen_id", 'mxchat'));
2195 +
2196 + wp_send_json_success([
2197 + 'new_messages' => array_values($new_messages)
2198 + ]);
2199 + wp_die();
2200 +}
2201 +
2202 +
2203 +public function mxchat_live_agent_handover($message, $user_id, $session_id) {
2204 + // First check if live agents are available
2205 + $live_agent_available = $this->options['live_agent_status'] ?? 'off';
2206 + if ($live_agent_available !== 'on') {
2207 + $away_message = $this->options['live_agent_away_message'] ?? 'Sorry, live agents are currently unavailable. I can continue helping you as an AI assistant.';
2208 + $this->fallbackResponse = [
2209 + 'text' => $away_message,
2210 + 'html' => '',
2211 + 'images' => [],
2212 + 'chat_mode' => 'ai'
2213 + ];
2214 + wp_send_json([
2215 + 'text' => $away_message,
2216 + 'html' => '',
2217 + 'chat_mode' => 'ai',
2218 + 'session_id' => $session_id
2219 + ]);
2220 + wp_die();
2221 + }
2222 +
2223 + $slack_webhook_url = $this->options['live_agent_webhook_url'] ?? '';
2224 + if (empty($slack_webhook_url)) {
2225 + return false;
2226 + }
2227 +
2228 + // Get recent chat history (last 5 messages)
2229 + $history = get_option("mxchat_history_{$session_id}", []);
2230 + $recent_history = array_slice($history, -5); // Get last 5 messages
2231 +
2232 + // Format conversation history
2233 + $conversation_context = "";
2234 + if (!empty($recent_history)) {
2235 + $conversation_context = "*Recent Conversation:*\n";
2236 + foreach ($recent_history as $hist_message) {
2237 + $role_display = $hist_message['role'] === 'user' ? 'User' : 'AI';
2238 + $conversation_context .= ">{$role_display}: {$hist_message['content']}\n";
2239 + }
2240 + $conversation_context .= "\n";
2241 + }
2242 +
2243 + update_option("mxchat_mode_{$session_id}", 'agent');
2244 +
2245 + $webhook_data = [
2246 + 'blocks' => [
2247 + [
2248 + 'type' => 'header',
2249 + 'text' => [
2250 + 'type' => 'plain_text',
2251 + 'text' => '🔔 New Live Agent Request',
2252 + 'emoji' => true
2253 + ]
2254 + ],
2255 + [
2256 + 'type' => 'section',
2257 + 'fields' => [
2258 + [
2259 + 'type' => 'mrkdwn',
2260 + 'text' => sprintf('*User ID:*\n`%s`', $user_id)
2261 + ],
2262 + [
2263 + 'type' => 'mrkdwn',
2264 + 'text' => sprintf('*Session ID:*\n`%s`', $session_id)
2265 + ]
2266 + ]
2267 + ]
2268 + ]
2269 + ];
2270 +
2271 + // Add conversation history if exists
2272 + if (!empty($conversation_context)) {
2273 + $webhook_data['blocks'][] = [
2274 + 'type' => 'section',
2275 + 'text' => [
2276 + 'type' => 'mrkdwn',
2277 + 'text' => $conversation_context
2278 + ]
2279 + ];
2280 + }
2281 +
2282 + // Add the current message
2283 + $webhook_data['blocks'][] = [
2284 + 'type' => 'section',
2285 + 'text' => [
2286 + 'type' => 'mrkdwn',
2287 + 'text' => sprintf('*Current Message:*\n%s', $message)
2288 + ]
2289 + ];
2290 +
2291 + // Add the reply button
2292 + $webhook_data['blocks'][] = [
2293 + 'type' => 'actions',
2294 + 'elements' => [
2295 + [
2296 + 'type' => 'button',
2297 + 'text' => [
2298 + 'type' => 'plain_text',
2299 + 'text' => '✍️ Reply',
2300 + 'emoji' => true
2301 + ],
2302 + 'value' => $session_id,
2303 + 'action_id' => 'reply_to_user',
2304 + 'style' => 'primary'
2305 + ]
2306 + ]
2307 + ];
2308 +
2309 + $response = wp_remote_post($slack_webhook_url, [
2310 + 'body' => json_encode($webhook_data),
2311 + 'headers' => [
2312 + 'Content-Type' => 'application/json',
2313 + ],
2314 + ]);
2315 +
2316 + if (is_wp_error($response)) {
2317 + return false;
2318 + }
2319 +
2320 + $success_message = $this->options['live_agent_notification_message'] ?? 'Live agent has been notified.';
2321 + $this->mxchat_save_chat_message($session_id, 'bot', $success_message);
2322 +
2323 + $this->fallbackResponse = [
2324 + 'text' => $success_message,
2325 + 'html' => '',
2326 + 'images' => [],
2327 + 'chat_mode' => 'agent'
2328 + ];
2329 +
2330 + wp_send_json([
2331 + 'success' => true,
2332 + 'text' => $success_message,
2333 + 'html' => '',
2334 + 'chat_mode' => 'agent',
2335 + 'session_id' => $session_id,
2336 + 'fallbackResponse' => $this->fallbackResponse
2337 + ]);
2338 + wp_die();
2339 +}
2340 +public function mxchat_send_user_message_to_agent($message, $user_id, $session_id) {
2341 + $slack_webhook_url = $this->options['live_agent_webhook_url'] ?? '';
2342 +
2343 + if (empty($slack_webhook_url)) {
2344 + //error_log(esc_html__('Slack Webhook URL is not configured.', 'mxchat'));
2345 + return false;
2346 + }
2347 +
2348 + $webhook_data = [
2349 + 'blocks' => [
2350 + [
2351 + 'type' => 'header',
2352 + 'text' => [
2353 + 'type' => 'plain_text',
2354 + 'text' => esc_html__('📩 New Chat Message', 'mxchat'),
2355 + 'emoji' => true
2356 + ]
2357 + ],
2358 + [
2359 + 'type' => 'section',
2360 + 'fields' => [
2361 + [
2362 + 'type' => 'mrkdwn',
2363 + 'text' => sprintf(esc_html__('*User ID:*\n`%s`', 'mxchat'), $user_id)
2364 + ],
2365 + [
2366 + 'type' => 'mrkdwn',
2367 + 'text' => sprintf(esc_html__('*Session ID:*\n`%s`', 'mxchat'), $session_id)
2368 + ]
2369 + ]
2370 + ],
2371 + [
2372 + 'type' => 'section',
2373 + 'text' => [
2374 + 'type' => 'mrkdwn',
2375 + 'text' => sprintf(esc_html__('*Message:*\n%s', 'mxchat'), $message)
2376 + ]
2377 + ],
2378 + [
2379 + 'type' => 'actions',
2380 + 'elements' => [
2381 + [
2382 + 'type' => 'button',
2383 + 'text' => [
2384 + 'type' => 'plain_text',
2385 + 'text' => esc_html__('✍️ Reply', 'mxchat'),
2386 + 'emoji' => true
2387 + ],
2388 + 'value' => $session_id,
2389 + 'action_id' => 'reply_to_user',
2390 + 'style' => 'primary'
2391 + ]
2392 + ]
2393 + ]
2394 + ]
2395 + ];
2396 +
2397 + $response = wp_remote_post($slack_webhook_url, [
2398 + 'body' => json_encode($webhook_data),
2399 + 'headers' => [
2400 + 'Content-Type' => 'application/json',
2401 + ],
2402 + ]);
2403 +
2404 + if (is_wp_error($response)) {
2405 + //error_log(esc_html__('Error sending message to Slack: ', 'mxchat') . $response->get_error_message());
2406 + return false;
2407 + }
2408 +
2409 + //error_log(esc_html__('Message sent to Slack successfully.', 'mxchat'));
2410 + return true;
2411 +}
2412 +public function handle_slack_interaction(WP_REST_Request $request) {
2413 + //error_log('Received Slack interaction');
2414 +
2415 + $payload = json_decode($request->get_param('payload'), true);
2416 + //error_log('Payload: ' . print_r($payload, true));
2417 +
2418 + // Handle button click
2419 + if ($payload['type'] === 'block_actions' && $payload['actions'][0]['action_id'] === 'reply_to_user') {
2420 + $session_id = $payload['actions'][0]['value'];
2421 + $trigger_id = $payload['trigger_id'];
2422 +
2423 + // Get Bot Token from settings
2424 + $slack_token = $this->options['live_agent_bot_token'] ?? '';
2425 +
2426 + if (empty($slack_token)) {
2427 + //error_log('Slack Bot Token not configured');
2428 + return new WP_REST_Response(['error' => esc_html__('Bot token not configured', 'mxchat')], 400);
2429 + }
2430 + $response = wp_remote_post('https://slack.com/api/views.open', [
2431 + 'headers' => [
2432 + 'Content-Type' => 'application/json',
2433 + 'Authorization' => 'Bearer ' . $slack_token
2434 + ],
2435 + 'body' => json_encode([
2436 + 'trigger_id' => $trigger_id,
2437 + 'view' => [
2438 + 'type' => 'modal',
2439 + 'callback_id' => 'reply_modal',
2440 + 'title' => [
2441 + 'type' => 'plain_text',
2442 + 'text' => __('Reply to User', 'mxchat')
2443 + ],
2444 + 'submit' => [
2445 + 'type' => 'plain_text',
2446 + 'text' => __('Send', 'mxchat')
2447 + ],
2448 + 'close' => [
2449 + 'type' => 'plain_text',
2450 + 'text' => __('Cancel', 'mxchat')
2451 + ],
2452 + 'blocks' => [
2453 + [
2454 + 'type' => 'input',
2455 + 'block_id' => 'reply_block',
2456 + 'label' => [
2457 + 'type' => 'plain_text',
2458 + 'text' => sprintf(__('Reply to session: %s', 'mxchat'), $session_id)
2459 + ],
2460 + 'element' => [
2461 + 'type' => 'plain_text_input',
2462 + 'action_id' => 'message',
2463 + 'multiline' => true,
2464 + 'placeholder' => [
2465 + 'type' => 'plain_text',
2466 + 'text' => __('Type your message here...', 'mxchat')
2467 + ]
2468 + ]
2469 + ]
2470 + ],
2471 + 'private_metadata' => $session_id
2472 + ]
2473 + ])
2474 + ]);
2475 +
2476 + //error_log('Views.open response: ' . print_r($response, true));
2477 +
2478 + // Return immediate acknowledgment
2479 + return new WP_REST_Response(['ok' => true]);
2480 + }
2481 +
2482 + // Handle modal submission
2483 +// Handle modal submission
2484 +if ($payload['type'] === 'view_submission') {
2485 + $session_id = $payload['view']['private_metadata'];
2486 + $message = $payload['view']['state']['values']['reply_block']['message']['value'];
2487 +
2488 + // Save the message (keep the message_id but don't include in response)
2489 + $this->mxchat_save_chat_message($session_id, 'agent', $message);
2490 +
2491 + // Keep the original response format for Slack
2492 + return new WP_REST_Response([
2493 + 'response_action' => 'clear'
2494 + ]);
2495 +}
2496 +
2497 + // Default acknowledgment
2498 + return new WP_REST_Response(['ok' => true]);
2499 +}
2500 +
2501 +public function mxchat_handle_agent_response(WP_REST_Request $request) {
2502 + //error_log('Received agent response request');
2503 + //error_log('Request data: ' . print_r($request->get_params(), true));
2504 + // //error_log('Raw body: ' . file_get_contents('php://input'));
2505 +
2506 + // Get the data from Slack's slash command format
2507 + $command_text = $request->get_param('text');
2508 + // //error_log('Command text: ' . $command_text);
2509 +
2510 + if (empty($command_text)) {
2511 + //error_log(esc_html__('Agent response error: No command text received', 'mxchat'));
2512 + return new WP_REST_Response([
2513 + 'error' => esc_html__('Command text is required. Format: /reply session_id message', 'mxchat')
2514 + ], 400);
2515 + }
2516 +
2517 + // Split the command text into session_id and message
2518 + $parts = explode(' ', $command_text, 2);
2519 + if (count($parts) !== 2) {
2520 + //error_log('Agent response error: Invalid command format');
2521 + return new WP_REST_Response([
2522 + 'error' => esc_html__('Invalid format. Use: /reply session_id message', 'mxchat')
2523 + ], 400);
2524 + }
2525 +
2526 + $session_id = sanitize_text_field($parts[0]);
2527 + $message = sanitize_text_field($parts[1]);
2528 +
2529 + //error_log("Processing agent response - Session ID: $session_id, Message: $message");
2530 +
2531 + // Save the message
2532 + $message_id = $this->mxchat_save_chat_message($session_id, 'agent', $message);
2533 +
2534 + if (!$message_id) {
2535 + // //error_log('Failed to save agent message');
2536 + return new WP_REST_Response([
2537 + 'error' => esc_html__('Failed to save message', 'mxchat')
2538 + ], 500);
2539 + }
2540 +
2541 + // Return success response in Slack's expected format
2542 + return new WP_REST_Response([
2543 + 'response_type' => 'in_channel',
2544 + 'text' => esc_html__("Message sent successfully to session $session_id", 'mxchat')
2545 + ], 200);
2546 +}
2547 +
2548 +
2549 +public function mxchat_handle_switch_to_chatbot_intent($message, $user_id, $session_id) {
2550 + //error_log(esc_html__("Switching back to chatbot mode via intent.", 'mxchat'));
2551 +
2552 + // Just update mode to AI
2553 + update_option("mxchat_mode_{$session_id}", 'ai');
2554 +
2555 + // Initialize states
2556 + $this->fallbackResponse = ['text' => '', 'html' => '', 'images' => []];
2557 + $this->productCardHtml = '';
2558 +
2559 + // Set the response message
2560 + $this->fallbackResponse['text'] = esc_html__('You are now chatting with the AI chatbot.', 'mxchat');
2561 +
2562 + return true; // Intent was handled
2563 +}
2564 +
2565 +
2566 +
2567 +
2568 +// For the word upload handler
2569 +public function mxchat_handle_word_upload() {
2570 + // Delegate to word handler
2571 + $this->word_handler->mxchat_handle_word_upload();
2572 +}
2573 +
2574 +// For the word removal handler
2575 +public function mxchat_handle_word_remove() {
2576 + // Delegate to word handler
2577 + $this->word_handler->mxchat_handle_word_remove();
2578 +}
2579 +
2580 +// For the word status check
2581 +public function mxchat_check_word_status() {
2582 + // Delegate to word handler
2583 + $this->word_handler->mxchat_check_word_status();
2584 +}
2585 +
2586 +
2587 +private function mxchat_get_user_identifier() {
2588 + return MxChat_User::mxchat_get_user_identifier();
2589 +}
2590 +
2591 +private function mxchat_generate_embedding($text, $api_key) {
2592 + try {
2593 + // Get options and selected model
2594 + $options = get_option('mxchat_options');
2595 + $selected_model = $options['embedding_model'] ?? 'text-embedding-ada-002';
2596 +
2597 + // Determine endpoint and API key based on model
2598 + if (strpos($selected_model, 'voyage') === 0) {
2599 + $endpoint = 'https://api.voyageai.com/v1/embeddings';
2600 + $api_key = $options['voyage_api_key'] ?? '';
2601 +
2602 + // Check if Voyage API key is missing
2603 + if (empty($api_key)) {
2604 + //error_log('Voyage API key is missing');
2605 + return [
2606 + 'error' => esc_html__('Voyage AI API key is not configured', 'mxchat'),
2607 + 'error_code' => 'missing_voyage_api_key'
2608 + ];
2609 + }
2610 + } else {
2611 + $endpoint = 'https://api.openai.com/v1/embeddings';
2612 + // Use the passed API key for OpenAI
2613 +
2614 + // Check if OpenAI API key is missing
2615 + if (empty($api_key)) {
2616 + //error_log('OpenAI API key is missing');
2617 + return [
2618 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
2619 + 'error_code' => 'missing_openai_api_key'
2620 + ];
2621 + }
2622 + }
2623 +
2624 + // Check if text is empty
2625 + if (empty($text)) {
2626 + //error_log('Empty text provided for embedding generation');
2627 + return [
2628 + 'error' => esc_html__('No text provided for embedding generation', 'mxchat'),
2629 + 'error_code' => 'empty_embedding_text'
2630 + ];
2631 + }
2632 +
2633 + // Prepare request body with conditional output_dimension
2634 + $request_body = [
2635 + 'input' => $text,
2636 + 'model' => $selected_model
2637 + ];
2638 +
2639 + // Add output_dimension for voyage-3-large
2640 + if ($selected_model === 'voyage-3-large') {
2641 + $request_body['output_dimension'] = 2048;
2642 + }
2643 +
2644 + // Prepare request arguments
2645 + $args = [
2646 + 'body' => wp_json_encode($request_body),
2647 + 'headers' => [
2648 + 'Content-Type' => 'application/json',
2649 + 'Authorization' => 'Bearer ' . $api_key,
2650 + ],
2651 + 'timeout' => 60,
2652 + 'redirection' => 5,
2653 + 'blocking' => true,
2654 + 'httpversion' => '1.0',
2655 + 'sslverify' => true,
2656 + ];
2657 +
2658 + // Make the request
2659 + $response = wp_remote_post($endpoint, $args);
2660 +
2661 + // Handle WordPress errors
2662 + if (is_wp_error($response)) {
2663 + $error_message = $response->get_error_message();
2664 + //error_log('Embedding Generation Error: ' . $error_message);
2665 + return [
2666 + 'error' => esc_html__('Connection error when generating embeddings: ', 'mxchat') . esc_html($error_message),
2667 + 'error_code' => 'embedding_connection_error'
2668 + ];
2669 + }
2670 +
2671 + // Check HTTP status code
2672 + $status_code = wp_remote_retrieve_response_code($response);
2673 + if ($status_code !== 200) {
2674 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
2675 +
2676 + $error_message = isset($response_body['error']['message'])
2677 + ? $response_body['error']['message']
2678 + : 'HTTP Error ' . $status_code;
2679 +
2680 + $error_type = isset($response_body['error']['type'])
2681 + ? $response_body['error']['type']
2682 + : 'unknown';
2683 +
2684 + //error_log('Embedding API HTTP Error: ' . $status_code . ' - ' . $error_message);
2685 +
2686 + // Handle specific error types
2687 + switch ($error_type) {
2688 + case 'invalid_request_error':
2689 + if (strpos($error_message, 'API key') !== false) {
2690 + return [
2691 + 'error' => esc_html__('Invalid API key for embedding generation. Please check your API key configuration.', 'mxchat'),
2692 + 'error_code' => 'embedding_invalid_api_key'
2693 + ];
2694 + }
2695 + break;
2696 +
2697 + case 'authentication_error':
2698 + return [
2699 + 'error' => esc_html__('Authentication failed for embedding generation. Please check your API key.', 'mxchat'),
2700 + 'error_code' => 'embedding_auth_error'
2701 + ];
2702 +
2703 + case 'rate_limit_exceeded':
2704 + return [
2705 + 'error' => esc_html__('Rate limit exceeded for embedding generation. Please try again later.', 'mxchat'),
2706 + 'error_code' => 'embedding_rate_limit'
2707 + ];
2708 +
2709 + case 'quota_exceeded':
2710 + return [
2711 + 'error' => esc_html__('API quota exceeded for embedding generation. Please check your billing details.', 'mxchat'),
2712 + 'error_code' => 'embedding_quota_exceeded'
2713 + ];
2714 + }
2715 +
2716 + // Generic error fallback
2717 + return [
2718 + 'error' => esc_html__('Embedding API error - check embedding API key.: ', 'mxchat') . esc_html($error_message),
2719 + 'error_code' => 'embedding_api_error',
2720 + 'status_code' => $status_code
2721 + ];
2722 + }
2723 +
2724 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
2725 +
2726 + if (isset($response_body['data'][0]['embedding']) && is_array($response_body['data'][0]['embedding'])) {
2727 + return $response_body['data'][0]['embedding'];
2728 + } else {
2729 + //error_log('Invalid embedding response: ' . wp_json_encode($response_body));
2730 + return [
2731 + 'error' => esc_html__('Received invalid embedding data from the API.', 'mxchat'),
2732 + 'error_code' => 'invalid_embedding_response'
2733 + ];
2734 + }
2735 + } catch (Exception $e) {
2736 + //error_log('Embedding Exception: ' . $e->getMessage());
2737 + return [
2738 + 'error' => esc_html__('System error when generating embeddings: ', 'mxchat') . esc_html($e->getMessage()),
2739 + 'error_code' => 'embedding_exception'
2740 + ];
2741 + }
2742 +}
2743 +
2744 +
2745 +private function mxchat_find_relevant_content($user_embedding) {
2746 + //error_log('MXChat Vector Search: Starting content search...');
2747 +
2748 + // Retrieve the add-on settings from the database.
2749 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
2750 +
2751 + // Determine whether Pinecone is enabled.
2752 + // We expect the sanitized setting to be a string '1' if enabled, otherwise '0'.
2753 + $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
2754 +
2755 + //error_log('Pinecone enabled flag: ' . $use_pinecone);
2756 +
2757 + if ($use_pinecone === 1) {
2758 + //error_log('MXChat Vector Search: Using Pinecone database');
2759 + return $this->find_relevant_content_pinecone($user_embedding);
2760 + } else {
2761 + //error_log('MXChat Vector Search: Using WordPress database');
2762 + return $this->find_relevant_content_wordpress($user_embedding);
2763 + }
2764 +}
2765 +
2766 +
2767 +private function find_relevant_content_wordpress($user_embedding) {
2768 + global $wpdb;
2769 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
2770 + $cache_key = 'mxchat_system_prompt_embeddings';
2771 + $batch_size = 500;
2772 +
2773 + // Log start of matching process
2774 + //error_log('[MXCHAT] Starting similarity matching process');
2775 +
2776 + // Retrieve embeddings from cache or database
2777 + $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
2778 + if ($embeddings === false) {
2779 + //error_log('[MXCHAT] Cache miss - loading embeddings from database');
2780 + $embeddings = [];
2781 + $offset = 0;
2782 +
2783 + // Load in batches and build cache
2784 + do {
2785 + $query = $wpdb->prepare(
2786 + "SELECT id, embedding_vector
2787 + FROM {$system_prompt_table}
2788 + LIMIT %d OFFSET %d",
2789 + $batch_size,
2790 + $offset
2791 + );
2792 +
2793 + $batch = $wpdb->get_results($query);
2794 + if (empty($batch)) {
2795 + break;
2796 + }
2797 +
2798 + $embeddings = array_merge($embeddings, $batch);
2799 + $offset += $batch_size;
2800 +
2801 + // Free memory
2802 + unset($batch);
2803 +
2804 + } while (true);
2805 +
2806 + if (empty($embeddings)) {
2807 + //error_log('[MXCHAT] No embeddings found in database');
2808 + return ''; // Return an empty string if no embeddings found
2809 + }
2810 + wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
2811 + //error_log('[MXCHAT] Cached ' . count($embeddings) . ' embeddings');
2812 + } else {
2813 + //error_log('[MXCHAT] Using ' . count($embeddings) . ' cached embeddings');
2814 + }
2815 +
2816 + // Initialize array to store relevant results with similarity scores
2817 + $relevant_results = [];
2818 +
2819 + // Get the similarity threshold from the main options array only
2820 + $main_options = get_option('mxchat_options', []);
2821 + $similarity_threshold = isset($main_options['similarity_threshold'])
2822 + ? ((int) $main_options['similarity_threshold']) / 100
2823 + : 0.8; // Default to 80%
2824 +
2825 + //error_log('[MXCHAT] Using similarity threshold: ' . ($similarity_threshold * 100) . '%');
2826 +
2827 + // Iterate through embeddings to calculate similarity
2828 + foreach ($embeddings as $embedding) {
2829 + $database_embedding = $embedding->embedding_vector
2830 + ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
2831 + : null;
2832 + if (is_array($database_embedding) && is_array($user_embedding)) {
2833 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
2834 +
2835 + // Log each similarity score over 0.5 to reduce log spam
2836 + if ($similarity > 0.1) {
2837 + //error_log(sprintf('[MXCHAT] ID: %d | Similarity Score: %.4f', $embedding->id, $similarity));
2838 + }
2839 +
2840 + $relevant_results[] = [
2841 + 'id' => $embedding->id,
2842 + 'similarity' => $similarity
2843 + ];
2844 + }
2845 + // Free memory
2846 + unset($database_embedding);
2847 + }
2848 +
2849 + // Filter and sort relevant results by similarity
2850 + $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
2851 + return $result['similarity'] >= $similarity_threshold;
2852 + });
2853 + usort($relevant_results, function ($a, $b) {
2854 + return $b['similarity'] <=> $a['similarity'];
2855 + });
2856 +
2857 + // Log number of results that met threshold
2858 + //error_log('[MXCHAT] ' . count($relevant_results) . ' results met the similarity threshold');
2859 +
2860 + // Limit to the top 5 results
2861 + $top_results = array_slice($relevant_results, 0, 5);
2862 +
2863 + // Log the top matches
2864 + //error_log('[MXCHAT] Top matching results:');
2865 + foreach ($top_results as $index => $result) {
2866 +
2867 + }
2868 +
2869 + // Initialize the final content
2870 + $content = '';
2871 +
2872 + // Fetch and combine content for the top results
2873 + foreach ($top_results as $result) {
2874 + $chunk_content = $this->fetch_content_with_product_links($result['id']);
2875 + // Check if the content is PDF-related and add surrounding pages
2876 + if (strpos($chunk_content, '{"document_type":"pdf"') !== false) {
2877 + //error_log('[MXCHAT] ID ' . $result['id'] . ' is PDF content, adding surrounding pages');
2878 + $surrounding_content = $wpdb->get_results($wpdb->prepare(
2879 + "SELECT id, article_content FROM {$system_prompt_table}
2880 + WHERE id IN (
2881 + (SELECT id FROM {$system_prompt_table} WHERE id < %d ORDER BY id DESC LIMIT 1),
2882 + (SELECT id FROM {$system_prompt_table} WHERE id > %d ORDER BY id ASC LIMIT 1)
2883 + )",
2884 + $result['id'],
2885 + $result['id']
2886 + ));
2887 + // Add previous content if it exists
2888 + if (!empty($surrounding_content[0])) {
2889 + $content .= $surrounding_content[0]->article_content . "\n\n";
2890 + }
2891 + // Add the main chunk content
2892 + $content .= $chunk_content . "\n\n";
2893 + // Add next content if it exists
2894 + if (!empty($surrounding_content[1])) {
2895 + $content .= $surrounding_content[1]->article_content . "\n\n";
2896 + }
2897 + } else {
2898 + // For non-PDF content, add directly
2899 + $content .= $chunk_content . "\n\n";
2900 + }
2901 + }
2902 +
2903 + // Log content length
2904 + //error_log('[MXCHAT] Retrieved content length: ' . strlen(trim($content)) . ' characters');
2905 +
2906 + return trim($content);
2907 +}
2908 +
2909 +
2910 +private function find_relevant_content_pinecone($user_embedding) {
2911 + $options = get_option('mxchat_pinecone_addon_options', array());
2912 + $api_key = $options['mxchat_pinecone_api_key'] ?? '';
2913 + $host = $options['mxchat_pinecone_host'] ?? '';
2914 +
2915 + if (empty($host) || empty($api_key)) {
2916 + //error_log('[MXCHAT Debug] Pinecone credentials not properly configured');
2917 + return '';
2918 + }
2919 +
2920 + // Get the similarity threshold from the main options array only
2921 + $main_options = get_option('mxchat_options', []);
2922 + $similarity_threshold = isset($main_options['similarity_threshold'])
2923 + ? ((int) $main_options['similarity_threshold']) / 100
2924 + : 0.8; // Default to 80%
2925 +
2926 + //error_log('[MXCHAT Debug] Using similarity threshold: ' . ($similarity_threshold * 100) . '%');
2927 +
2928 + // Prepare the query request for Pinecone
2929 + $api_endpoint = "https://{$host}/query";
2930 +
2931 + //error_log('[MXCHAT Debug] Querying Pinecone at: ' . $api_endpoint);
2932 +
2933 + $request_body = array(
2934 + 'vector' => $user_embedding,
2935 + 'topK' => 5,
2936 + 'includeMetadata' => true,
2937 + 'includeValues' => true
2938 + );
2939 +
2940 + $response = wp_remote_post($api_endpoint, array(
2941 + 'headers' => array(
2942 + 'Api-Key' => $api_key,
2943 + 'accept' => 'application/json',
2944 + 'content-type' => 'application/json'
2945 + ),
2946 + 'body' => wp_json_encode($request_body),
2947 + 'timeout' => 30
2948 + ));
2949 +
2950 + if (is_wp_error($response)) {
2951 + //error_log('[MXCHAT Debug] Pinecone query error: ' . $response->get_error_message());
2952 + return '';
2953 + }
2954 +
2955 + $response_code = wp_remote_retrieve_response_code($response);
2956 + if ($response_code !== 200) {
2957 + //error_log('[MXCHAT Debug] Pinecone API error: ' . wp_remote_retrieve_body($response));
2958 + return '';
2959 + }
2960 +
2961 + $results = json_decode(wp_remote_retrieve_body($response), true);
2962 + if (empty($results['matches'])) {
2963 + //error_log('[MXCHAT Debug] No matches found in Pinecone response');
2964 + return '';
2965 + }
2966 +
2967 + //error_log('[MXCHAT Debug] Found ' . count($results['matches']) . ' matches in Pinecone');
2968 +
2969 + // Initialize the final content
2970 + $content = '';
2971 + $matches_above_threshold = 0;
2972 +
2973 + // Process each match
2974 + foreach ($results['matches'] as $index => $match) {
2975 + // Log score for each match
2976 +
2977 + // Skip if similarity is below threshold
2978 + if ($match['score'] < $similarity_threshold) {
2979 + continue;
2980 + }
2981 +
2982 + $matches_above_threshold++;
2983 +
2984 + if (!empty($match['metadata']['text']) && !empty($match['metadata']['source_url'])) {
2985 + // Add content with citation
2986 + $content .= $match['metadata']['text'] . "\n";
2987 + $content .= "Source: " . $match['metadata']['source_url'] . "\n\n";
2988 + }
2989 + }
2990 +
2991 + //error_log('[MXCHAT Debug] Total matches used (above threshold): ' . $matches_above_threshold);
2992 + //error_log('[MXCHAT Debug] Content length returned: ' . strlen(trim($content)) . ' characters');
2993 +
2994 + return trim($content);
2995 +}
2996 +
2997 +private function mxchat_find_relevant_products($user_embedding) {
2998 + //error_log('MXChat Vector Search: Starting product search...');
2999 +
3000 + // Retrieve the add-on settings from the database
3001 + $addon_options = get_option('mxchat_pinecone_addon_options', array());
3002 +
3003 + // Determine whether Pinecone is enabled
3004 + $use_pinecone = (isset($addon_options['mxchat_use_pinecone']) && $addon_options['mxchat_use_pinecone'] === '1') ? 1 : 0;
3005 +
3006 + //error_log('Pinecone enabled flag: ' . $use_pinecone);
3007 +
3008 + if ($use_pinecone === 1) {
3009 + //error_log('MXChat Vector Search: Using Pinecone database for products');
3010 + return $this->find_relevant_products_pinecone($user_embedding);
3011 + } else {
3012 + //error_log('MXChat Vector Search: Using WordPress database for products');
3013 + return $this->find_relevant_products_wordpress($user_embedding);
3014 + }
3015 +}
3016 +
3017 +private function find_relevant_products_wordpress($user_embedding) {
3018 + global $wpdb;
3019 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
3020 + $cache_key = 'mxchat_system_prompt_embeddings';
3021 + $batch_size = 500;
3022 +
3023 + // Original WordPress database search logic
3024 + // [Previous implementation remains the same]
3025 + $embeddings = wp_cache_get($cache_key, 'mxchat_system_prompts');
3026 + if ($embeddings === false) {
3027 + $embeddings = [];
3028 + $offset = 0;
3029 +
3030 + do {
3031 + $query = $wpdb->prepare(
3032 + "SELECT id, embedding_vector
3033 + FROM {$system_prompt_table}
3034 + LIMIT %d OFFSET %d",
3035 + $batch_size,
3036 + $offset
3037 + );
3038 +
3039 + $batch = $wpdb->get_results($query);
3040 + if (empty($batch)) {
3041 + break;
3042 + }
3043 +
3044 + $embeddings = array_merge($embeddings, $batch);
3045 + $offset += $batch_size;
3046 +
3047 + unset($batch);
3048 +
3049 + } while (true);
3050 +
3051 + if (empty($embeddings)) {
3052 + return '';
3053 + }
3054 + wp_cache_set($cache_key, $embeddings, 'mxchat_system_prompts', 3600);
3055 + }
3056 +
3057 + $relevant_results = [];
3058 + foreach ($embeddings as $embedding) {
3059 + $database_embedding = $embedding->embedding_vector
3060 + ? unserialize($embedding->embedding_vector, ['allowed_classes' => false])
3061 + : null;
3062 + if (is_array($database_embedding) && is_array($user_embedding)) {
3063 + $similarity = $this->mxchat_calculate_cosine_similarity($user_embedding, $database_embedding);
3064 + $relevant_results[] = [
3065 + 'id' => $embedding->id,
3066 + 'similarity' => $similarity
3067 + ];
3068 + }
3069 + unset($database_embedding);
3070 + }
3071 +
3072 + // Use fixed threshold for products
3073 + $similarity_threshold = 0.85;
3074 +
3075 + $relevant_results = array_filter($relevant_results, function ($result) use ($similarity_threshold) {
3076 + return $result['similarity'] >= $similarity_threshold;
3077 + });
3078 + usort($relevant_results, function ($a, $b) {
3079 + return $b['similarity'] <=> $a['similarity'];
3080 + });
3081 +
3082 + $top_results = array_slice($relevant_results, 0, 5);
3083 + $content = '';
3084 +
3085 + foreach ($top_results as $result) {
3086 + $chunk_content = $this->fetch_content_with_product_links($result['id']);
3087 + $content .= $chunk_content . "\n\n";
3088 + }
3089 +
3090 + return trim($content);
3091 +}
3092 +
3093 +// Modified search function with correct filter syntax
3094 +private function find_relevant_products_pinecone($user_embedding) {
3095 + //error_log('Starting Pinecone product search...');
3096 +
3097 + $options = get_option('mxchat_pinecone_addon_options', array());
3098 + $api_key = $options['mxchat_pinecone_api_key'] ?? '';
3099 + $host = $options['mxchat_pinecone_host'] ?? '';
3100 +
3101 + if (empty($host) || empty($api_key)) {
3102 + //error_log('Pinecone credentials not properly configured for product search');
3103 + return '';
3104 + }
3105 +
3106 + $similarity_threshold = 0.85;
3107 + $api_endpoint = "https://{$host}/query";
3108 +
3109 + $request_body = array(
3110 + 'vector' => $user_embedding,
3111 + 'topK' => 5,
3112 + 'includeMetadata' => true,
3113 + 'includeValues' => true,
3114 + 'filter' => array(
3115 + 'type' => 'product'
3116 + )
3117 + );
3118 +
3119 + //error_log('Sending request to Pinecone with body: ' . wp_json_encode($request_body));
3120 +
3121 + $response = wp_remote_post($api_endpoint, array(
3122 + 'headers' => array(
3123 + 'Api-Key' => $api_key,
3124 + 'accept' => 'application/json',
3125 + 'content-type' => 'application/json'
3126 + ),
3127 + 'body' => wp_json_encode($request_body),
3128 + 'timeout' => 30
3129 + ));
3130 +
3131 + if (is_wp_error($response)) {
3132 + //error_log('Pinecone product query error: ' . $response->get_error_message());
3133 + return '';
3134 + }
3135 +
3136 + $response_code = wp_remote_retrieve_response_code($response);
3137 + //error_log('Pinecone response code: ' . $response_code);
3138 +
3139 + if ($response_code !== 200) {
3140 + //error_log('Pinecone API error during product search: ' . wp_remote_retrieve_body($response));
3141 + return '';
3142 + }
3143 +
3144 + $results = json_decode(wp_remote_retrieve_body($response), true);
3145 + //error_log('Pinecone raw response: ' . wp_remote_retrieve_body($response));
3146 +
3147 + if (empty($results['matches'])) {
3148 + //error_log('No matches found in Pinecone response');
3149 + return '';
3150 + }
3151 +
3152 + $content = '';
3153 + foreach ($results['matches'] as $match) {
3154 + if ($match['score'] < $similarity_threshold) {
3155 + //error_log("Match below threshold: " . $match['score']);
3156 + continue;
3157 + }
3158 +
3159 + if (!empty($match['metadata']['text'])) {
3160 + $content .= $match['metadata']['text'];
3161 + if (!empty($match['metadata']['source_url'])) {
3162 + $content .= "\n\nFor more details, check out this product: " . esc_url($match['metadata']['source_url']);
3163 + }
3164 + $content .= "\n\n";
3165 + }
3166 + }
3167 +
3168 + return trim($content);
3169 +}
3170 +
3171 +
3172 +private function fetch_content_with_product_links($most_relevant_id) {
3173 + global $wpdb;
3174 + $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
3175 +
3176 + // Fetch the article content and associated product URL
3177 + $query = $wpdb->prepare("SELECT article_content, source_url FROM {$system_prompt_table} WHERE id = %d", $most_relevant_id);
3178 + $result = $wpdb->get_row($query);
3179 +
3180 + if ($result) {
3181 + // Append the product link to the content if available
3182 + $content = $result->article_content;
3183 + if (!empty($result->source_url)) {
3184 + $content .= "\n\nFor more details, check out this product: " . esc_url($result->source_url);
3185 + }
3186 + return $content;
3187 + }
3188 +
3189 + return null;
3190 +}
3191 +
3192 +private function mxchat_generate_response($relevant_content, $api_key, $xai_api_key, $claude_api_key, $deepseek_api_key, $gemini_api_key, $conversation_history) {
3193 + try {
3194 + if (!$relevant_content) {
3195 + return [
3196 + 'error' => esc_html__("I couldn't find relevant information on that topic.", 'mxchat'),
3197 + 'error_code' => 'no_relevant_content'
3198 + ];
3199 + }
3200 +
3201 + // Ensure conversation_history is an array
3202 + if (!is_array($conversation_history)) {
3203 + $conversation_history = array();
3204 + }
3205 +
3206 + // Get selected model with default fallback
3207 + $selected_model = isset($this->options['model']) ? $this->options['model'] : 'gpt-4o';
3208 +
3209 + // Extract model prefix to determine the provider
3210 + $model_parts = explode('-', $selected_model);
3211 + $provider = strtolower($model_parts[0]);
3212 +
3213 + // Handle model selection based on provider prefix
3214 + switch ($provider) {
3215 + case 'gemini':
3216 + if (empty($gemini_api_key)) {
3217 + return [
3218 + 'error' => esc_html__('Google Gemini API key is not configured', 'mxchat'),
3219 + 'error_code' => 'missing_gemini_api_key'
3220 + ];
3221 + }
3222 + $response = $this->mxchat_generate_response_gemini(
3223 + $selected_model,
3224 + $gemini_api_key,
3225 + $conversation_history,
3226 + $relevant_content
3227 + );
3228 + break;
3229 +
3230 + case 'claude':
3231 + if (empty($claude_api_key)) {
3232 + return [
3233 + 'error' => esc_html__('Claude API key is not configured', 'mxchat'),
3234 + 'error_code' => 'missing_claude_api_key'
3235 + ];
3236 + }
3237 + $response = $this->mxchat_generate_response_claude(
3238 + $selected_model,
3239 + $claude_api_key,
3240 + $conversation_history,
3241 + $relevant_content
3242 + );
3243 + break;
3244 +
3245 + case 'grok':
3246 + if (empty($xai_api_key)) {
3247 + return [
3248 + 'error' => esc_html__('X.AI API key is not configured', 'mxchat'),
3249 + 'error_code' => 'missing_xai_api_key'
3250 + ];
3251 + }
3252 + $response = $this->mxchat_generate_response_xai(
3253 + $selected_model,
3254 + $xai_api_key,
3255 + $conversation_history,
3256 + $relevant_content
3257 + );
3258 + break;
3259 +
3260 + case 'deepseek':
3261 + if (empty($deepseek_api_key)) {
3262 + return [
3263 + 'error' => esc_html__('DeepSeek API key is not configured', 'mxchat'),
3264 + 'error_code' => 'missing_deepseek_api_key'
3265 + ];
3266 + }
3267 + $response = $this->mxchat_generate_response_deepseek(
3268 + $selected_model,
3269 + $deepseek_api_key,
3270 + $conversation_history,
3271 + $relevant_content
3272 + );
3273 + break;
3274 +
3275 + case 'gpt':
3276 + if (empty($api_key)) {
3277 + return [
3278 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
3279 + 'error_code' => 'missing_openai_api_key'
3280 + ];
3281 + }
3282 + $response = $this->mxchat_generate_response_openai(
3283 + $selected_model,
3284 + $api_key,
3285 + $conversation_history,
3286 + $relevant_content
3287 + );
3288 + break;
3289 +
3290 + default:
3291 + // Default to OpenAI for custom models or unrecognized prefixes
3292 + if (empty($api_key)) {
3293 + return [
3294 + 'error' => esc_html__('OpenAI API key is not configured', 'mxchat'),
3295 + 'error_code' => 'missing_openai_api_key'
3296 + ];
3297 + }
3298 + $response = $this->mxchat_generate_response_openai(
3299 + $selected_model,
3300 + $api_key,
3301 + $conversation_history,
3302 + $relevant_content
3303 + );
3304 + break;
3305 + }
3306 +
3307 + // Check if the response is an error array from the provider-specific function
3308 + if (is_array($response) && isset($response['error'])) {
3309 + return $response; // Pass through the error
3310 + }
3311 +
3312 + return $response;
3313 +
3314 + } catch (Exception $e) {
3315 + //error_log('MXChat Error: ' . $e->getMessage());
3316 + return [
3317 + 'error' => sprintf(esc_html__('An error occurred: %s', 'mxchat'), esc_html($e->getMessage())),
3318 + 'error_code' => 'system_exception',
3319 + 'exception_details' => $e->getMessage()
3320 + ];
3321 + }
3322 +}
3323 +
3324 +private function mxchat_generate_response_deepseek($selected_model, $deepseek_api_key, $conversation_history, $relevant_content) {
3325 + try {
3326 + // Ensure conversation_history is an array
3327 + if (!is_array($conversation_history)) {
3328 + $conversation_history = array();
3329 + }
3330 +
3331 + // Get system prompt instructions from options
3332 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3333 +
3334 + // Create a new array for the formatted conversation
3335 + $formatted_conversation = array();
3336 +
3337 + // Add system message first
3338 + $formatted_conversation[] = array(
3339 + 'role' => 'system',
3340 + 'content' => $system_prompt_instructions . " " . $relevant_content
3341 + );
3342 +
3343 + // Add the rest of the conversation history
3344 + foreach ($conversation_history as $message) {
3345 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
3346 + $role = $message['role'];
3347 +
3348 + // Convert roles to supported format
3349 + if ($role === 'bot' || $role === 'agent') {
3350 + $role = 'assistant';
3351 + }
3352 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
3353 + $role = 'user';
3354 + }
3355 +
3356 + $formatted_conversation[] = array(
3357 + 'role' => $role,
3358 + 'content' => $message['content']
3359 + );
3360 + }
3361 + }
3362 +
3363 + $body = json_encode([
3364 + 'model' => $selected_model,
3365 + 'messages' => $formatted_conversation,
3366 + 'temperature' => 0.8,
3367 + 'stream' => false
3368 + ]);
3369 +
3370 + $args = [
3371 + 'body' => $body,
3372 + 'headers' => [
3373 + 'Content-Type' => 'application/json',
3374 + 'Authorization' => 'Bearer ' . $deepseek_api_key,
3375 + ],
3376 + 'timeout' => 60,
3377 + 'redirection' => 5,
3378 + 'blocking' => true,
3379 + 'httpversion' => '1.0',
3380 + 'sslverify' => true,
3381 + ];
3382 +
3383 + $response = wp_remote_post('https://api.deepseek.com/v1/chat/completions', $args);
3384 +
3385 + if (is_wp_error($response)) {
3386 + $error_message = $response->get_error_message();
3387 + //error_log('DeepSeek API Error: ' . $error_message);
3388 + return [
3389 + 'error' => esc_html__('Connection error when contacting DeepSeek: ', 'mxchat') . esc_html($error_message),
3390 + 'error_code' => 'deepseek_connection_error',
3391 + 'provider' => 'deepseek'
3392 + ];
3393 + }
3394 +
3395 + $status_code = wp_remote_retrieve_response_code($response);
3396 + if ($status_code !== 200) {
3397 + $response_body = wp_remote_retrieve_body($response);
3398 + $decoded_response = json_decode($response_body, true);
3399 +
3400 + $error_message = isset($decoded_response['error']['message'])
3401 + ? $decoded_response['error']['message']
3402 + : 'HTTP Error ' . $status_code;
3403 +
3404 + $error_type = isset($decoded_response['error']['type'])
3405 + ? $decoded_response['error']['type']
3406 + : 'unknown';
3407 +
3408 + //error_log('DeepSeek API HTTP Error: ' . $status_code . ' - ' . $error_message);
3409 +
3410 + // Handle specific error types
3411 + switch ($status_code) {
3412 + case 401:
3413 + return [
3414 + 'error' => esc_html__('Authentication failed with DeepSeek. Please check your API key.', 'mxchat'),
3415 + 'error_code' => 'deepseek_auth_error',
3416 + 'provider' => 'deepseek'
3417 + ];
3418 +
3419 + case 400:
3420 + if (strpos($error_message, 'API key') !== false) {
3421 + return [
3422 + 'error' => esc_html__('Invalid DeepSeek API key. Please check your API key configuration.', 'mxchat'),
3423 + 'error_code' => 'deepseek_invalid_api_key',
3424 + 'provider' => 'deepseek'
3425 + ];
3426 + }
3427 + break;
3428 +
3429 + case 429:
3430 + if (strpos($error_message, 'quota') !== false) {
3431 + return [
3432 + 'error' => esc_html__('DeepSeek API quota exceeded. Please check your billing details.', 'mxchat'),
3433 + 'error_code' => 'deepseek_quota_exceeded',
3434 + 'provider' => 'deepseek'
3435 + ];
3436 + } else {
3437 + return [
3438 + 'error' => esc_html__('DeepSeek rate limit exceeded. Please try again later.', 'mxchat'),
3439 + 'error_code' => 'deepseek_rate_limit',
3440 + 'provider' => 'deepseek'
3441 + ];
3442 + }
3443 +
3444 + case 500:
3445 + case 502:
3446 + case 503:
3447 + case 504:
3448 + return [
3449 + 'error' => esc_html__('DeepSeek service is currently unavailable. Please try again later.', 'mxchat'),
3450 + 'error_code' => 'deepseek_service_unavailable',
3451 + 'provider' => 'deepseek'
3452 + ];
3453 + }
3454 +
3455 + // Generic error fallback
3456 + return [
3457 + 'error' => esc_html__('DeepSeek API error: ', 'mxchat') . esc_html($error_message),
3458 + 'error_code' => 'deepseek_api_error',
3459 + 'provider' => 'deepseek',
3460 + 'status_code' => $status_code
3461 + ];
3462 + }
3463 +
3464 + $response_body = wp_remote_retrieve_body($response);
3465 + $decoded_response = json_decode($response_body, true);
3466 +
3467 + if (isset($decoded_response['choices'][0]['message']['content'])) {
3468 + return trim($decoded_response['choices'][0]['message']['content']);
3469 + } else {
3470 + //error_log('DeepSeek API Response Format Error: ' . print_r($decoded_response, true));
3471 + return [
3472 + 'error' => esc_html__('Unexpected response format from DeepSeek.', 'mxchat'),
3473 + 'error_code' => 'deepseek_response_format_error',
3474 + 'provider' => 'deepseek'
3475 + ];
3476 + }
3477 + } catch (Exception $e) {
3478 + //error_log('DeepSeek Exception: ' . $e->getMessage());
3479 + return [
3480 + 'error' => esc_html__('System error when processing DeepSeek request: ', 'mxchat') . esc_html($e->getMessage()),
3481 + 'error_code' => 'deepseek_exception',
3482 + 'provider' => 'deepseek'
3483 + ];
3484 + }
3485 +}
3486 +
3487 +private function mxchat_generate_response_openai($selected_model, $api_key, $conversation_history, $relevant_content) {
3488 + try {
3489 + // Ensure conversation_history is an array
3490 + if (!is_array($conversation_history)) {
3491 + $conversation_history = array();
3492 + }
3493 +
3494 + // Get system prompt instructions from options
3495 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3496 +
3497 + // Create a new array for the formatted conversation
3498 + $formatted_conversation = array();
3499 +
3500 + // Add system message first
3501 + $formatted_conversation[] = array(
3502 + 'role' => 'system',
3503 + 'content' => $system_prompt_instructions . " " . $relevant_content
3504 + );
3505 +
3506 + // Add the rest of the conversation history
3507 + foreach ($conversation_history as $message) {
3508 + if (is_array($message) && isset($message['role']) && isset($message['content'])) {
3509 + $role = $message['role'];
3510 +
3511 + // Convert roles to supported format
3512 + if ($role === 'bot' || $role === 'agent') {
3513 + $role = 'assistant';
3514 + }
3515 + if (!in_array($role, ['system', 'assistant', 'user', 'function', 'tool'])) {
3516 + $role = 'user';
3517 + }
3518 +
3519 + $formatted_conversation[] = array(
3520 + 'role' => $role,
3521 + 'content' => $message['content']
3522 + );
3523 + }
3524 + }
3525 +
3526 + $body = json_encode([
3527 + 'model' => $selected_model,
3528 + 'messages' => $formatted_conversation,
3529 + 'temperature' => 0.8,
3530 + 'stream' => false
3531 + ]);
3532 +
3533 + $args = [
3534 + 'body' => $body,
3535 + 'headers' => [
3536 + 'Content-Type' => 'application/json',
3537 + 'Authorization' => 'Bearer ' . $api_key,
3538 + ],
3539 + 'timeout' => 60,
3540 + 'redirection' => 5,
3541 + 'blocking' => true,
3542 + 'httpversion' => '1.0',
3543 + 'sslverify' => true,
3544 + ];
3545 +
3546 + $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
3547 +
3548 + if (is_wp_error($response)) {
3549 + $error_message = $response->get_error_message();
3550 + //error_log('OpenAI API Error: ' . $error_message);
3551 + return [
3552 + 'error' => esc_html__('Connection error when contacting OpenAI: ', 'mxchat') . esc_html($error_message),
3553 + 'error_code' => 'openai_connection_error',
3554 + 'provider' => 'openai'
3555 + ];
3556 + }
3557 +
3558 + $status_code = wp_remote_retrieve_response_code($response);
3559 + if ($status_code !== 200) {
3560 + $response_body = wp_remote_retrieve_body($response);
3561 + $decoded_response = json_decode($response_body, true);
3562 +
3563 + $error_message = isset($decoded_response['error']['message'])
3564 + ? $decoded_response['error']['message']
3565 + : 'HTTP Error ' . $status_code;
3566 +
3567 + $error_type = isset($decoded_response['error']['type'])
3568 + ? $decoded_response['error']['type']
3569 + : 'unknown';
3570 +
3571 + //error_log('OpenAI API HTTP Error: ' . $status_code . ' - ' . $error_message);
3572 +
3573 + // Handle specific error types
3574 + switch ($error_type) {
3575 + case 'invalid_request_error':
3576 + if (strpos($error_message, 'API key') !== false) {
3577 + return [
3578 + 'error' => esc_html__('Invalid OpenAI API key. Please check your API key configuration.', 'mxchat'),
3579 + 'error_code' => 'openai_invalid_api_key',
3580 + 'provider' => 'openai'
3581 + ];
3582 + }
3583 + break;
3584 +
3585 + case 'authentication_error':
3586 + return [
3587 + 'error' => esc_html__('Authentication failed with OpenAI. Please check your API key.', 'mxchat'),
3588 + 'error_code' => 'openai_auth_error',
3589 + 'provider' => 'openai'
3590 + ];
3591 +
3592 + case 'rate_limit_exceeded':
3593 + return [
3594 + 'error' => esc_html__('OpenAI rate limit exceeded. Please try again later.', 'mxchat'),
3595 + 'error_code' => 'openai_rate_limit',
3596 + 'provider' => 'openai'
3597 + ];
3598 +
3599 + case 'quota_exceeded':
3600 + return [
3601 + 'error' => esc_html__('OpenAI API quota exceeded. Please check your billing details.', 'mxchat'),
3602 + 'error_code' => 'openai_quota_exceeded',
3603 + 'provider' => 'openai'
3604 + ];
3605 + }
3606 +
3607 + // Generic error fallback
3608 + return [
3609 + 'error' => esc_html__('OpenAI API error: ', 'mxchat') . esc_html($error_message),
3610 + 'error_code' => 'openai_api_error',
3611 + 'provider' => 'openai',
3612 + 'status_code' => $status_code
3613 + ];
3614 + }
3615 +
3616 + $response_body = wp_remote_retrieve_body($response);
3617 + $decoded_response = json_decode($response_body, true);
3618 +
3619 + if (isset($decoded_response['choices'][0]['message']['content'])) {
3620 + return trim($decoded_response['choices'][0]['message']['content']);
3621 + } else {
3622 + //error_log('OpenAI API Response Format Error: ' . print_r($decoded_response, true));
3623 + return [
3624 + 'error' => esc_html__('Unexpected response format from OpenAI.', 'mxchat'),
3625 + 'error_code' => 'openai_response_format_error',
3626 + 'provider' => 'openai'
3627 + ];
3628 + }
3629 + } catch (Exception $e) {
3630 + //error_log('OpenAI Exception: ' . $e->getMessage());
3631 + return [
3632 + 'error' => esc_html__('System error when processing OpenAI request: ', 'mxchat') . esc_html($e->getMessage()),
3633 + 'error_code' => 'openai_exception',
3634 + 'provider' => 'openai'
3635 + ];
3636 + }
3637 +}
3638 +private function mxchat_generate_response_xai($selected_model, $xai_api_key, $conversation_history, $relevant_content) {
3639 + try {
3640 + // Get system prompt instructions from options
3641 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3642 +
3643 + // Add system prompt to relevant content
3644 + $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
3645 +
3646 + // Prepend system instructions to the conversation history
3647 + array_unshift($conversation_history, [
3648 + 'role' => 'system',
3649 + 'content' => "Here are your instructions: " . $content_with_instructions
3650 + ]);
3651 +
3652 + // Ensure consistency: Replace 'bot' and 'agent' roles with supported values
3653 + foreach ($conversation_history as &$message) {
3654 + if ($message['role'] === 'bot') {
3655 + $message['role'] = 'assistant';
3656 + } elseif ($message['role'] === 'agent') {
3657 + // Tag the message as coming from a live agent
3658 + $message['role'] = 'assistant';
3659 + if (!isset($message['metadata'])) {
3660 + $message['metadata'] = ['source' => 'live_agent'];
3661 + }
3662 + }
3663 +
3664 + // Ensure all roles are valid
3665 + if (!in_array($message['role'], ['system', 'assistant', 'user', 'function', 'tool'])) {
3666 + $message['role'] = 'user'; // Default to 'user'
3667 + }
3668 + }
3669 +
3670 + // Build the request body
3671 + $body = json_encode([
3672 + 'model' => $selected_model,
3673 + 'messages' => $conversation_history,
3674 + 'temperature' => 0.8,
3675 + 'stream' => false
3676 + ]);
3677 +
3678 + // Set up the API request
3679 + $args = [
3680 + 'body' => $body,
3681 + 'headers' => [
3682 + 'Content-Type' => 'application/json',
3683 + 'Authorization' => 'Bearer ' . $xai_api_key,
3684 + ],
3685 + 'timeout' => 60,
3686 + 'redirection' => 5,
3687 + 'blocking' => true,
3688 + 'httpversion' => '1.0',
3689 + 'sslverify' => true,
3690 + ];
3691 +
3692 + // Make the API request
3693 + $response = wp_remote_post('https://api.x.ai/v1/chat/completions', $args);
3694 +
3695 + // Process the response
3696 + if (is_wp_error($response)) {
3697 + $error_message = $response->get_error_message();
3698 + //error_log('X.AI API Error: ' . $error_message);
3699 + return [
3700 + 'error' => esc_html__('Connection error when contacting X.AI: ', 'mxchat') . esc_html($error_message),
3701 + 'error_code' => 'xai_connection_error',
3702 + 'provider' => 'xai'
3703 + ];
3704 + }
3705 +
3706 + $status_code = wp_remote_retrieve_response_code($response);
3707 + if ($status_code !== 200) {
3708 + $response_body = wp_remote_retrieve_body($response);
3709 + $decoded_response = json_decode($response_body, true);
3710 +
3711 + // Log the full response for debugging
3712 + //error_log('X.AI Error Response: ' . print_r($decoded_response, true));
3713 +
3714 + // Extract error message from X.AI's specific format
3715 + $error_message = '';
3716 +
3717 + // Check for direct error string (as seen in your logs)
3718 + if (isset($decoded_response['error']) && is_string($decoded_response['error'])) {
3719 + $error_message = $decoded_response['error'];
3720 + }
3721 + // Check for nested error object (OpenAI style)
3722 + elseif (isset($decoded_response['error']['message'])) {
3723 + $error_message = $decoded_response['error']['message'];
3724 + }
3725 + // Check for top-level message
3726 + elseif (isset($decoded_response['message'])) {
3727 + $error_message = $decoded_response['message'];
3728 + }
3729 + // Fallback
3730 + else {
3731 + $error_message = 'HTTP Error ' . $status_code;
3732 + }
3733 +
3734 + //error_log('X.AI API HTTP Error: ' . $status_code . ' - ' . $error_message);
3735 +
3736 + // Check for API key errors using string matching
3737 + if (stripos($error_message, 'api key') !== false ||
3738 + stripos($error_message, 'incorrect api key') !== false ||
3739 + stripos($error_message, 'invalid api key') !== false) {
3740 + return [
3741 + 'error' => esc_html__('Invalid X.AI API key. Please check your API key configuration.', 'mxchat'),
3742 + 'error_code' => 'xai_invalid_api_key',
3743 + 'provider' => 'xai'
3744 + ];
3745 + }
3746 +
3747 + // Authentication errors
3748 + if ($status_code === 401 || $status_code === 403 ||
3749 + stripos($error_message, 'auth') !== false) {
3750 + return [
3751 + 'error' => esc_html__('Authentication failed with X.AI. Please check your API key.', 'mxchat'),
3752 + 'error_code' => 'xai_auth_error',
3753 + 'provider' => 'xai'
3754 + ];
3755 + }
3756 +
3757 + // Model errors
3758 + if (stripos($error_message, 'model') !== false) {
3759 + return [
3760 + 'error' => esc_html__('Invalid model specified for X.AI. Please check your model configuration.', 'mxchat'),
3761 + 'error_code' => 'xai_invalid_model',
3762 + 'provider' => 'xai'
3763 + ];
3764 + }
3765 +
3766 + // Rate limit errors
3767 + if ($status_code === 429 ||
3768 + stripos($error_message, 'rate') !== false ||
3769 + stripos($error_message, 'limit') !== false) {
3770 + return [
3771 + 'error' => esc_html__('X.AI rate limit exceeded. Please try again later.', 'mxchat'),
3772 + 'error_code' => 'xai_rate_limit',
3773 + 'provider' => 'xai'
3774 + ];
3775 + }
3776 +
3777 + // Quota errors
3778 + if (stripos($error_message, 'quota') !== false ||
3779 + stripos($error_message, 'billing') !== false) {
3780 + return [
3781 + 'error' => esc_html__('X.AI API quota exceeded. Please check your billing details.', 'mxchat'),
3782 + 'error_code' => 'xai_quota_exceeded',
3783 + 'provider' => 'xai'
3784 + ];
3785 + }
3786 +
3787 + // Server errors
3788 + if ($status_code >= 500) {
3789 + return [
3790 + 'error' => esc_html__('X.AI service is currently unavailable. Please try again later.', 'mxchat'),
3791 + 'error_code' => 'xai_service_unavailable',
3792 + 'provider' => 'xai'
3793 + ];
3794 + }
3795 +
3796 + // Generic error fallback with the actual error message
3797 + return [
3798 + 'error' => esc_html__('X.AI API error: ', 'mxchat') . esc_html($error_message),
3799 + 'error_code' => 'xai_api_error',
3800 + 'provider' => 'xai',
3801 + 'status_code' => $status_code
3802 + ];
3803 + }
3804 +
3805 + $response_body = wp_remote_retrieve_body($response);
3806 + $decoded_response = json_decode($response_body, true);
3807 +
3808 + if (isset($decoded_response['choices'][0]['message']['content'])) {
3809 + return trim($decoded_response['choices'][0]['message']['content']);
3810 + } else {
3811 + //error_log('X.AI API Response Format Error: ' . print_r($decoded_response, true));
3812 + return [
3813 + 'error' => esc_html__('Unexpected response format from X.AI.', 'mxchat'),
3814 + 'error_code' => 'xai_response_format_error',
3815 + 'provider' => 'xai'
3816 + ];
3817 + }
3818 +} catch (Exception $e) {
3819 + //error_log('X.AI Exception: ' . $e->getMessage());
3820 + return [
3821 + 'error' => esc_html__('System error when processing X.AI request: ', 'mxchat') . esc_html($e->getMessage()),
3822 + 'error_code' => 'xai_exception',
3823 + 'provider' => 'xai'
3824 + ];
3825 +}
3826 +}
3827 +private function mxchat_generate_response_claude($selected_model, $claude_api_key, $conversation_history, $relevant_content) {
3828 + // Get system prompt instructions from options
3829 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3830 +
3831 + // Clean and validate conversation history
3832 + foreach ($conversation_history as &$message) {
3833 + // Convert bot and agent roles to assistant
3834 + if ($message['role'] === 'bot' || $message['role'] === 'agent') {
3835 + $message['role'] = 'assistant';
3836 + }
3837 +
3838 + // Remove unsupported roles - Claude only supports 'assistant' and 'user'
3839 + if (!in_array($message['role'], ['assistant', 'user'])) {
3840 + $message['role'] = 'user';
3841 + }
3842 +
3843 + // Ensure content field exists
3844 + if (!isset($message['content']) || empty($message['content'])) {
3845 + $message['content'] = '';
3846 + }
3847 +
3848 + // Remove any unsupported fields
3849 + $message = array_intersect_key($message, array_flip(['role', 'content']));
3850 + }
3851 +
3852 + // Add relevant content as the latest user message
3853 + $conversation_history[] = [
3854 + 'role' => 'user',
3855 + 'content' => $relevant_content
3856 + ];
3857 +
3858 + // Build request body
3859 + $body = json_encode([
3860 + 'model' => $selected_model,
3861 + 'max_tokens' => 1000,
3862 + 'temperature' => 0.8,
3863 + 'messages' => $conversation_history,
3864 + 'system' => $system_prompt_instructions
3865 + ]);
3866 +
3867 + // Set up API request
3868 + $args = [
3869 + 'body' => $body,
3870 + 'headers' => [
3871 + 'Content-Type' => 'application/json',
3872 + 'x-api-key' => $claude_api_key,
3873 + 'anthropic-version' => '2023-06-01'
3874 + ],
3875 + 'timeout' => 60,
3876 + 'redirection' => 5,
3877 + 'blocking' => true,
3878 + 'httpversion' => '1.0',
3879 + 'sslverify' => true,
3880 + ];
3881 +
3882 + // Make API request
3883 + $response = wp_remote_post('https://api.anthropic.com/v1/messages', $args);
3884 +
3885 + // Check for WordPress errors
3886 + if (is_wp_error($response)) {
3887 + //error_log("Claude API request error: " . $response->get_error_message());
3888 + return "Sorry, there was an error connecting to the API.";
3889 + }
3890 +
3891 + // Check HTTP response code
3892 + $http_code = wp_remote_retrieve_response_code($response);
3893 + if ($http_code !== 200) {
3894 + $error_body = wp_remote_retrieve_body($response);
3895 + //error_log("Claude API HTTP error: " . $http_code . " - " . $error_body);
3896 +
3897 + // Try to extract error message from response
3898 + $error_data = json_decode($error_body, true);
3899 + $error_message = isset($error_data['error']['message']) ?
3900 + $error_data['error']['message'] :
3901 + "HTTP error " . $http_code;
3902 +
3903 + return "Sorry, the API returned an error: " . $error_message;
3904 + }
3905 +
3906 + // Parse response
3907 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
3908 +
3909 + // Check for JSON decode errors
3910 + if (json_last_error() !== JSON_ERROR_NONE) {
3911 + //error_log("Claude API JSON decode error: " . json_last_error_msg());
3912 + return "Sorry, there was an error processing the API response.";
3913 + }
3914 +
3915 + // Extract and validate response content
3916 + if (isset($response_body['content']) &&
3917 + is_array($response_body['content']) &&
3918 + !empty($response_body['content']) &&
3919 + isset($response_body['content'][0]['text'])) {
3920 + return trim($response_body['content'][0]['text']);
3921 + }
3922 +
3923 + // Log unexpected response format
3924 + //error_log("Claude API unexpected response format: " . print_r($response_body, true));
3925 + return "Sorry, I received an unexpected response format from the API.";
3926 +}
3927 +private function mxchat_generate_response_gemini($selected_model, $gemini_api_key, $conversation_history, $relevant_content) {
3928 + // Get system prompt instructions from options
3929 + $system_prompt_instructions = isset($this->options['system_prompt_instructions']) ? $this->options['system_prompt_instructions'] : '';
3930 +
3931 + // Add system prompt to relevant content
3932 + $content_with_instructions = $system_prompt_instructions . " " . $relevant_content;
3933 +
3934 + // Format messages for Gemini API
3935 + $formatted_messages = [];
3936 +
3937 + // Add system message as the first user message with role prefix
3938 + // Note: Gemini doesn't have a dedicated system role, so we use a prefixed user message
3939 + $formatted_messages[] = [
3940 + 'role' => 'user',
3941 + 'parts' => [
3942 + ['text' => "[System Instructions] " . $content_with_instructions]
3943 + ]
3944 + ];
3945 +
3946 + // Add model response to acknowledge system instructions
3947 + $formatted_messages[] = [
3948 + 'role' => 'model',
3949 + 'parts' => [
3950 + ['text' => "I understand and will follow these instructions."]
3951 + ]
3952 + ];
3953 +
3954 + // Process the rest of the conversation history
3955 + $current_role = null;
3956 + $current_parts = [];
3957 +
3958 + foreach ($conversation_history as $message) {
3959 + // Skip the first system message as we already handled it
3960 + if ($message['role'] === 'system') {
3961 + continue;
3962 + }
3963 +
3964 + // Map roles to Gemini format
3965 + $gemini_role = '';
3966 + if ($message['role'] === 'user') {
3967 + $gemini_role = 'user';
3968 + } else if (in_array($message['role'], ['assistant', 'bot', 'agent'])) {
3969 + $gemini_role = 'model';
3970 + } else {
3971 + // Skip unsupported roles
3972 + continue;
3973 + }
3974 +
3975 + // If we have a new role, add the previous message
3976 + if ($current_role !== null && $current_role !== $gemini_role && !empty($current_parts)) {
3977 + $formatted_messages[] = [
3978 + 'role' => $current_role,
3979 + 'parts' => $current_parts
3980 + ];
3981 + $current_parts = [];
3982 + }
3983 +
3984 + // Set current role and add text to parts
3985 + $current_role = $gemini_role;
3986 + $current_parts[] = ['text' => $message['content']];
3987 + }
3988 +
3989 + // Add the last message if there's content
3990 + if ($current_role !== null && !empty($current_parts)) {
3991 + $formatted_messages[] = [
3992 + 'role' => $current_role,
3993 + 'parts' => $current_parts
3994 + ];
3995 + }
3996 +
3997 + // Build the request body
3998 + $body = json_encode([
3999 + 'contents' => $formatted_messages,
4000 + 'generationConfig' => [
4001 + 'temperature' => 0.7,
4002 + 'topP' => 0.95,
4003 + 'topK' => 40,
4004 + 'maxOutputTokens' => 8192,
4005 + ],
4006 + 'safetySettings' => [
4007 + [
4008 + 'category' => 'HARM_CATEGORY_HARASSMENT',
4009 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
4010 + ],
4011 + [
4012 + 'category' => 'HARM_CATEGORY_HATE_SPEECH',
4013 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
4014 + ],
4015 + [
4016 + 'category' => 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
4017 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
4018 + ],
4019 + [
4020 + 'category' => 'HARM_CATEGORY_DANGEROUS_CONTENT',
4021 + 'threshold' => 'BLOCK_MEDIUM_AND_ABOVE'
4022 + ]
4023 + ]
4024 + ]);
4025 +
4026 + // Prepare the API endpoint
4027 + $api_endpoint = 'https://generativelanguage.googleapis.com/v1/models/' . $selected_model . ':generateContent?key=' . $gemini_api_key;
4028 +
4029 + // Set up the API request
4030 + $args = [
4031 + 'body' => $body,
4032 + 'headers' => [
4033 + 'Content-Type' => 'application/json',
4034 + ],
4035 + 'timeout' => 60,
4036 + 'redirection' => 5,
4037 + 'blocking' => true,
4038 + 'httpversion' => '1.0',
4039 + 'sslverify' => true,
4040 + ];
4041 +
4042 + // Make the API request
4043 + $response = wp_remote_post($api_endpoint, $args);
4044 +
4045 + // Process the response
4046 + if (is_wp_error($response)) {
4047 + return "Sorry, there was an error processing your request: " . $response->get_error_message();
4048 + }
4049 +
4050 + $response_body = json_decode(wp_remote_retrieve_body($response), true);
4051 +
4052 + // Handle potential errors in the response
4053 + if (isset($response_body['error'])) {
4054 + //error_log('Gemini API Error: ' . json_encode($response_body['error']));
4055 + return "Sorry, there was an error with the Gemini API: " .
4056 + (isset($response_body['error']['message']) ? $response_body['error']['message'] : 'Unknown error');
4057 + }
4058 +
4059 + // Extract the response text
4060 + if (isset($response_body['candidates'][0]['content']['parts'][0]['text'])) {
4061 + return trim($response_body['candidates'][0]['content']['parts'][0]['text']);
4062 + } else {
4063 + //error_log('Unexpected Gemini API response format: ' . json_encode($response_body));
4064 + return "Sorry, I couldn't process that request. The response format was unexpected.";
4065 + }
4066 +}
4067 +
4068 +
4069 +
4070 +public function mxchat_dismiss_pre_chat_message() {
4071 + // Get and sanitize the user identifier
4072 + $user_id = $this->mxchat_get_user_identifier();
4073 + $user_id = sanitize_key($user_id);
4074 +
4075 + // Set a transient to track that the user has dismissed the pre-chat message
4076 + $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
4077 + set_transient($transient_key, true, DAY_IN_SECONDS);
4078 +
4079 + wp_send_json_success();
4080 +}
4081 +
4082 +public function mxchat_check_pre_chat_message_status() {
4083 + // Get and sanitize the user identifier
4084 + $user_id = $this->mxchat_get_user_identifier();
4085 + $user_id = sanitize_key($user_id);
4086 +
4087 + // Check if the transient exists (i.e., if the message was dismissed)
4088 + $transient_key = 'mxchat_pre_chat_message_dismissed_' . $user_id;
4089 + $dismissed = get_transient($transient_key);
4090 +
4091 + // Log the result to see if it's being set correctly
4092 + //error_log("Check pre-chat message dismissed for $user_id: " . ($dismissed ? 'Yes' : 'No'));
4093 +
4094 + if ($dismissed) {
4095 + wp_send_json_success(['dismissed' => true]);
4096 + } else {
4097 + wp_send_json_success(['dismissed' => false]);
4098 + }
4099 +
4100 + wp_die();
4101 +}
4102 +
4103 +private function mxchat_calculate_cosine_similarity($vectorA, $vectorB) {
4104 + if (!is_array($vectorA) || !is_array($vectorB) || empty($vectorA) || empty($vectorB)) {
4105 + return 0;
4106 + }
4107 +
4108 + $dotProduct = array_sum(array_map(function ($a, $b) {
4109 + return $a * $b;
4110 + }, $vectorA, $vectorB));
4111 + $normA = sqrt(array_sum(array_map(function ($a) {
4112 + return $a * $a;
4113 + }, $vectorA)));
4114 + $normB = sqrt(array_sum(array_map(function ($b) {
4115 + return $b * $b;
4116 + }, $vectorB)));
4117 +
4118 + if ($normA == 0 || $normB == 0) {
4119 + return 0;
4120 + }
4121 +
4122 + return $dotProduct / ($normA * $normB);
4123 + }
4124 +
4125 +public function mxchat_enqueue_scripts_styles() {
4126 + // Define version numbers for the styles and scripts
4127 + $chat_style_version = '2.1.7';
4128 + $chat_script_version = '2.1.7';
4129 +
4130 + // Enqueue the script
4131 + wp_enqueue_script(
4132 + 'mxchat-chat-js',
4133 + plugin_dir_url(__FILE__) . '../js/chat-script.js',
4134 + array('jquery'),
4135 + $chat_script_version,
4136 + true
4137 + );
4138 +
4139 + // Enqueue the CSS
4140 + wp_enqueue_style(
4141 + 'mxchat-chat-css',
4142 + plugin_dir_url(__FILE__) . '../css/chat-style.css',
4143 + array(),
4144 + $chat_style_version
4145 + );
4146 +
4147 + // Fetch options from the database
4148 + $this->options = get_option('mxchat_options');
4149 + $prompts_options = get_option('mxchat_prompts_options', array());
4150 +
4151 + // Prepare settings for JavaScript
4152 + $style_settings = array(
4153 + 'ajax_url' => admin_url('admin-ajax.php'),
4154 + 'nonce' => wp_create_nonce('mxchat_chat_nonce'),
4155 + 'link_target_toggle' => $this->options['link_target_toggle'] ?? 'off',
4156 + 'rate_limit_message' => $this->options['rate_limit_message'] ?? 'Rate limit exceeded. Please try again later.',
4157 + 'complianz_toggle' => isset($this->options['complianz_toggle']) && $this->options['complianz_toggle'] === 'on',
4158 + 'user_message_bg_color' => $this->options['user_message_bg_color'] ?? '#fff',
4159 + 'user_message_font_color' => $this->options['user_message_font_color'] ?? '#212121',
4160 + 'bot_message_bg_color' => $this->options['bot_message_bg_color'] ?? '#212121',
4161 + 'bot_message_font_color' => $this->options['bot_message_font_color'] ?? '#fff',
4162 + 'top_bar_bg_color' => $this->options['top_bar_bg_color'] ?? '#212121',
4163 + 'send_button_font_color' => $this->options['send_button_font_color'] ?? '#212121',
4164 + 'close_button_color' => $this->options['close_button_color'] ?? '#fff',
4165 + 'chatbot_background_color' => $this->options['chatbot_background_color'] ?? '#212121',
4166 + 'chatbot_bg_color' => $this->options['chatbot_bg_color'] ?? '#fff',
4167 + 'icon_color' => $this->options['icon_color'] ?? '#fff',
4168 + 'chat_input_font_color' => $this->options['chat_input_font_color'] ?? '#212121',
4169 + 'chat_persistence_toggle' => $this->options['chat_persistence_toggle'] ?? 'off',
4170 + 'appendWidgetToBody' => $this->options['append_to_body'] ?? 'off', // Example for consistency
4171 +
4172 + 'live_agent_message_bg_color' => $this->options['live_agent_message_bg_color'] ?? '#ffffff',
4173 + 'live_agent_message_font_color' => $this->options['live_agent_message_font_color'] ?? '#333333',
4174 + 'chat_toolbar_toggle' => $this->options['chat_toolbar_toggle'] ?? 'off',
4175 + 'mode_indicator_bg_color' => $this->options['mode_indicator_bg_color'] ?? '#767676',
4176 + 'mode_indicator_font_color' => $this->options['mode_indicator_font_color'] ?? '#ffffff',
4177 + 'toolbar_icon_color' => $this->options['toolbar_icon_color'] ?? '#212121',
4178 +
4179 + 'use_pinecone' => $prompts_options['mxchat_use_pinecone'] ?? '0',
4180 + 'pinecone_enabled' => isset($prompts_options['mxchat_use_pinecone']) && $prompts_options['mxchat_use_pinecone'] === '1'
4181 + );
4182 +
4183 + // Pass the settings to the script
4184 + wp_localize_script('mxchat-chat-js', 'mxchatChat', $style_settings);
4185 +}
4186 +
4187 +
4188 +// Modify the mxchat_reset_rate_limits function to handle different timeframes
4189 +public function mxchat_reset_rate_limits() {
4190 + global $wpdb;
4191 + $all_options = get_option('mxchat_options', []);
4192 + $current_time = time();
4193 +
4194 + // Get all rate limit options
4195 + $option_names = $wpdb->get_col("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'mxchat_chat_limit_%'");
4196 +
4197 + foreach ($option_names as $option_name) {
4198 + // Parse the option name to extract role and user ID
4199 + // Format: mxchat_chat_limit_ROLE_USERID or mxchat_chat_limit_logged_out_IP
4200 + $parts = explode('_', $option_name);
4201 +
4202 + // Skip if the option name doesn't match our expected format
4203 + if (count($parts) < 4) {
4204 + continue;
4205 + }
4206 +
4207 + // Extract role (may be multiple parts like 'shop_manager')
4208 + $role_parts = array_slice($parts, 3, -1); // Get all parts between 'mxchat_chat_limit_' and the last part (user ID)
4209 + $role = implode('_', $role_parts);
4210 +
4211 + // Skip if role doesn't exist in our settings
4212 + if (!isset($all_options['rate_limits'][$role])) {
4213 + continue;
4214 + }
4215 +
4216 + $timeframe = $all_options['rate_limits'][$role]['timeframe'];
4217 + $limit_data = get_option($option_name);
4218 +
4219 + if (!$limit_data || !is_array($limit_data) || !isset($limit_data['timestamp'])) {
4220 + continue;
4221 + }
4222 +
4223 + $timestamp = $limit_data['timestamp'];
4224 + $should_reset = false;
4225 +
4226 + // Determine if we should reset based on the timeframe
4227 + switch ($timeframe) {
4228 + case 'hourly':
4229 + $should_reset = ($current_time - $timestamp) >= 3600; // 1 hour
4230 + break;
4231 + case 'daily':
4232 + $should_reset = ($current_time - $timestamp) >= 86400; // 24 hours
4233 + break;
4234 + case 'weekly':
4235 + $should_reset = ($current_time - $timestamp) >= 604800; // 7 days
4236 + break;
4237 + case 'monthly':
4238 + $should_reset = ($current_time - $timestamp) >= 2592000; // 30 days
4239 + break;
4240 + }
4241 +
4242 + // Reset the counter if the timeframe has passed
4243 + if ($should_reset) {
4244 + delete_option($option_name);
4245 + wp_cache_delete($option_name, 'options');
4246 + }
4247 + }
4248 +
4249 + // Clean up any orphaned entries
4250 + wp_cache_delete('mxchat_all_chat_limits', 'options');
4251 +}
4252 +private function mxchat_fetch_woocommerce_products() {
4253 + // Ensure WooCommerce is active
4254 + if (!class_exists('WooCommerce')) {
4255 + return [];
4256 + }
4257 +
4258 + $args = array(
4259 + 'post_type' => 'product',
4260 + 'post_status' => 'publish',
4261 + 'posts_per_page' => -1,
4262 + );
4263 +
4264 + $products = get_posts($args);
4265 + $product_data = [];
4266 +
4267 + foreach ($products as $product) {
4268 + $product_id = $product->ID;
4269 + $product_obj = wc_get_product($product_id);
4270 +
4271 + $product_data[] = array(
4272 + 'id' => $product_id,
4273 + 'name' => $product_obj->get_name(),
4274 + 'description' => $product_obj->get_description(),
4275 + 'short_description' => $product_obj->get_short_description(),
4276 + 'url' => get_permalink($product_id),
4277 + 'price' => $product_obj->get_regular_price(),
4278 + 'sale_price' => $product_obj->get_sale_price(),
4279 + 'stock_status' => $product_obj->get_stock_status(),
4280 + 'sku' => $product_obj->get_sku(),
4281 + 'in_stock' => $product_obj->is_in_stock(),
4282 + 'total_sales' => $product_obj->get_total_sales(),
4283 + );
4284 + }
4285 +
4286 + return $product_data;
4287 +}
4288 +
4289 +
4290 +/**
4291 + * Check if the current user has exceeded their rate limit based on role
4292 + *
4293 + * @return true|array True if limit not exceeded, or array with error message if exceeded
4294 + */
4295 +public function check_rate_limit() {
4296 + $all_options = get_option('mxchat_options', []);
4297 + //error_log('MXChat Rate Limit: Starting check');
4298 + //error_log('MXChat Rate Limit: Options: ' . print_r($all_options, true));
4299 +
4300 + // Determine user role or if logged out
4301 + if (is_user_logged_in()) {
4302 + $user = wp_get_current_user();
4303 + $user_id = $user->ID;
4304 +
4305 + // Get the user's primary role (first in the array)
4306 + $user_roles = $user->roles;
4307 + $role = !empty($user_roles) ? $user_roles[0] : 'subscriber'; // Default to subscriber if no role found
4308 + //error_log('MXChat Rate Limit: User ID: ' . $user_id . ', Role: ' . $role);
4309 + } else {
4310 + $role = 'logged_out';
4311 + // Use IP address for non-logged-in users
4312 + $user_id = $this->get_client_ip();
4313 + //error_log('MXChat Rate Limit: Logged out user IP: ' . $user_id);
4314 + }
4315 +
4316 + // Check if rate limits are configured for this role
4317 + if (!isset($all_options['rate_limits'][$role])) {
4318 + //error_log('MXChat Rate Limit: No rate limit configured for role: ' . $role);
4319 + return true; // No limit set for this role
4320 + }
4321 +
4322 + $limit = $all_options['rate_limits'][$role]['limit'];
4323 + //error_log('MXChat Rate Limit: Limit for role ' . $role . ': ' . $limit);
4324 +
4325 + // If unlimited, return true immediately
4326 + if ($limit === 'unlimited') {
4327 + //error_log('MXChat Rate Limit: Unlimited setting, no limit applied');
4328 + return true;
4329 + }
4330 +
4331 + // Get the option name for this user/role
4332 + $option_name = 'mxchat_chat_limit_' . $role . '_' . $user_id;
4333 + //error_log('MXChat Rate Limit: Option name: ' . $option_name);
4334 +
4335 + // Get the counter data
4336 + $limit_data = get_option($option_name, ['count' => 0, 'timestamp' => time()]);
4337 + //error_log('MXChat Rate Limit: Current limit data: ' . print_r($limit_data, true));
4338 +
4339 + // If first request or counter reset needed, set the initial timestamp
4340 + if ($limit_data['count'] === 0) {
4341 + $limit_data['timestamp'] = time();
4342 + update_option($option_name, $limit_data);
4343 + //error_log('MXChat Rate Limit: First request, initialized timestamp');
4344 + }
4345 +
4346 + // Get the timeframe
4347 + $timeframe = isset($all_options['rate_limits'][$role]['timeframe']) ?
4348 + $all_options['rate_limits'][$role]['timeframe'] : 'daily';
4349 + //error_log('MXChat Rate Limit: Timeframe: ' . $timeframe);
4350 +
4351 + // Check if the counter needs to be reset based on timeframe
4352 + $current_time = time();
4353 + $timestamp = $limit_data['timestamp'];
4354 + $should_reset = false;
4355 +
4356 + switch ($timeframe) {
4357 + case 'hourly':
4358 + $should_reset = ($current_time - $timestamp) >= 3600; // 1 hour
4359 + break;
4360 + case 'daily':
4361 + $should_reset = ($current_time - $timestamp) >= 86400; // 24 hours
4362 + break;
4363 + case 'weekly':
4364 + $should_reset = ($current_time - $timestamp) >= 604800; // 7 days
4365 + break;
4366 + case 'monthly':
4367 + $should_reset = ($current_time - $timestamp) >= 2592000; // 30 days
4368 + break;
4369 + }
4370 +
4371 + //error_log('MXChat Rate Limit: Current time: ' . $current_time . ', Last timestamp: ' . $timestamp);
4372 + //error_log('MXChat Rate Limit: Time elapsed: ' . ($current_time - $timestamp) . ' seconds');
4373 + //error_log('MXChat Rate Limit: Should reset: ' . ($should_reset ? 'Yes' : 'No'));
4374 +
4375 + // Reset the counter if the timeframe has passed
4376 + if ($should_reset) {
4377 + $limit_data = ['count' => 0, 'timestamp' => $current_time];
4378 + update_option($option_name, $limit_data);
4379 + //error_log('MXChat Rate Limit: Reset counter to 0');
4380 + }
4381 +
4382 + // Check if user has exceeded their limit
4383 + if ($limit_data['count'] >= intval($limit)) {
4384 + // Get the custom message for this role
4385 + $message = !empty($all_options['rate_limits'][$role]['message'])
4386 + ? $all_options['rate_limits'][$role]['message']
4387 + : __('Rate limit exceeded. Please try again later.', 'mxchat');
4388 +
4389 + // Add timeframe information to the message if placeholders exist
4390 + $timeframe_label = '';
4391 + switch ($timeframe) {
4392 + case 'hourly':
4393 + $timeframe_label = __('hour', 'mxchat');
4394 + break;
4395 + case 'daily':
4396 + $timeframe_label = __('day', 'mxchat');
4397 + break;
4398 + case 'weekly':
4399 + $timeframe_label = __('week', 'mxchat');
4400 + break;
4401 + case 'monthly':
4402 + $timeframe_label = __('month', 'mxchat');
4403 + break;
4404 + }
4405 +
4406 + // Replace placeholders in the message
4407 + $message = str_replace(
4408 + ['{limit}', '{count}', '{remaining}', '{timeframe}'],
4409 + [intval($limit), $limit_data['count'], max(0, intval($limit) - $limit_data['count']), $timeframe_label],
4410 + $message
4411 + );
4412 +
4413 + //error_log('MXChat Rate Limit: Limit exceeded. Message: ' . $message);
4414 +
4415 + // Return error with the custom message
4416 + return [
4417 + 'error' => true,
4418 + 'message' => $message
4419 + ];
4420 + }
4421 +
4422 + // Increment the counter
4423 + $limit_data['count']++;
4424 + update_option($option_name, $limit_data);
4425 + //error_log('MXChat Rate Limit: Incremented counter to ' . $limit_data['count']);
4426 +
4427 + return true;
4428 +}
4429 +
4430 +// Helper function to get client IP address
4431 +private function get_client_ip() {
4432 + // Check for shared internet/ISP IP
4433 + if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
4434 + return sanitize_text_field($_SERVER['HTTP_CLIENT_IP']);
4435 + }
4436 +
4437 + // Check for IPs passing through proxies
4438 + if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
4439 + // Use the first value in the comma-separated list
4440 + $forwarded_for = explode(',', sanitize_text_field($_SERVER['HTTP_X_FORWARDED_FOR']));
4441 + return trim($forwarded_for[0]);
4442 + }
4443 +
4444 + if (!empty($_SERVER['REMOTE_ADDR'])) {
4445 + return sanitize_text_field($_SERVER['REMOTE_ADDR']);
4446 + }
4447 +
4448 + // Fallback
4449 + return 'unknown';
4450 +}
4451 +
4452 +}
4453 +?>