PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / trunk
MxChat – AI Chatbot & Content Generation for WordPress vtrunk
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
mxchat-basic / admin / class-ajax-handler.php

class-ajax-handler.php in MxChat – AI Chatbot & Content Generation for WordPress trunk, at admin/class-ajax-handler.php

2,037 lines 91.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * File: admin/class-ajax-handler.php
4 *
5 * Handles all AJAX requests for MxChat admin functionality
6 */
7
8 if (!defined('ABSPATH')) {
9 exit; // Exit if accessed directly
10 }
11
12 class MxChat_Ajax_Handler {
13
14 private $pinecone_manager = null;
15
16 /**
17 * Constructor - Register all AJAX hooks
18 */
19 public function __construct() {
20 $this->mxchat_init_ajax_hooks();
21 }
22
23
24 /**
25 * Register all AJAX action hooks
26 */
27 private function mxchat_init_ajax_hooks() {
28 // Settings AJAX
29 add_action('wp_ajax_mxchat_save_setting', array($this, 'mxchat_save_setting_callback'));
30 add_action('wp_ajax_mxchat_save_prompts_setting', array($this, 'mxchat_save_prompts_setting_callback'));
31 add_action('wp_ajax_mxchat_acf_toggle_group', array($this, 'mxchat_acf_toggle_group_callback'));
32 add_action('wp_ajax_migrate_pinecone_settings', array($this, 'ajax_migrate_pinecone_settings'));
33
34 // License AJAX
35 add_action('wp_ajax_mxchat_handle_activate_license', array($this, 'mxchat_handle_activate_license'));
36 add_action('wp_ajax_mxchat_check_license_status', array($this, 'mxchat_check_license_status'));
37 add_action('wp_ajax_mxchat_deactivate_license', array($this, 'mxchat_deactivate_license'));
38
39 // Actions & Intents AJAX
40 add_action('wp_ajax_mxchat_toggle_action', array($this, 'mxchat_toggle_action'));
41 add_action('wp_ajax_mxchat_update_intent_threshold', array($this, 'mxchat_update_intent_threshold'));
42
43 add_action('wp_ajax_mxchat_save_selected_bot', array($this, 'mxchat_save_selected_bot'));
44 add_action('wp_ajax_mxchat_check_api_keys', array($this, 'mxchat_check_api_keys'));
45
46 // Debug & Optimization AJAX
47 add_action('wp_ajax_mxchat_toggle_debug_mode', array($this, 'mxchat_toggle_debug_mode_callback'));
48 add_action('wp_ajax_mxchat_get_debug_log', array($this, 'mxchat_get_debug_log_callback'));
49 add_action('wp_ajax_mxchat_clear_debug_log', array($this, 'mxchat_clear_debug_log_callback'));
50 add_action('wp_ajax_mxchat_export_settings', array($this, 'mxchat_export_settings_callback'));
51 add_action('wp_ajax_mxchat_reset_all_settings', array($this, 'mxchat_reset_all_settings_callback'));
52
53 // Global rate-limit usage counter reset (admin-only, nonce-guarded)
54 add_action('wp_ajax_mxchat_reset_global_rate_limit', array($this, 'mxchat_reset_global_rate_limit_callback'));
55
56 // Custom (OpenAI-compatible) Provider connection test
57 add_action('wp_ajax_mxchat_test_custom_provider', array($this, 'mxchat_test_custom_provider_callback'));
58
59 // Built-in provider key validation — cheap per-provider auth check (plan-mxchat-20260623-c41f74)
60 add_action('wp_ajax_mxchat_test_provider_key', array($this, 'mxchat_test_provider_key_callback'));
61
62 // Custom Post Meta discovery scan for the KB whitelist picker (plan-mxchat-20260709-fe8e4e)
63 add_action('wp_ajax_mxchat_scan_custom_meta_keys', array($this, 'mxchat_scan_custom_meta_keys_callback'));
64 }
65
66 /**
67 * Discover non-ACF custom post-meta keys present on published public content, so the
68 * KB → Custom Post Meta section can offer a click-to-add picker instead of a blind
69 * "type the exact key you already know" textarea. plan-mxchat-20260709-fe8e4e.
70 *
71 * Bounded + button-triggered only (never on page load). Returns up to 50 keys by
72 * frequency, each with a short sample value, so the owner can judge relevance before
73 * whitelisting. Underscore-prefixed (protected/internal) keys are hidden unless the
74 * caller opts in; ACF-managed keys are excluded so this picker never double-lists the
75 * sibling ACF discovery picker on the same page.
76 */
77 public function mxchat_scan_custom_meta_keys_callback() {
78 check_ajax_referer('mxchat_prompts_setting_nonce');
79
80 if (!current_user_can('manage_options')) {
81 wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')]);
82 }
83
84 global $wpdb;
85
86 $include_internal = isset($_POST['include_internal']) && $_POST['include_internal'] === '1';
87
88 // Restrict discovery to public post types (the content the KB actually embeds).
89 $post_types = get_post_types(array('public' => true), 'names');
90 if (empty($post_types)) {
91 wp_send_json_success(array('keys' => array(), 'scanned' => 0));
92 }
93 $pt_placeholders = implode(',', array_fill(0, count($post_types), '%s'));
94
95 // Build the set of ACF-managed meta keys to exclude. ACF stores, alongside each
96 // value key `foo`, a reference key `_foo` whose value is the ACF field key
97 // (`field_xxxxx`). Strip the leading underscore from every such reference key to
98 // get the real meta key, and exclude those — the ACF picker on this page owns them.
99 $acf_managed = array();
100 $acf_refs = $wpdb->get_col(
101 $wpdb->prepare(
102 "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE %s AND meta_value LIKE %s",
103 $wpdb->esc_like('_') . '%',
104 $wpdb->esc_like('field_') . '%'
105 )
106 );
107 foreach ((array) $acf_refs as $ref_key) {
108 if (strlen($ref_key) > 1 && $ref_key[0] === '_') {
109 $acf_managed[substr($ref_key, 1)] = true;
110 }
111 }
112
113 // Discover keys + counts + a sample value in one bounded aggregate query.
114 // SUBSTRING(MIN(...)) keeps the sample selection ONLY_FULL_GROUP_BY-safe.
115 $params = $post_types;
116 $sql = "SELECT pm.meta_key AS mk, COUNT(*) AS n, SUBSTRING(MIN(pm.meta_value), 1, 200) AS sample
117 FROM {$wpdb->postmeta} pm
118 INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
119 WHERE p.post_status = 'publish'
120 AND p.post_type IN ($pt_placeholders)
121 AND pm.meta_key <> ''";
122 if (!$include_internal) {
123 $sql .= " AND pm.meta_key NOT LIKE %s";
124 $params[] = $wpdb->esc_like('_') . '%';
125 }
126 $sql .= " GROUP BY pm.meta_key ORDER BY n DESC, pm.meta_key ASC LIMIT 200";
127
128 // phpcs:ignore WordPress.DB.PreparedSQL — placeholders assembled above, values in $params.
129 $rows = $wpdb->get_results($wpdb->prepare($sql, $params));
130
131 $keys = array();
132 foreach ((array) $rows as $row) {
133 $mk = $row->mk;
134 if (isset($acf_managed[$mk])) {
135 continue; // already offered by the ACF picker
136 }
137
138 $raw = (string) $row->sample;
139 if ($raw !== '' && (is_serialized($raw) || preg_match('/^(a:\d+:\{|O:\d+:"|s:\d+:")/', $raw))) {
140 $sample = esc_html__('[structured value]', 'mxchat');
141 } else {
142 $sample = trim(preg_replace('/\s+/', ' ', $raw));
143 if (function_exists('mb_strlen') ? mb_strlen($sample) > 60 : strlen($sample) > 60) {
144 $sample = (function_exists('mb_substr') ? mb_substr($sample, 0, 60) : substr($sample, 0, 60)) . '';
145 }
146 if ($sample === '') {
147 $sample = esc_html__('(empty value)', 'mxchat');
148 }
149 }
150
151 $keys[] = array(
152 'key' => $mk,
153 'count' => (int) $row->n,
154 'sample' => $sample,
155 );
156
157 if (count($keys) >= 50) {
158 break;
159 }
160 }
161
162 wp_send_json_success(array(
163 'keys' => $keys,
164 'scanned' => is_array($rows) ? count($rows) : 0,
165 ));
166 }
167
168 /**
169 * Test connection to a Custom (OpenAI-compatible) provider by hitting its /models endpoint
170 * with whichever auth scheme the user configured. Reports model count or a clean error.
171 */
172 public function mxchat_test_custom_provider_callback() {
173 check_ajax_referer('mxchat_test_custom_provider');
174 if (!current_user_can('manage_options')) {
175 wp_send_json_error(array('message' => esc_html__('Unauthorized', 'mxchat')));
176 }
177
178 $options = get_option('mxchat_options', array());
179 $base_url = isset($options['custom_provider_base_url']) ? trim((string) $options['custom_provider_base_url']) : '';
180 $api_key = isset($options['custom_provider_api_key']) ? trim((string) $options['custom_provider_api_key']) : '';
181 $auth = isset($options['custom_provider_auth_scheme']) ? $options['custom_provider_auth_scheme'] : 'bearer';
182 $api_version = isset($options['custom_provider_api_version']) ? trim((string) $options['custom_provider_api_version']) : '';
183
184 if (empty($base_url)) {
185 wp_send_json_error(array('message' => esc_html__('Base URL is empty. Save it first.', 'mxchat')));
186 }
187
188 $url = rtrim($base_url, '/') . '/models';
189 if (!empty($api_version)) {
190 $url = add_query_arg('api-version', $api_version, $url);
191 }
192
193 $headers = array('Content-Type' => 'application/json');
194 if (!empty($api_key)) {
195 if ($auth === 'api-key') {
196 $headers['api-key'] = $api_key;
197 } else {
198 $headers['Authorization'] = 'Bearer ' . $api_key;
199 }
200 }
201
202 $response = wp_remote_get($url, array(
203 'headers' => $headers,
204 'timeout' => 10,
205 ));
206
207 if (is_wp_error($response)) {
208 wp_send_json_error(array('message' => sprintf(esc_html__('Network error: %s', 'mxchat'), esc_html($response->get_error_message()))));
209 }
210
211 $code = (int) wp_remote_retrieve_response_code($response);
212 if ($code === 401 || $code === 403) {
213 wp_send_json_error(array('message' => sprintf(esc_html__('Auth rejected (HTTP %d). Check API key and auth scheme.', 'mxchat'), $code)));
214 }
215 if ($code === 404) {
216 wp_send_json_error(array('message' => esc_html__('Endpoint not found (HTTP 404). Check the Base URL.', 'mxchat')));
217 }
218 if ($code < 200 || $code >= 300) {
219 wp_send_json_error(array('message' => sprintf(esc_html__('Upstream returned HTTP %d.', 'mxchat'), $code)));
220 }
221
222 $body = json_decode(wp_remote_retrieve_body($response), true);
223 $count = 0;
224 if (is_array($body)) {
225 if (isset($body['data']) && is_array($body['data'])) {
226 $count = count($body['data']);
227 } elseif (isset($body['models']) && is_array($body['models'])) {
228 $count = count($body['models']);
229 }
230 }
231
232 wp_send_json_success(array(
233 'message' => sprintf(esc_html__('Connection OK — %d model(s) reported.', 'mxchat'), $count),
234 'count' => $count,
235 ));
236 }
237
238 /**
239 * Validate a BUILT-IN provider key with the lightest authenticated call per
240 * provider (a /models or key-info GET — never a generation). Reads the posted
241 * key value so the owner can test BEFORE saving; falls back to the saved option
242 * when the field is empty. Mirrors mxchat_test_custom_provider_callback and the
243 * add-on test buttons (cf5bd5 veo / 8d16f1 perplexity). The key is never logged.
244 * plan-mxchat-20260623-c41f74.
245 */
246 public function mxchat_test_provider_key_callback() {
247 check_ajax_referer('mxchat_test_provider_key');
248 if (!current_user_can('manage_options')) {
249 wp_send_json_error(array('message' => esc_html__('Unauthorized', 'mxchat')));
250 }
251
252 $provider = isset($_POST['provider']) ? sanitize_key(wp_unslash($_POST['provider'])) : '';
253 $posted_key = isset($_POST['key']) ? trim((string) wp_unslash($_POST['key'])) : '';
254
255 $option_map = array(
256 'openai' => 'api_key',
257 'xai' => 'xai_api_key',
258 'claude' => 'claude_api_key',
259 'deepseek' => 'deepseek_api_key',
260 'gemini' => 'gemini_api_key',
261 'openrouter' => 'openrouter_api_key',
262 );
263 if (!isset($option_map[$provider])) {
264 wp_send_json_error(array('message' => esc_html__('Unknown provider.', 'mxchat')));
265 }
266
267 // Prefer the just-typed value (test-before-save); fall back to the saved key.
268 $key = $posted_key;
269 if ($key === '') {
270 $options = get_option('mxchat_options', array());
271 $key = isset($options[$option_map[$provider]]) ? trim((string) $options[$option_map[$provider]]) : '';
272 }
273 if ($key === '') {
274 wp_send_json_error(array('message' => esc_html__('No API key entered or saved for this provider.', 'mxchat')));
275 }
276
277 // Lightest authenticated metadata call per provider — model-agnostic, no generation.
278 $headers = array();
279 switch ($provider) {
280 case 'openai':
281 $url = 'https://api.openai.com/v1/models';
282 $headers = array('Authorization' => 'Bearer ' . $key);
283 break;
284 case 'xai':
285 $url = 'https://api.x.ai/v1/models';
286 $headers = array('Authorization' => 'Bearer ' . $key);
287 break;
288 case 'deepseek':
289 $url = 'https://api.deepseek.com/models';
290 $headers = array('Authorization' => 'Bearer ' . $key);
291 break;
292 case 'openrouter':
293 // /auth/key validates the key itself (the public /models list does not).
294 $url = 'https://openrouter.ai/api/v1/auth/key';
295 $headers = array('Authorization' => 'Bearer ' . $key);
296 break;
297 case 'gemini':
298 $url = add_query_arg(array('pageSize' => 1, 'key' => $key), 'https://generativelanguage.googleapis.com/v1beta/models');
299 break;
300 case 'claude':
301 $url = 'https://api.anthropic.com/v1/models';
302 $headers = array('x-api-key' => $key, 'anthropic-version' => '2023-06-01');
303 break;
304 default:
305 wp_send_json_error(array('message' => esc_html__('Unknown provider.', 'mxchat')));
306 }
307
308 $response = wp_remote_get($url, array(
309 'headers' => $headers,
310 'timeout' => 10,
311 ));
312
313 if (is_wp_error($response)) {
314 wp_send_json_error(array('message' => sprintf(esc_html__('Network error: %s', 'mxchat'), esc_html($response->get_error_message()))));
315 }
316
317 $code = (int) wp_remote_retrieve_response_code($response);
318 if ($code >= 200 && $code < 300) {
319 wp_send_json_success(array('message' => esc_html__('Key is valid.', 'mxchat')));
320 }
321
322 // Surface the provider's own error text when present (trimmed; key never echoed).
323 $detail = '';
324 $body = json_decode(wp_remote_retrieve_body($response), true);
325 if (is_array($body)) {
326 if (isset($body['error']['message'])) {
327 $detail = $body['error']['message'];
328 } elseif (isset($body['error']) && is_string($body['error'])) {
329 $detail = $body['error'];
330 } elseif (isset($body['message'])) {
331 $detail = $body['message'];
332 }
333 }
334 $detail = trim((string) $detail);
335 if (strlen($detail) > 200) {
336 $detail = substr($detail, 0, 200) . '';
337 }
338
339 if ($code === 401 || $code === 403) {
340 $msg = ($detail !== '')
341 ? sprintf(esc_html__('Key rejected (HTTP %1$d): %2$s', 'mxchat'), $code, esc_html($detail))
342 : sprintf(esc_html__('Key rejected (HTTP %d). Check the API key.', 'mxchat'), $code);
343 wp_send_json_error(array('message' => $msg));
344 }
345
346 $msg = ($detail !== '')
347 ? sprintf(esc_html__('Provider returned HTTP %1$d: %2$s', 'mxchat'), $code, esc_html($detail))
348 : sprintf(esc_html__('Provider returned HTTP %d.', 'mxchat'), $code);
349 wp_send_json_error(array('message' => $msg));
350 }
351
352 // ========================================
353 // SETTINGS AJAX HANDLERS
354 // ========================================
355
356 /**
357 * Validates and saves chat settings via AJAX request
358 */
359 public function mxchat_save_setting_callback() {
360 check_ajax_referer('mxchat_save_setting_nonce');
361 if (!current_user_can('manage_options')) {
362 ('MXChat Save: Unauthorized access attempt');
363 wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')]);
364 }
365
366 $name = isset($_POST['name']) ? $_POST['name'] : '';
367 // Remove WP's added slashes before saving (wp_unslash is the canonical form; plan-3f8158).
368 $value = isset($_POST['value']) ? wp_unslash($_POST['value']) : '';
369
370 //error_log('MXChat Save: Processing field name: ' . $name);
371 //error_log('MXChat Save: Field value: ' . $value);
372
373 if (empty($name)) {
374 //error_log('MXChat Save: Empty field name detected');
375 wp_send_json_error(['message' => esc_html__('Invalid field name', 'mxchat')]);
376 }
377
378 // Load the full options array
379 $options = get_option('mxchat_options', []);
380 //error_log('MXChat Save: Current options array: ' . print_r($options, true));
381
382 // Extract field name from mxchat_options[field_name] format if present
383 // But preserve the full name for special cases like rate_limits that need the full path
384 $field_name = $name;
385 if (preg_match('/^mxchat_options\[([^\[\]]+)\]$/', $name, $matches)) {
386 $field_name = $matches[1];
387 }
388
389 // Handle special cases
390 switch ($field_name) {
391 // Editor Assistant enable toggle (plan-8cb0cb). STANDALONE option — NOT part
392 // of mxchat_options, so it skips the mxchat_sanitize strip-trap entirely. Save
393 // it directly and short-circuit (mirrors the mxchat_transcripts_options pattern
394 // below); never falls through to the generic mxchat_options save. Default OFF.
395 case 'mxchat_editor_assistant_enabled':
396 $ea_value = ($value === 'on' || $value === '1') ? 'on' : 'off';
397 update_option('mxchat_editor_assistant_enabled', $ea_value);
398 wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
399 return;
400
401 // Smart asset loading toggle (plan-915355). STANDALONE option, same
402 // reasoning as the Editor Assistant case above — saved directly and
403 // short-circuited so it never touches mxchat_options / mxchat_sanitize.
404 // Default OFF (opt-in performance optimization).
405 case 'mxchat_smart_asset_loading':
406 $sal_value = ($value === 'on' || $value === '1') ? 'on' : 'off';
407 update_option('mxchat_smart_asset_loading', $sal_value);
408 wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
409 return;
410
411 // Hybrid keyword boost toggle (plan-38ffa1). STANDALONE option, same
412 // pattern. Enabling runs capability detection HERE, at admin-save time —
413 // building the FULLTEXT index during a visitor's chat request is not
414 // acceptable, and detection is a one-time cost the admin can wait on.
415 case 'mxchat_hybrid_keyword_toggle':
416 $hkb_value = ($value === 'on' || $value === '1') ? 'on' : 'off';
417 update_option('mxchat_hybrid_keyword_toggle', $hkb_value);
418 if ($hkb_value === 'on') {
419 MxChat_Utils::mxchat_hybrid_detect_capability(true);
420 }
421 wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
422 return;
423
424 // ACF→PDF import-time extraction (plan 11720c). STANDALONE option, same
425 // pattern. Moved from a per-import modal checkbox to an install-level
426 // setting on Knowledge → ACF Fields. Stored '1'/'0' to match the
427 // knowledge page's sibling toggles. Default OFF.
428 case 'mxchat_acf_pdf_extraction':
429 $apx_value = ($value === 'on' || $value === '1') ? '1' : '0';
430 update_option('mxchat_acf_pdf_extraction', $apx_value);
431 wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
432 return;
433
434 // In-chat YouTube card: master switch + its own confidence floor
435 // (plan f52492). STANDALONE options, same pattern as the cases above.
436 // Default ON — the card already ships, so this is an opt-OUT.
437 case 'mxchat_video_embed_enabled':
438 $vce_value = ($value === 'on' || $value === '1') ? 'on' : 'off';
439 update_option('mxchat_video_embed_enabled', $vce_value);
440 wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
441 return;
442
443 // Clamped to the same 20-95 the field advertises. An out-of-range or
444 // non-numeric POST is corrected rather than refused, and the corrected
445 // value is echoed back so the field can reconcile — a silently stored
446 // 0 here would put a video on every answer, which is the bug.
447 case 'mxchat_video_embed_threshold':
448 $vct_value = is_numeric($value)
449 ? (int) $value
450 : MXCHAT_VIDEO_EMBED_THRESHOLD_DEFAULT;
451 if ($vct_value < 20) { $vct_value = 20; }
452 if ($vct_value > 95) { $vct_value = 95; }
453 update_option('mxchat_video_embed_threshold', $vct_value);
454 wp_send_json_success([
455 'message' => esc_html__('Setting saved', 'mxchat'),
456 'value' => $vct_value,
457 ]);
458 return;
459
460 // Live-agent availability schedules (plans 8ccaa2 + 99d7a4). STANDALONE
461 // options, same reasoning as the Editor Assistant case above — nested
462 // structures that mxchat_sanitize() would strip on the next autosave of any
463 // other field. Each channel's value arrives as JSON from its own hidden
464 // input, which that channel's schedule editor keeps in sync; the class owns
465 // all validation. The bare legacy name is kept as a defense against a
466 // browser still running pre-split cached admin JS: that UI edited "both
467 // channels" as one, so its save writes both.
468 case 'live_agent_schedule_slack':
469 case 'live_agent_schedule_telegram':
470 case 'live_agent_schedule_webhook':
471 case 'live_agent_schedule':
472 if (!class_exists('MxChat_Live_Agent_Schedule')) {
473 wp_send_json_error(['message' => esc_html__('Schedule unavailable', 'mxchat')]);
474 return;
475 }
476 $decoded = json_decode($value, true);
477 if (!is_array($decoded)) {
478 wp_send_json_error(['message' => esc_html__('Invalid schedule', 'mxchat')]);
479 return;
480 }
481 $channels = ($field_name === 'live_agent_schedule')
482 ? array('slack', 'telegram')
483 : array(substr($field_name, strlen('live_agent_schedule_')));
484 $saved_schedule = null;
485 foreach ($channels as $schedule_channel) {
486 $saved_schedule = MxChat_Live_Agent_Schedule::save($schedule_channel, $decoded);
487 }
488 // Echo the normalized result so the editor can reconcile if it ever
489 // disagrees with the server (e.g. a time the class rejected).
490 wp_send_json_success([
491 'message' => esc_html__('Setting saved', 'mxchat'),
492 'schedule' => $saved_schedule,
493 ]);
494 return;
495
496 case 'model':
497 //error_log('MXChat Save: Processing model selection');
498 //error_log('MXChat Save: Model value received: ' . $value);
499 //error_log('MXChat Save: Value type: ' . gettype($value));
500 //error_log('MXChat Save: Value length: ' . strlen($value));
501 //error_log('MXChat Save: Value === "openrouter": ' . ($value === 'openrouter' ? 'YES' : 'NO'));
502
503 // Allow 'openrouter' or validate against whitelist
504 if ($value === 'openrouter') {
505 //error_log('MXChat Save: Setting model to openrouter');
506 $options['model'] = 'openrouter';
507 } else {
508 //error_log('MXChat Save: Checking against whitelist');
509 // Catalog refactor (plan-d14e89): canonical allowlist lives in
510 // includes/class-mxchat-model-catalog.php. A new chat model
511 // added there is automatically accepted by autosave.
512 if (!class_exists('MxChat_Model_Catalog')) {
513 require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-mxchat-model-catalog.php';
514 }
515 $allowed_models = MxChat_Model_Catalog::chat_model_ids();
516
517 //error_log('MXChat Save: in_array result: ' . (in_array($value, $allowed_models) ? 'YES' : 'NO'));
518
519 if (in_array($value, $allowed_models)) {
520 //error_log('MXChat Save: Model is in whitelist, saving');
521 $options['model'] = sanitize_text_field($value);
522 } else {
523 //error_log('MXChat Save: Invalid model rejected: ' . $value);
524 //error_log('MXChat Save: Allowed models: ' . print_r($allowed_models, true));
525 wp_send_json_error(['message' => esc_html__('Invalid model selected', 'mxchat')]);
526 return;
527 }
528 }
529 break;
530
531 case 'openrouter_selected_model':
532 //error_log('MXChat Save: Processing OpenRouter model: ' . $value);
533 $options['openrouter_selected_model'] = sanitize_text_field($value);
534 // Force immediate save for new keys
535 //error_log('MXChat Save: OpenRouter model saved immediately');
536 break;
537
538 case 'openrouter_selected_model_name':
539 //error_log('MXChat Save: Processing OpenRouter model name: ' . $value);
540 $options['openrouter_selected_model_name'] = sanitize_text_field($value);
541 // Force immediate save for new keys
542 //error_log('MXChat Save: OpenRouter model name saved immediately');
543 break;
544
545 case 'openrouter_api_key':
546 //error_log('MXChat Save: Processing OpenRouter API key');
547 $options['openrouter_api_key'] = sanitize_text_field($value);
548 break;
549
550 // REMOVED DUPLICATE case 'openrouter_selected_model_name' HERE!
551
552 case 'additional_popular_questions':
553 //error_log('MXChat Save: Processing additional_popular_questions');
554 $questions = json_decode($value, true); // No need for stripslashes here
555 if (is_array($questions)) {
556 $options[$field_name] = $questions;
557 // Also update old option for backwards compatibility
558 update_option('additional_popular_questions', $questions);
559 //error_log('MXChat Save: Saved ' . count($questions) . ' additional questions');
560 } else {
561 //error_log('MXChat Save: Failed to decode questions JSON');
562 }
563 break;
564 case 'email_blocker_header_content':
565 //error_log('MXChat Save: Processing email_blocker_header_content');
566 // Allow HTML content but sanitize it safely
567 $options[$field_name] = wp_kses_post($value);
568 break;
569 case 'intro_message':
570 // Stored-XSS hardening (Wordfence CWE-79, plan-3f8158): sanitize on save as
571 // defense in depth. wp_kses_post mirrors mxchat_sanitize() (the options.php
572 // save path) so both save routes treat intro_message identically and strip
573 // <script>/</textarea> breakout while keeping basic formatting + {visitor_name}.
574 $options[$field_name] = wp_kses_post($value);
575 break;
576 case 'email_blocker_button_text':
577 //error_log('MXChat Save: Processing email_blocker_button_text');
578 $options[$field_name] = sanitize_text_field($value);
579 break;
580 case 'name_field_placeholder':
581 //error_log('MXChat Save: Processing name_field_placeholder');
582 $options[$field_name] = sanitize_text_field($value);
583 break;
584 case 'consent_checkbox_label':
585 // b062c4 — same allowlist as the options.php save path and the
586 // widget render, so the stored label always equals the shown label.
587 $options[$field_name] = MxChat_Utils::sanitize_consent_label($value);
588 break;
589 case 'similarity_threshold':
590 //error_log('MXChat Save: Processing similarity_threshold');
591 // Validate and save - enforce min 20, max 85
592 $threshold = intval($value);
593 if ($threshold < 20) $threshold = 20;
594 if ($threshold > 85) $threshold = 85;
595 $options[$field_name] = $threshold;
596 break;
597 case 'rag_sources_limit':
598 //error_log('MXChat Save: Processing rag_sources_limit');
599 // Validate and save - enforce min 3, max 10, default 6
600 $rag_limit = intval($value);
601 if ($rag_limit < 3) $rag_limit = 3;
602 if ($rag_limit > 10) $rag_limit = 10;
603 $options[$field_name] = $rag_limit;
604 break;
605 case 'rag_chunks_limit':
606 // Validate and save - enforce min 8, max 20, default 15
607 $chunks_limit = intval($value);
608 if ($chunks_limit < 8) $chunks_limit = 8;
609 if ($chunks_limit > 20) $chunks_limit = 20;
610 $options[$field_name] = $chunks_limit;
611 break;
612 case 'live_agent_status':
613 //error_log('MXChat Save: Processing live_agent_status');
614 // Set the new value
615 $options[$field_name] = ($value === 'on') ? 'on' : 'off';
616 break;
617 // Shared handoff channel (plan 1a2666): re-probe the channel's privacy
618 // at configuration time so the settings screen can warn about private
619 // channels (their inbound events arrive as message.groups, which the
620 // documented app setup never subscribes to). Only id-shaped values can
621 // be checked before the first handoff resolves a #name — the handoff
622 // path probes those when it caches the resolved id.
623 case 'live_agent_shared_channel':
624 $options[$field_name] = sanitize_text_field($value);
625 delete_option('mxchat_slack_shared_channel_privacy');
626 $shared_channel_target = ltrim(trim((string) $options[$field_name]), '#');
627 if ($shared_channel_target !== '' && preg_match('/^[CG][A-Z0-9]{6,}$/', $shared_channel_target)) {
628 if (!class_exists('MxChat_Integrator')) {
629 require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-mxchat-integrator.php';
630 }
631 MxChat_Integrator::mxchat_probe_slack_channel_privacy(
632 $options['live_agent_bot_token'] ?? '',
633 $shared_channel_target,
634 trim((string) $options[$field_name])
635 );
636 }
637 break;
638 // Webhook handoff destination (plan d88e22). Status normalized like the
639 // other channel toggles; the URL is refused outright when it isn't
640 // https so the admin hears about it at save time instead of the
641 // handoff silently never firing.
642 case 'webhook_handoff_status':
643 $options[$field_name] = ($value === 'on') ? 'on' : 'off';
644 break;
645 case 'webhook_handoff_url':
646 $wh_url = trim((string) $value);
647 if ($wh_url === '') {
648 $options[$field_name] = '';
649 break;
650 }
651 $wh_clean = esc_url_raw($wh_url, array('https'));
652 if ($wh_clean === '' || stripos($wh_clean, 'https://') !== 0) {
653 wp_send_json_error(['message' => esc_html__('Webhook URL must start with https://', 'mxchat')]);
654 return;
655 }
656 $options[$field_name] = $wh_clean;
657 break;
658 case 'enable_web_search':
659 //error_log('MXChat Save: Processing enable_web_search');
660 $options[$field_name] = ($value === 'on') ? 'on' : 'off';
661 break;
662 case 'enable_woocommerce_integration':
663 //error_log('MXChat Save: Processing enable_woocommerce_integration');
664 // Handle values that used to be 1/0
665 $options[$field_name] = ($value === 'on' || $value === '1') ? 'on' : 'off';
666 break;
667 case 'post_type_visibility_mode':
668 // Validate mode value
669 $allowed_modes = array('all', 'include', 'exclude');
670 $options[$field_name] = in_array($value, $allowed_modes) ? $value : 'all';
671 break;
672 case 'post_type_visibility_list':
673 // Handle JSON array of post types
674 $post_types = json_decode($value, true);
675 if (is_array($post_types)) {
676 // Sanitize each post type slug
677 $options[$field_name] = array_map('sanitize_key', $post_types);
678 } else {
679 $options[$field_name] = array();
680 }
681 break;
682 case 'script_loading_strategy':
683 // Validate script loading strategy value
684 $allowed_strategies = array('default', 'defer', 'delay_1s', 'delay_3s', 'delay_5s', 'on_interaction');
685 $options[$field_name] = in_array($value, $allowed_strategies) ? $value : 'default';
686 break;
687 case 'auto_retry_on_transient_error':
688 // Boolean toggle — accept 1/0/on/off, default to '1' if any truthy value.
689 $options[$field_name] = ($value === '1' || $value === 'on' || $value === 1 || $value === true) ? '1' : '0';
690 break;
691 default:
692 // Handle transcripts options
693 if (strpos($name, 'mxchat_transcripts_options') !== false) {
694 // Extract field name from mxchat_transcripts_options[field_name]
695 if (preg_match('/mxchat_transcripts_options\[([^\]]+)\]/', $name, $matches)) {
696 $field_name = $matches[1];
697
698 // Get current transcripts options
699 $transcripts_options = get_option('mxchat_transcripts_options', array());
700
701 // Ensure it's an array
702 if (!is_array($transcripts_options)) {
703 $transcripts_options = array();
704 }
705
706 // Handle checkbox values (convert 'on'/'off' to 1/0)
707 if ($field_name === 'mxchat_retention_days') {
708 // Number field, NOT a checkbox — without this branch a
709 // value of '1' would hit the 'on'/'1' coercion below
710 // (harmlessly) but nothing would clamp: this direct-DB
711 // path bypasses the registered sanitiser and its
712 // 0-3650 clamp entirely (plan-3c3338).
713 $transcripts_options[$field_name] = max(0, min(3650, (int) $value));
714 } else if ($value === 'on' || $value === '1') {
715 $transcripts_options[$field_name] = 1;
716 } else if ($value === 'off' || $value === '0' || $value === '') {
717 $transcripts_options[$field_name] = 0;
718 } else {
719 // For text/select fields, sanitize appropriately
720 if ($field_name === 'mxchat_notification_email') {
721 // sanitize_email() alone CANNOT validate this field: given
722 // "a@x.com, b@y.com" it returns the single concatenated
723 // address "a@x.comby.com", which is_email() then accepts.
724 // That is how two addresses used to be stored as one dead
725 // one, silently. MxChat_Utils validates the raw parts first
726 // and refuses the whole list if any of them is bad.
727 $parsed = MxChat_Utils::parse_notification_emails($value);
728 if ($parsed['error'] !== '') {
729 // Reject: the previously stored value stays untouched.
730 wp_send_json_error(array('message' => $parsed['error']));
731 }
732 $transcripts_options[$field_name] = implode(', ', $parsed['emails']);
733 } else {
734 $transcripts_options[$field_name] = sanitize_text_field($value);
735 }
736 }
737
738 // Use direct database update to bypass any filters
739 global $wpdb;
740
741 // Serialize the options array
742 $serialized = maybe_serialize($transcripts_options);
743
744 // Check if the option already exists in the database
745 $existing = $wpdb->get_var("SELECT option_id FROM {$wpdb->options} WHERE option_name = 'mxchat_transcripts_options'");
746
747 if ($existing) {
748 // Option exists, do an update
749 $result = $wpdb->update(
750 $wpdb->options,
751 array('option_value' => $serialized),
752 array('option_name' => 'mxchat_transcripts_options'),
753 array('%s'),
754 array('%s')
755 );
756 } else {
757 // Option doesn't exist (new install), do an insert
758 $result = $wpdb->insert(
759 $wpdb->options,
760 array(
761 'option_name' => 'mxchat_transcripts_options',
762 'option_value' => $serialized,
763 'autoload' => 'yes'
764 ),
765 array('%s', '%s', '%s')
766 );
767 }
768
769 // Clear all caches after direct DB update
770 wp_cache_delete('mxchat_transcripts_options', 'options');
771 wp_cache_delete('alloptions', 'options');
772 wp_cache_flush();
773
774 wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
775 return;
776 }
777 }
778 // Whole-chatbot global cap (sits in mxchat_options['rate_limits_global']).
779 // Field names: mxchat_options[rate_limits_global][limit|timeframe|limit_custom]
780 else if (strpos($name, 'mxchat_options[rate_limits_global]') !== false) {
781 preg_match('/\[rate_limits_global\]\[(.*?)\]/', $name, $matches);
782 if (isset($matches[1])) {
783 $setting_key = $matches[1];
784 if (!isset($options['rate_limits_global']) || !is_array($options['rate_limits_global'])) {
785 $options['rate_limits_global'] = array('limit' => 'unlimited', 'timeframe' => 'daily');
786 }
787 if ($setting_key === 'limit') {
788 // Selection from the preset dropdown. If __custom__, resolve from limit_custom; otherwise store directly.
789 if ($value === '__custom__') {
790 $custom = isset($options['rate_limits_global']['limit_custom']) ? (string) $options['rate_limits_global']['limit_custom'] : '';
791 if ($custom !== '' && ctype_digit($custom) && (int) $custom >= 1) {
792 $options['rate_limits_global']['limit'] = $custom;
793 }
794 // else leave existing limit untouched until the custom value arrives
795 } else {
796 $options['rate_limits_global']['limit'] = $value;
797 }
798 } elseif ($setting_key === 'limit_custom') {
799 $clean = preg_replace('/[^0-9]/', '', (string) $value);
800 $options['rate_limits_global']['limit_custom'] = $clean;
801 // Mirror a valid custom value into limit UNCONDITIONALLY (plan-74eb86).
802 // The custom number input is only editable when the dropdown is on
803 // "Custom…" (the toggle JS hides it for presets/unlimited) and autosave
804 // sends one field per change event, so a limit_custom change only fires
805 // in custom mode — there is no preset to clobber. The old guard required
806 // limit to already be non-preset, which it isn't on a first-time custom
807 // entry (the limit=__custom__ event arrives before limit_custom is set),
808 // so the value never landed in limit on the first save and reverted on refresh.
809 if ($clean !== '' && (int) $clean >= 1) {
810 $options['rate_limits_global']['limit'] = $clean;
811 }
812 } elseif ($setting_key === 'timeframe') {
813 $allowed_tf = array('hourly','daily','weekly','monthly');
814 $options['rate_limits_global']['timeframe'] = in_array($value, $allowed_tf, true) ? $value : 'daily';
815 }
816 }
817 }
818 // First check for rate limits settings
819 else if (strpos($name, 'mxchat_options[rate_limits]') !== false) {
820 //error_log('MXChat Save: Detected rate_limits field: ' . $name);
821
822 // Extract role ID and setting from the name
823 preg_match('/\[rate_limits\]\[(.*?)\]\[(.*?)\]/', $name, $matches);
824 //error_log('MXChat Save: Regex matches: ' . print_r($matches, true));
825
826 if (isset($matches[1]) && isset($matches[2])) {
827 $role_id = $matches[1];
828 $setting_key = $matches[2]; // limit, timeframe, message, or limit_custom
829
830 //error_log('MXChat Save: Role ID = ' . $role_id . ', Setting Key = ' . $setting_key);
831
832 // Initialize rate_limits if it doesn't exist
833 if (!isset($options['rate_limits'])) {
834 // //error_log('MXChat Save: Initializing rate_limits array');
835 $options['rate_limits'] = [];
836 }
837
838 // Initialize role settings if it doesn't exist
839 if (!isset($options['rate_limits'][$role_id])) {
840 //error_log('MXChat Save: Initializing rate_limits for role: ' . $role_id);
841 $options['rate_limits'][$role_id] = [
842 'limit' => ($role_id === 'logged_out') ? '10' : '100',
843 'timeframe' => 'daily',
844 'message' => 'Rate limit exceeded. Please try again later.'
845 ];
846 }
847
848 if ($setting_key === 'limit') {
849 if ($value === '__custom__') {
850 // Pull the integer from limit_custom that may have arrived (or will arrive).
851 $custom = isset($options['rate_limits'][$role_id]['limit_custom']) ? (string) $options['rate_limits'][$role_id]['limit_custom'] : '';
852 if ($custom !== '' && ctype_digit($custom) && (int) $custom >= 1) {
853 $options['rate_limits'][$role_id]['limit'] = $custom;
854 }
855 } else {
856 $options['rate_limits'][$role_id]['limit'] = $value;
857 }
858 } elseif ($setting_key === 'limit_custom') {
859 $clean = preg_replace('/[^0-9]/', '', (string) $value);
860 $options['rate_limits'][$role_id]['limit_custom'] = $clean;
861 // Mirror a valid custom value into limit UNCONDITIONALLY — same reasoning
862 // as the global branch above (plan-74eb86). The per-role custom input is
863 // only editable in custom mode and autosave is one-field-per-change, so
864 // this never clobbers a preset; it fixes the first-time-save revert.
865 if ($clean !== '' && (int) $clean >= 1) {
866 $options['rate_limits'][$role_id]['limit'] = $clean;
867 }
868 } else {
869 // Update the specific setting (timeframe, message)
870 $options['rate_limits'][$role_id][$setting_key] = $value;
871 }
872 //error_log('MXChat Save: Updated rate_limits[' . $role_id . '][' . $setting_key . '] = ' . $value);
873 } else {
874 //error_log('MXChat Save: Failed to parse rate_limits pattern: ' . $name);
875 }
876 }
877 // Then check for role rate limits (old format)
878 else if (strpos($name, 'mxchat_options[role_rate_limits]') !== false) {
879 //error_log('MXChat Save: Processing role_rate_limits field: ' . $name);
880 // Extract role ID from the name
881 preg_match('/\[role_rate_limits\]\[(.*?)\]/', $name, $matches);
882 //error_log('MXChat Save: Regex matches: ' . print_r($matches, true));
883
884 if (isset($matches[1])) {
885 $role_id = $matches[1];
886 // Initialize role_rate_limits if it doesn't exist
887 if (!isset($options['role_rate_limits'])) {
888 //error_log('MXChat Save: Initializing role_rate_limits array');
889 $options['role_rate_limits'] = [];
890 }
891 // Update the specific role's rate limit
892 $options['role_rate_limits'][$role_id] = sanitize_text_field($value);
893 //error_log('MXChat Save: Updated role_rate_limits[' . $role_id . '] = ' . $value);
894 } else {
895 //error_log('MXChat Save: Failed to parse role_rate_limits pattern: ' . $name);
896 }
897 }
898 // Handle toggles - check both extracted field_name and original name for toggle detection
899 else if (strpos($field_name, 'toggle') !== false || in_array($field_name, [
900 'chat_persistence_toggle',
901 'privacy_toggle',
902 'complianz_toggle',
903 'chat_toolbar_toggle',
904 'show_pdf_upload_button',
905 'show_word_upload_button',
906 'enable_streaming_toggle',
907 'contextual_awareness_toggle',
908 'citation_links_toggle',
909 'enable_email_block',
910 'enable_name_field',
911 'enable_consent_checkbox',
912 'consent_checkbox_required',
913 'custom_provider_for_embeddings',
914 'custom_provider_for_images',
915 'print_button_enabled',
916 'reset_chat_enabled'
917 ])) {
918 //error_log('MXChat Save: Processing toggle: ' . $field_name);
919 $options[$field_name] = ($value === 'on') ? 'on' : 'off';
920 } else {
921 //error_log('MXChat Save: Processing standard field: ' . $field_name);
922 // Store all other values directly using the extracted field name
923 $options[$field_name] = $value;
924 }
925 break;
926 }
927
928 // Save all updates to the options array
929 $updated = update_option('mxchat_options', $options);
930 //error_log('MXChat Save: Update result: ' . ($updated ? 'success' : 'unchanged') . ' for field: ' . $name);
931 //error_log('MXChat Save: Updated options array: ' . print_r($options, true));
932
933 // Log the save action if debug mode is enabled
934 if ( class_exists( 'MxChat_Admin' ) ) {
935 MxChat_Admin::mxchat_log_debug(
936 'settings_save',
937 sprintf( 'Field saved: %s', $field_name ),
938 array(
939 'field' => $field_name,
940 'updated' => $updated,
941 )
942 );
943 }
944
945 // Always return success even if WordPress says nothing changed
946 // (which happens when the value is the same as before)
947 wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
948 }
949
950 /**
951 * Save the selected bot for knowledge base operations
952 */
953 public function mxchat_save_selected_bot() {
954 // Check nonce
955 if (!wp_verify_nonce($_POST['nonce'] ?? '', 'mxchat_save_setting_nonce')) {
956 wp_send_json_error('Invalid nonce');
957 }
958
959 // Check permissions
960 if (!current_user_can('manage_options')) {
961 wp_send_json_error('Unauthorized');
962 }
963
964 $bot_id = isset($_POST['bot_id']) ? sanitize_key($_POST['bot_id']) : 'default';
965
966 // Save as user meta for the current user
967 $user_id = get_current_user_id();
968 update_user_meta($user_id, 'mxchat_selected_knowledge_bot', $bot_id);
969
970 // Also save as an option for site-wide default
971 update_option('mxchat_current_knowledge_bot', $bot_id);
972
973 // No cache clearing needed since we removed caching
974
975 wp_send_json_success(array(
976 'message' => 'Bot selection saved',
977 'bot_id' => $bot_id
978 ));
979 }
980
981 /**
982 * Handles AJAX request for saving chat settings
983 */
984 public function mxchat_save_prompts_setting_callback() {
985 check_ajax_referer('mxchat_prompts_setting_nonce');
986
987 if (!current_user_can('manage_options')) {
988 wp_send_json_error(['message' => esc_html__('Unauthorized', 'mxchat')]);
989 }
990
991 $name = isset($_POST['name']) ? $_POST['name'] : '';
992 $value = isset($_POST['value']) ? stripslashes($_POST['value']) : '';
993
994 //error_log('[MXCHAT-PROMPTS] Saving setting: ' . $name . ' = ' . $value);
995
996 if (empty($name)) {
997 wp_send_json_error(['message' => esc_html__('Invalid field name', 'mxchat')]);
998 }
999
1000 // Handle Pinecone settings - BYPASS WORDPRESS SANITIZATION
1001 if (strpos($name, 'mxchat_pinecone_addon_options') !== false) {
1002 //error_log('[MXCHAT-PROMPTS] Processing Pinecone setting: ' . $name);
1003
1004 // Extract the field name
1005 if (preg_match('/mxchat_pinecone_addon_options\[([^\]]+)\]/', $name, $matches)) {
1006 $field_name = $matches[1];
1007 //error_log('[MXCHAT-PROMPTS] Extracted field name: ' . $field_name);
1008
1009 // Get current options directly from database - NO WordPress filters
1010 global $wpdb;
1011 $current_options_raw = $wpdb->get_var(
1012 $wpdb->prepare(
1013 "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s",
1014 'mxchat_pinecone_addon_options'
1015 )
1016 );
1017
1018 // FIX: Handle the case where the option doesn't exist yet
1019 if ($current_options_raw === null) {
1020 // Option doesn't exist, create it with default values
1021 $current_options = array(
1022 'mxchat_use_pinecone' => '0',
1023 'mxchat_pinecone_api_key' => '',
1024 'mxchat_pinecone_host' => '',
1025 'mxchat_pinecone_index' => '',
1026 'mxchat_pinecone_environment' => ''
1027 );
1028 //error_log('[MXCHAT-PROMPTS] Option does not exist, creating with defaults');
1029 } else {
1030 // Unserialize the raw data
1031 $current_options = maybe_unserialize($current_options_raw);
1032 if (!is_array($current_options)) {
1033 // Fallback to defaults if unserialization fails
1034 $current_options = array(
1035 'mxchat_use_pinecone' => '0',
1036 'mxchat_pinecone_api_key' => '',
1037 'mxchat_pinecone_host' => '',
1038 'mxchat_pinecone_index' => '',
1039 'mxchat_pinecone_environment' => ''
1040 );
1041 //error_log('[MXCHAT-PROMPTS] Failed to unserialize, using defaults');
1042 }
1043 }
1044
1045 //error_log('[MXCHAT-PROMPTS] Current options from DB: ' . print_r($current_options, true));
1046
1047 // Update the specific field with proper sanitization
1048 switch ($field_name) {
1049 case 'mxchat_use_pinecone':
1050 $new_value = ($value === '1') ? '1' : '0';
1051 break;
1052 case 'mxchat_pinecone_api_key':
1053 case 'mxchat_pinecone_host':
1054 case 'mxchat_pinecone_index':
1055 case 'mxchat_pinecone_environment':
1056 $new_value = sanitize_text_field($value);
1057 if ($field_name === 'mxchat_pinecone_host') {
1058 $new_value = str_replace(['https://', 'http://'], '', $new_value);
1059 }
1060 break;
1061 case 'mxchat_pinecone_top_k':
1062 // d0cae1: out-of-range and junk normalize to the default 50 —
1063 // same clamp the read site applies.
1064 $top_k = absint($value);
1065 $new_value = (string) (($top_k >= 1 && $top_k <= 1000) ? $top_k : 50);
1066 break;
1067 default:
1068 wp_send_json_error(['message' => esc_html__('Unknown Pinecone field', 'mxchat')]);
1069 }
1070
1071 $current_options[$field_name] = $new_value;
1072 //error_log('[MXCHAT-PROMPTS] New value for ' . $field_name . ': "' . $new_value . '"');
1073 //error_log('[MXCHAT-PROMPTS] Updated options: ' . print_r($current_options, true));
1074
1075 // Save directly to database to bypass WordPress sanitization
1076 $serialized_options = maybe_serialize($current_options);
1077
1078 // FIX: Use INSERT ... ON DUPLICATE KEY UPDATE or separate INSERT/UPDATE logic
1079 $option_exists = $wpdb->get_var(
1080 $wpdb->prepare(
1081 "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name = %s",
1082 'mxchat_pinecone_addon_options'
1083 )
1084 );
1085
1086 if ($option_exists > 0) {
1087 // Update existing option
1088 $save_result = $wpdb->update(
1089 $wpdb->options,
1090 array('option_value' => $serialized_options),
1091 array('option_name' => 'mxchat_pinecone_addon_options'),
1092 array('%s'),
1093 array('%s')
1094 );
1095 //error_log('[MXCHAT-PROMPTS] Updated existing option, result: ' . ($save_result !== false ? 'SUCCESS' : 'FAILED'));
1096 } else {
1097 // Insert new option
1098 // Credential option — must NOT autoload (holds the Pinecone secret;
1099 // autoloaded rows are read into memory on every request).
1100 $save_result = $wpdb->insert(
1101 $wpdb->options,
1102 array(
1103 'option_name' => 'mxchat_pinecone_addon_options',
1104 'option_value' => $serialized_options,
1105 'autoload' => 'off'
1106 ),
1107 array('%s', '%s', '%s')
1108 );
1109 //error_log('[MXCHAT-PROMPTS] Inserted new option, result: ' . ($save_result !== false ? 'SUCCESS' : 'FAILED'));
1110 }
1111
1112 // Clear any WordPress option cache to ensure get_option() returns fresh data
1113 wp_cache_delete('mxchat_pinecone_addon_options', 'options');
1114
1115 // IMPROVED VERIFICATION - Check if the database operation succeeded
1116 if ($save_result !== false) {
1117 // Double-check by reading fresh from database
1118 $verification_raw = $wpdb->get_var(
1119 $wpdb->prepare(
1120 "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s",
1121 'mxchat_pinecone_addon_options'
1122 )
1123 );
1124 $verification_options = maybe_unserialize($verification_raw);
1125 $verified_value = isset($verification_options[$field_name]) ? $verification_options[$field_name] : 'NOT_FOUND';
1126
1127 //error_log('[MXCHAT-PROMPTS] Final verification - Expected: "' . $new_value . '", Got: "' . $verified_value . '"');
1128
1129 // Use loose comparison (==) instead of strict (===) to avoid type issues
1130 if ($verified_value == $new_value || $save_result > 0) {
1131 wp_send_json_success(['message' => esc_html__('Pinecone setting saved', 'mxchat')]);
1132 } else {
1133 // Still return success if the DB operation worked, even if verification is quirky
1134 //error_log('[MXCHAT-PROMPTS] Verification mismatch but DB operation succeeded');
1135 wp_send_json_success(['message' => esc_html__('Pinecone setting saved (DB success)', 'mxchat')]);
1136 }
1137 } else {
1138 wp_send_json_error(['message' => esc_html__('Database save failed', 'mxchat')]);
1139 }
1140 } else {
1141 wp_send_json_error(['message' => esc_html__('Invalid field name format', 'mxchat')]);
1142 }
1143
1144 return; // Exit here for Pinecone settings
1145 }
1146 // Handle auto-sync settings (existing functionality)
1147 if (strpos($name, 'mxchat_auto_sync_') === 0) {
1148 $value = ($value === 'on' || $value === '1') ? '1' : '0';
1149 $updated = update_option($name, $value);
1150
1151 if ($updated || get_option($name) === $value) {
1152 wp_send_json_success(['message' => esc_html__('Auto-sync setting saved', 'mxchat')]);
1153 } else {
1154 wp_send_json_error(['message' => esc_html__('No changes detected', 'mxchat')]);
1155 }
1156 }
1157
1158 // Handle chunking settings - use direct DB access to bypass WordPress filters
1159 if (strpos($name, 'mxchat_chunk') === 0 || $name === 'mxchat_chunking_enabled') {
1160 global $wpdb;
1161
1162 // Get current options directly from database
1163 $current_options_raw = $wpdb->get_var(
1164 $wpdb->prepare(
1165 "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s",
1166 'mxchat_options'
1167 )
1168 );
1169
1170 $options = $current_options_raw !== null ? maybe_unserialize($current_options_raw) : array();
1171 if (!is_array($options)) {
1172 $options = array();
1173 }
1174
1175 // Update the specific chunking field
1176 if ($name === 'mxchat_chunking_enabled') {
1177 $options['chunking_enabled'] = in_array($value, array('on', '1', 'true', true), true);
1178 } elseif ($name === 'mxchat_chunk_size') {
1179 $options['chunk_size'] = max(1000, min(10000, intval($value)));
1180 }
1181
1182 // Save directly to database
1183 $serialized_options = maybe_serialize($options);
1184
1185 $option_exists = $wpdb->get_var(
1186 $wpdb->prepare(
1187 "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name = %s",
1188 'mxchat_options'
1189 )
1190 );
1191
1192 if ($option_exists > 0) {
1193 $save_result = $wpdb->update(
1194 $wpdb->options,
1195 array('option_value' => $serialized_options),
1196 array('option_name' => 'mxchat_options'),
1197 array('%s'),
1198 array('%s')
1199 );
1200 } else {
1201 $save_result = $wpdb->insert(
1202 $wpdb->options,
1203 array(
1204 'option_name' => 'mxchat_options',
1205 'option_value' => $serialized_options,
1206 'autoload' => 'yes'
1207 ),
1208 array('%s', '%s', '%s')
1209 );
1210 }
1211
1212 // Clear object cache for this option
1213 wp_cache_delete('mxchat_options', 'options');
1214
1215 if ($save_result !== false) {
1216 wp_send_json_success(['message' => esc_html__('Chunking setting saved', 'mxchat')]);
1217 } else {
1218 wp_send_json_error(['message' => esc_html__('Failed to save chunking setting', 'mxchat')]);
1219 }
1220 return;
1221 }
1222
1223 // Handle ACF field exclusion toggles
1224 if (strpos($name, 'mxchat_acf_field_') === 0) {
1225 // The identifier after the prefix is the ACF field KEY (unique per
1226 // field), not the field name — names are shared across groups and
1227 // collide (plan 30e81f). Reject anything that isn't key-shaped so a
1228 // stale pre-3.2.20 page (or its exit beacon) posting a bare name
1229 // can't write junk into the key-based list.
1230 $field_key = str_replace('mxchat_acf_field_', '', $name);
1231 if (!preg_match('/^field_[A-Za-z0-9_\-]+$/', $field_key)) {
1232 wp_send_json_error(['message' => esc_html__('Invalid ACF field identifier', 'mxchat')]);
1233 return;
1234 }
1235 $is_enabled = ($value === 'on' || $value === '1');
1236
1237 // Get current excluded fields
1238 $excluded_fields = get_option('mxchat_acf_excluded_fields', array());
1239 if (!is_array($excluded_fields)) {
1240 $excluded_fields = array();
1241 }
1242
1243 if ($is_enabled) {
1244 // Remove from exclusion list (field should be included)
1245 $excluded_fields = array_values(array_diff($excluded_fields, array($field_key)));
1246 // Lazy legacy-name conversion: if this field's NAME is still
1247 // stored (its group was inactive when the 30e81f migration
1248 // ran), including this one field must not silently include
1249 // its same-named twins — swap the name entry for the keys of
1250 // every OTHER field currently wearing that name.
1251 $excluded_fields = $this->mxchat_expand_legacy_acf_name_entry($excluded_fields, $field_key);
1252 } else {
1253 // Add to exclusion list (field should be excluded)
1254 if (!in_array($field_key, $excluded_fields, true)) {
1255 $excluded_fields[] = $field_key;
1256 }
1257 }
1258
1259 $updated = update_option('mxchat_acf_excluded_fields', $excluded_fields);
1260
1261 if ($updated || true) { // Always report success since the state may already be correct
1262 wp_send_json_success([
1263 'message' => $is_enabled
1264 ? esc_html__('Field will be included in imports', 'mxchat')
1265 : esc_html__('Field will be excluded from imports', 'mxchat')
1266 ]);
1267 } else {
1268 wp_send_json_error(['message' => esc_html__('Failed to save ACF field setting', 'mxchat')]);
1269 }
1270 return;
1271 }
1272
1273 // Handle custom post meta whitelist
1274 if ($name === 'mxchat_custom_meta_whitelist') {
1275 $updated = update_option('mxchat_custom_meta_whitelist', sanitize_textarea_field($value));
1276
1277 if ($updated || true) { // Always report success since the state may already be correct
1278 wp_send_json_success([
1279 'message' => esc_html__('Custom meta whitelist saved', 'mxchat')
1280 ]);
1281 } else {
1282 wp_send_json_error(['message' => esc_html__('Failed to save custom meta whitelist', 'mxchat')]);
1283 }
1284 return;
1285 }
1286
1287 // Handle other prompts options (autoload false — can hold the Pinecone secret)
1288 $options = get_option('mxchat_prompts_options', []);
1289 $options[$name] = $value;
1290 $updated = update_option('mxchat_prompts_options', $options, false);
1291
1292 if ($updated) {
1293 wp_send_json_success(['message' => esc_html__('Setting saved', 'mxchat')]);
1294 } else {
1295 wp_send_json_error(['message' => esc_html__('No changes detected', 'mxchat')]);
1296 }
1297 }
1298
1299 /**
1300 * If the field behind $included_key still has its NAME stored in the
1301 * exclusion list (a legacy entry the 30e81f migration could not resolve
1302 * because the group was inactive), replace that name with the keys of
1303 * every OTHER current field wearing it. Including one field must never
1304 * silently include its same-named twins — that would be the original
1305 * collision bug in reverse, in the unsafe (privacy-losing) direction.
1306 */
1307 private function mxchat_expand_legacy_acf_name_entry($excluded_fields, $included_key) {
1308 if (!function_exists('acf_get_field')) {
1309 return $excluded_fields;
1310 }
1311 $field = acf_get_field($included_key);
1312 if (!$field || empty($field['name'])) {
1313 return $excluded_fields;
1314 }
1315 $field_name = $field['name'];
1316 if (!in_array($field_name, $excluded_fields, true)) {
1317 return $excluded_fields;
1318 }
1319 $excluded_fields = array_values(array_diff($excluded_fields, array($field_name)));
1320 foreach ($this->mxchat_acf_keys_for_name($field_name) as $twin_key) {
1321 if ($twin_key !== $included_key && !in_array($twin_key, $excluded_fields, true)) {
1322 $excluded_fields[] = $twin_key;
1323 }
1324 }
1325 return $excluded_fields;
1326 }
1327
1328 /**
1329 * Keys of every currently-registered top-level ACF field with this name.
1330 */
1331 private function mxchat_acf_keys_for_name($field_name) {
1332 $keys = array();
1333 if (!function_exists('acf_get_field_groups') || !function_exists('acf_get_fields')) {
1334 return $keys;
1335 }
1336 foreach (acf_get_field_groups() as $group) {
1337 $group_fields = acf_get_fields($group['key']);
1338 if (empty($group_fields)) {
1339 continue;
1340 }
1341 foreach ($group_fields as $field) {
1342 if (isset($field['name'], $field['key']) && $field['name'] === $field_name) {
1343 $keys[] = $field['key'];
1344 }
1345 }
1346 }
1347 return $keys;
1348 }
1349
1350 /**
1351 * Group-level ACF toggle (plan bf57e0): sets every field in one ACF field
1352 * group included or excluded in a SINGLE option write. The client must
1353 * never loop the per-field endpoint for this — get_option → modify →
1354 * update_option once per field from twenty concurrent requests is a
1355 * lost-update race that silently drops most of the group.
1356 */
1357 public function mxchat_acf_toggle_group_callback() {
1358 check_ajax_referer('mxchat_prompts_setting_nonce');
1359
1360 if (!current_user_can('manage_options')) {
1361 wp_send_json_error(['message' => esc_html__('Insufficient permissions', 'mxchat')], 403);
1362 return;
1363 }
1364
1365 if (!function_exists('acf_get_fields')) {
1366 wp_send_json_error(['message' => esc_html__('ACF is not active', 'mxchat')]);
1367 return;
1368 }
1369
1370 $group_key = isset($_POST['group_key']) ? sanitize_text_field(wp_unslash($_POST['group_key'])) : '';
1371 if (!preg_match('/^group_[A-Za-z0-9_\-]+$/', $group_key)) {
1372 wp_send_json_error(['message' => esc_html__('Invalid ACF group identifier', 'mxchat')]);
1373 return;
1374 }
1375 $state = isset($_POST['state']) ? sanitize_text_field(wp_unslash($_POST['state'])) : '';
1376 $include = ($state === 'on' || $state === '1');
1377
1378 // Resolve the group's fields SERVER-side — a client-supplied key list
1379 // is not trusted. This is the same call the settings UI lists from,
1380 // so the toggle covers exactly the rendered set (top-level fields).
1381 $group_fields = acf_get_fields($group_key);
1382 if (empty($group_fields)) {
1383 wp_send_json_error(['message' => esc_html__('No fields found for this group', 'mxchat')]);
1384 return;
1385 }
1386
1387 $excluded_fields = get_option('mxchat_acf_excluded_fields', array());
1388 if (!is_array($excluded_fields)) {
1389 $excluded_fields = array();
1390 }
1391
1392 $touched = array();
1393 foreach ($group_fields as $field) {
1394 if (empty($field['key'])) {
1395 continue;
1396 }
1397 if ($include) {
1398 $excluded_fields = array_values(array_diff($excluded_fields, array($field['key'])));
1399 $excluded_fields = $this->mxchat_expand_legacy_acf_name_entry($excluded_fields, $field['key']);
1400 } elseif (!in_array($field['key'], $excluded_fields, true)) {
1401 $excluded_fields[] = $field['key'];
1402 }
1403 $touched[] = array(
1404 'name' => 'mxchat_acf_field_' . $field['key'],
1405 'value' => $include ? 'on' : 'off',
1406 );
1407 }
1408
1409 // The one write — the whole point of this endpoint.
1410 update_option('mxchat_acf_excluded_fields', array_values($excluded_fields));
1411
1412 wp_send_json_success([
1413 'message' => $include
1414 ? esc_html__('All fields in this group will be included in imports', 'mxchat')
1415 : esc_html__('All fields in this group will be excluded from imports', 'mxchat'),
1416 'fields' => $touched,
1417 ]);
1418 }
1419
1420 /**
1421 * Handles AJAX request for Pinecone settings migration
1422 */
1423 public function ajax_migrate_pinecone_settings() {
1424 // Verify nonce
1425 if (!wp_verify_nonce($_POST['_ajax_nonce'] ?? '', 'mxchat_save_setting_nonce')) {
1426 wp_send_json_error('Invalid nonce');
1427 }
1428
1429 // Check permissions
1430 if (!current_user_can('manage_options')) {
1431 wp_send_json_error('Unauthorized access');
1432 }
1433
1434 // Check if old Pinecone addon options exist
1435 $old_options = get_option('mxchat_pinecone_addon_options', array());
1436
1437 if (empty($old_options)) {
1438 wp_send_json_success(array('migrated' => false, 'message' => 'No old settings found'));
1439 }
1440
1441 // Get current core plugin options
1442 $current_options = get_option('mxchat_pinecone_addon_options', array());
1443
1444 // Only migrate if core options are empty or if explicitly requested
1445 $should_migrate = empty($current_options) ||
1446 (empty($current_options['mxchat_pinecone_api_key']) && !empty($old_options['mxchat_pinecone_api_key']));
1447
1448 if ($should_migrate) {
1449 // Migrate settings with proper sanitization
1450 $migrated_options = array(
1451 'mxchat_use_pinecone' => $old_options['mxchat_use_pinecone'] ?? '0',
1452 'mxchat_pinecone_api_key' => sanitize_text_field($old_options['mxchat_pinecone_api_key'] ?? ''),
1453 'mxchat_pinecone_host' => sanitize_text_field($old_options['mxchat_pinecone_host'] ?? ''),
1454 'mxchat_pinecone_index' => sanitize_text_field($old_options['mxchat_pinecone_index'] ?? ''),
1455 'mxchat_pinecone_environment' => sanitize_text_field($old_options['mxchat_pinecone_environment'] ?? '')
1456 );
1457
1458 update_option('mxchat_pinecone_addon_options', $migrated_options, false);
1459
1460 wp_send_json_success(array(
1461 'migrated' => true,
1462 'message' => 'Settings migrated successfully from Pinecone add-on'
1463 ));
1464 } else {
1465 wp_send_json_success(array(
1466 'migrated' => false,
1467 'message' => 'Settings already exist in core plugin'
1468 ));
1469 }
1470 }
1471
1472
1473 // ========================================
1474 // LICENSE AJAX HANDLERS
1475 // ========================================
1476
1477 /**
1478 * Validates and activates chat license via AJAX
1479 */
1480 public function mxchat_handle_activate_license() {
1481 // Check nonce
1482 if (!check_ajax_referer('mxchat_activate_license_nonce', 'security', false)) {
1483 wp_send_json_error(esc_html__('Invalid security token', 'mxchat'));
1484 return;
1485 }
1486
1487 // Verify user capabilities
1488 if (!current_user_can('manage_options')) {
1489 wp_send_json_error(esc_html__('Unauthorized access', 'mxchat'));
1490 return;
1491 }
1492
1493 $license_key = isset($_POST['mxchat_activation_key']) ? sanitize_text_field($_POST['mxchat_activation_key']) : '';
1494 $customer_email = isset($_POST['mxchat_pro_email']) ? sanitize_email($_POST['mxchat_pro_email']) : '';
1495
1496 if (empty($license_key) || empty($customer_email)) {
1497 wp_send_json_error(esc_html__('Email or License Key is missing', 'mxchat'));
1498 return;
1499 }
1500
1501 $product_id = 'MxChatPRO';
1502 $domain = parse_url(home_url(), PHP_URL_HOST); // Get the current domain
1503
1504 // Call WooCommerce Software API for activation (not just validation)
1505 $response = wp_remote_get(
1506 add_query_arg(
1507 array(
1508 'wc-api' => 'software-api',
1509 'request' => 'activation',
1510 'email' => $customer_email,
1511 'license_key' => $license_key,
1512 'product_id' => $product_id,
1513 'instance' => $domain, // THIS IS KEY - include the domain as instance
1514 'platform' => 'wordpress' // Optional but good to include
1515 ),
1516 'https://mxchat.ai/'
1517 ),
1518 array(
1519 'timeout' => 60,
1520 'sslverify' => true
1521 )
1522 );
1523
1524 if (is_wp_error($response)) {
1525 $error_message = $response->get_error_message();
1526 //error_log('MxChat License Activation Error: ' . $error_message);
1527 wp_send_json_error(esc_html__('Activation failed due to a server error: ', 'mxchat') . $error_message);
1528 return;
1529 }
1530
1531 $response_code = wp_remote_retrieve_response_code($response);
1532 $body = wp_remote_retrieve_body($response);
1533
1534 // Log response for debugging
1535 //error_log('MxChat License Response Code: ' . $response_code);
1536 //error_log('MxChat License Response Body: ' . $body);
1537
1538 if ($response_code !== 200) {
1539 wp_send_json_error(esc_html__('Server returned error code: ', 'mxchat') . $response_code);
1540 return;
1541 }
1542
1543 $data = json_decode($body);
1544
1545 if ($data && isset($data->activated) && $data->activated) {
1546 // Success - save local options
1547 update_option('mxchat_license_status', 'active');
1548 update_option('mxchat_pro_email', $customer_email);
1549 update_option('mxchat_activation_key', $license_key);
1550 delete_option('mxchat_license_error');
1551
1552 // Also track on your website (this is your existing domain tracking)
1553 $this->track_domain_on_website($license_key, $customer_email, $domain);
1554
1555 wp_send_json_success(array('message' => esc_html__('License activated successfully', 'mxchat')));
1556 } else {
1557 $error_message = isset($data->error) ? $data->error : esc_html__('Activation failed', 'mxchat');
1558 update_option('mxchat_license_status', 'inactive');
1559 update_option('mxchat_license_error', $error_message);
1560
1561 //error_log('MxChat Activation failed: ' . $error_message);
1562 wp_send_json_error($error_message);
1563 }
1564 }
1565
1566 /**
1567 * Track domain on your website (separate from WooCommerce activation)
1568 */
1569 private function track_domain_on_website($license_key, $email, $domain) {
1570 // This calls your website's tracking API
1571 wp_remote_post('https://mxchat.ai/mxchat-api/activate-license', array(
1572 'body' => array(
1573 'mxchat_pro_email' => $email,
1574 'mxchat_activation_key' => $license_key,
1575 'domain' => $domain
1576 ),
1577 'timeout' => 10,
1578 'sslverify' => true
1579 ));
1580 }
1581
1582 /**
1583 * Validates license via AJAX with email and key
1584 */
1585 public function mxchat_check_license_status() {
1586 // Verify nonce
1587 if (!check_ajax_referer('mxchat_activate_license_nonce', 'security', false)) {
1588 wp_send_json_error('Security check failed');
1589 return;
1590 }
1591
1592 // Add isset checks for safety
1593 $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
1594 $key = isset($_POST['key']) ? sanitize_text_field($_POST['key']) : '';
1595
1596 // Check if this license is actually active in your system
1597 $is_active = (get_option('mxchat_license_status') === 'active' &&
1598 get_option('mxchat_pro_email') === $email &&
1599 get_option('mxchat_activation_key') === $key);
1600
1601 wp_send_json(array(
1602 'is_active' => $is_active
1603 ));
1604 }
1605
1606 /**
1607 * Handle license deactivation - Complete version for plugin
1608 */
1609 function mxchat_deactivate_license() {
1610 // Add debugging
1611 //error_log('MxChat deactivate function called');
1612
1613 // Check nonce
1614 if (!check_ajax_referer('mxchat_activate_license_nonce', 'security', false)) {
1615 //error_log('MxChat deactivate: Nonce check failed');
1616 wp_send_json_error('Security check failed.');
1617 return;
1618 }
1619
1620 // plan-mxchat-20260731-c63fb6 — nonce is not authorization. Without this,
1621 // any authenticated user holding the nonce could revoke the site's PRO
1622 // licence. Every sibling handler in this file already checks.
1623 if (!current_user_can('manage_options')) {
1624 wp_send_json_error(esc_html__('Unauthorized', 'mxchat'), 403);
1625 return;
1626 }
1627
1628 //error_log('MxChat deactivate: Nonce check passed');
1629
1630 $license_key = get_option('mxchat_activation_key');
1631 $email = get_option('mxchat_pro_email');
1632 $domain = parse_url(home_url(), PHP_URL_HOST);
1633
1634 //error_log('MxChat deactivate: License: ' . $license_key . ', Email: ' . $email . ', Domain: ' . $domain);
1635
1636 if (empty($license_key) || empty($email)) {
1637 //error_log('MxChat deactivate: No active license found');
1638 wp_send_json_error('No active license found.');
1639 return;
1640 }
1641
1642 // Clear local license data first
1643 delete_option('mxchat_license_status');
1644 delete_option('mxchat_pro_email');
1645 delete_option('mxchat_activation_key');
1646 delete_option('mxchat_license_error');
1647
1648 //error_log('MxChat deactivate: Local data cleared');
1649
1650 // Notify your website's API to properly deactivate
1651 $response = wp_remote_post('https://mxchat.ai/mxchat-api/deactivate-license', array(
1652 'body' => array(
1653 'license_key' => $license_key,
1654 'email' => $email,
1655 'domain' => $domain
1656 ),
1657 'timeout' => 15,
1658 'sslverify' => true
1659 ));
1660
1661 if (is_wp_error($response)) {
1662 //error_log('MxChat deactivate: Server error - ' . $response->get_error_message());
1663 wp_send_json_success(array(
1664 'message' => 'License deactivated locally. Server could not be contacted to free activation slot.',
1665 'server_notified' => false
1666 ));
1667 return;
1668 }
1669
1670 $response_body = wp_remote_retrieve_body($response);
1671 $response_data = json_decode($response_body, true);
1672
1673 //error_log('MxChat deactivate: Server response - ' . $response_body);
1674
1675 if (isset($response_data['success']) && $response_data['success']) {
1676 //error_log('MxChat deactivate: Success with server notification');
1677 wp_send_json_success(array(
1678 'message' => 'License deactivated successfully. Activation slot has been freed up.',
1679 'server_notified' => true
1680 ));
1681 } else {
1682 //error_log('MxChat deactivate: Server responded but deactivation may have failed');
1683 wp_send_json_success(array(
1684 'message' => 'License deactivated locally. Please check your account dashboard to verify the activation was freed.',
1685 'server_notified' => false
1686 ));
1687 }
1688 }
1689
1690
1691 // ========================================
1692 // ACTIONS & INTENTS AJAX HANDLERS
1693 // ========================================
1694
1695 /**
1696 * Validates nonce and returns JSON error on failure
1697 */
1698 public function mxchat_toggle_action() {
1699 // Check nonce
1700 if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mxchat_actions_nonce')) {
1701 wp_send_json_error(array('message' => 'Security check failed'));
1702 return;
1703 }
1704
1705 // Check permissions
1706 if (!current_user_can('manage_options')) {
1707 wp_send_json_error(array('message' => 'Permission denied'));
1708 return;
1709 }
1710
1711 // Validate params
1712 $intent_id = isset($_POST['intent_id']) ? intval($_POST['intent_id']) : 0;
1713 $enabled = isset($_POST['enabled']) ? (bool)$_POST['enabled'] : false;
1714
1715 if (!$intent_id) {
1716 wp_send_json_error(array('message' => 'Invalid action ID'));
1717 return;
1718 }
1719
1720 // Update the intent/action status in the database
1721 global $wpdb;
1722 $table_name = $wpdb->prefix . 'mxchat_intents';
1723
1724 // Using the 'enabled' field - add this field if it doesn't exist
1725 $result = $wpdb->update(
1726 $table_name,
1727 array('enabled' => $enabled ? 1 : 0),
1728 array('id' => $intent_id),
1729 array('%d'),
1730 array('%d')
1731 );
1732
1733 if ($result === false) {
1734 wp_send_json_error(array('message' => 'Database error'));
1735 return;
1736 }
1737
1738 wp_send_json_success();
1739 }
1740
1741
1742 /**
1743 * Validates permissions for AJAX request handling
1744 */
1745 public function mxchat_update_intent_threshold() {
1746 // Check permissions
1747 if (!current_user_can('manage_options')) {
1748 if (wp_doing_ajax()) {
1749 wp_send_json_error(array('message' => 'Unauthorized user'));
1750 return;
1751 }
1752 wp_die(esc_html__('Unauthorized user', 'mxchat'));
1753 }
1754
1755 // Verify nonce
1756 check_admin_referer('mxchat_update_intent_threshold_nonce');
1757
1758 // Process the update if we have valid data
1759 if (isset($_POST['intent_id'], $_POST['intent_threshold'])) {
1760 global $wpdb;
1761 $table_name = $wpdb->prefix . 'mxchat_intents';
1762 $intent_id = intval($_POST['intent_id']);
1763 $threshold_percentage = max(70, min(95, intval($_POST['intent_threshold'])));
1764 $similarity_threshold = $threshold_percentage / 100;
1765
1766 $result = $wpdb->update(
1767 $table_name,
1768 ['similarity_threshold' => $similarity_threshold],
1769 ['id' => $intent_id],
1770 ['%f'],
1771 ['%d']
1772 );
1773
1774 // Handle AJAX requests
1775 if (wp_doing_ajax()) {
1776 if ($result === false) {
1777 wp_send_json_error(array('message' => 'Failed to update threshold'));
1778 } else {
1779 wp_send_json_success(array('threshold' => $threshold_percentage));
1780 }
1781 return;
1782 }
1783 }
1784
1785 // Redirect for regular form submissions
1786 wp_safe_redirect(admin_url('admin.php?page=mxchat-actions&updated=true'));
1787 exit;
1788 }
1789
1790 // ========================================
1791 // HELPER METHODS
1792 // ========================================
1793
1794 /**
1795 * Returns a specific nonce action string
1796 */
1797 private function mxchat_get_nonce_action() {
1798 return 'mxchat_license_nonce';
1799 }
1800
1801 /**
1802 * Check API key status for all providers
1803 */
1804 public function mxchat_check_api_keys() {
1805 // Check nonce
1806 if (!wp_verify_nonce($_POST['nonce'] ?? '', 'mxchat_save_setting_nonce')) {
1807 wp_send_json_error('Invalid nonce');
1808 }
1809
1810 // Check permissions
1811 if (!current_user_can('manage_options')) {
1812 wp_send_json_error('Unauthorized');
1813 }
1814
1815 // Get current options
1816 $options = get_option('mxchat_options', array());
1817
1818 // Check which API keys are present
1819 $api_key_status = array(
1820 'openai' => !empty($options['api_key']),
1821 'claude' => !empty($options['claude_api_key']),
1822 'xai' => !empty($options['xai_api_key']),
1823 'deepseek' => !empty($options['deepseek_api_key']),
1824 'gemini' => !empty($options['gemini_api_key']),
1825 'openrouter' => !empty($options['openrouter_api_key']),
1826 'voyage' => !empty($options['voyage_api_key'])
1827 );
1828
1829 wp_send_json_success($api_key_status);
1830 }
1831
1832 // ========================================
1833 // DEBUG & OPTIMIZATION AJAX HANDLERS
1834 // ========================================
1835
1836 /**
1837 * Toggle debug mode on/off
1838 */
1839 public function mxchat_toggle_debug_mode_callback() {
1840 // Verify nonce
1841 if ( ! check_ajax_referer( 'mxchat_save_setting_nonce', '_ajax_nonce', false ) ) {
1842 wp_send_json_error( array( 'message' => esc_html__( 'Security check failed', 'mxchat' ) ) );
1843 }
1844
1845 // Check permissions
1846 if ( ! current_user_can( 'manage_options' ) ) {
1847 wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'mxchat' ) ) );
1848 }
1849
1850 $enabled = isset( $_POST['enabled'] ) && $_POST['enabled'] === 'on';
1851
1852 $options = get_option( 'mxchat_options', array() );
1853
1854 if ( $enabled ) {
1855 $options['debug_mode'] = 'on';
1856 update_option( 'mxchat_options', $options );
1857 MxChat_Admin::mxchat_log_debug( 'debug_mode', 'Debug mode enabled' );
1858 } else {
1859 // Log before disabling
1860 MxChat_Admin::mxchat_log_debug( 'debug_mode', 'Debug mode disabled' );
1861 $options['debug_mode'] = 'off';
1862 update_option( 'mxchat_options', $options );
1863 }
1864
1865 wp_send_json_success( array(
1866 'message' => $enabled ? esc_html__( 'Debug mode enabled', 'mxchat' ) : esc_html__( 'Debug mode disabled', 'mxchat' ),
1867 'enabled' => $enabled,
1868 ) );
1869 }
1870
1871 /**
1872 * Get the debug log entries
1873 */
1874 public function mxchat_get_debug_log_callback() {
1875 // Verify nonce
1876 if ( ! check_ajax_referer( 'mxchat_save_setting_nonce', '_ajax_nonce', false ) ) {
1877 wp_send_json_error( array( 'message' => esc_html__( 'Security check failed', 'mxchat' ) ) );
1878 }
1879
1880 // Check permissions
1881 if ( ! current_user_can( 'manage_options' ) ) {
1882 wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'mxchat' ) ) );
1883 }
1884
1885 $log = MxChat_Admin::mxchat_get_debug_log();
1886
1887 wp_send_json_success( array(
1888 'log' => $log,
1889 'count' => count( $log ),
1890 ) );
1891 }
1892
1893 /**
1894 * Clear the debug log
1895 */
1896 public function mxchat_clear_debug_log_callback() {
1897 // Verify nonce
1898 if ( ! check_ajax_referer( 'mxchat_save_setting_nonce', '_ajax_nonce', false ) ) {
1899 wp_send_json_error( array( 'message' => esc_html__( 'Security check failed', 'mxchat' ) ) );
1900 }
1901
1902 // Check permissions
1903 if ( ! current_user_can( 'manage_options' ) ) {
1904 wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'mxchat' ) ) );
1905 }
1906
1907 MxChat_Admin::mxchat_clear_debug_log();
1908
1909 // Log that the log was cleared (this will be the first entry in the new log)
1910 MxChat_Admin::mxchat_log_debug( 'debug_log', 'Debug log cleared by user' );
1911
1912 wp_send_json_success( array( 'message' => esc_html__( 'Debug log cleared', 'mxchat' ) ) );
1913 }
1914
1915 /**
1916 * Export settings as JSON
1917 */
1918 public function mxchat_export_settings_callback() {
1919 // Verify nonce
1920 if ( ! check_ajax_referer( 'mxchat_save_setting_nonce', '_ajax_nonce', false ) ) {
1921 wp_send_json_error( array( 'message' => esc_html__( 'Security check failed', 'mxchat' ) ) );
1922 }
1923
1924 // Check permissions
1925 if ( ! current_user_can( 'manage_options' ) ) {
1926 wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'mxchat' ) ) );
1927 }
1928
1929 $export = MxChat_Admin::mxchat_export_settings();
1930
1931 // Log the export
1932 MxChat_Admin::mxchat_log_debug( 'settings_export', 'Settings exported by user' );
1933
1934 wp_send_json_success( array(
1935 'settings' => $export,
1936 'filename' => 'mxchat-settings-' . gmdate( 'Y-m-d-His' ) . '.json',
1937 ) );
1938 }
1939
1940 /**
1941 * Reset all settings to defaults
1942 */
1943 public function mxchat_reset_all_settings_callback() {
1944 // Verify nonce
1945 if ( ! check_ajax_referer( 'mxchat_save_setting_nonce', '_ajax_nonce', false ) ) {
1946 wp_send_json_error( array( 'message' => esc_html__( 'Security check failed', 'mxchat' ) ) );
1947 }
1948
1949 // Check permissions
1950 if ( ! current_user_can( 'manage_options' ) ) {
1951 wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'mxchat' ) ) );
1952 }
1953
1954 // Require confirmation code
1955 $confirmation = isset( $_POST['confirmation'] ) ? sanitize_text_field( wp_unslash( $_POST['confirmation'] ) ) : '';
1956
1957 if ( strtoupper( $confirmation ) !== 'RESET' ) {
1958 wp_send_json_error( array( 'message' => esc_html__( 'Invalid confirmation code. Please type RESET to confirm.', 'mxchat' ) ) );
1959 }
1960
1961 // Perform the reset
1962 MxChat_Admin::mxchat_reset_all_settings();
1963
1964 wp_send_json_success( array( 'message' => esc_html__( 'All settings have been reset to defaults. The page will reload.', 'mxchat' ) ) );
1965 }
1966
1967 /**
1968 * Reset the global rate-limit usage counter to zero on demand.
1969 *
1970 * Zeroes the WP option mxchat_chat_limit_<bot>_global that the integrator
1971 * increments per message, then returns a freshly-formatted readout string
1972 * so the settings page can update without a reload. Does NOT change any
1973 * enforcement config — purely clears the running counter.
1974 */
1975 public function mxchat_reset_global_rate_limit_callback() {
1976 // Verify nonce
1977 if ( ! check_ajax_referer( 'mxchat_reset_global_usage', '_ajax_nonce', false ) ) {
1978 wp_send_json_error( array( 'message' => esc_html__( 'Security check failed', 'mxchat' ) ) );
1979 }
1980
1981 // Check permissions
1982 if ( ! current_user_can( 'manage_options' ) ) {
1983 wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'mxchat' ) ) );
1984 }
1985
1986 // Resolve the per-bot counter key the same way the integrator does.
1987 $bot_id = isset( $_POST['bot_id'] ) ? sanitize_key( wp_unslash( $_POST['bot_id'] ) ) : 'default';
1988 $safe_bot = preg_replace( '/[^a-zA-Z0-9_]/', '_', $bot_id );
1989 if ( $safe_bot === '' ) {
1990 $safe_bot = 'default';
1991 }
1992 $option_key = 'mxchat_chat_limit_' . $safe_bot . '_global';
1993
1994 $now = time();
1995 update_option( $option_key, array( 'count' => 0, 'timestamp' => $now ) );
1996
1997 // Recompute the display string so the front-end can update in place.
1998 $all_options = get_option( 'mxchat_options', array() );
1999 $global_cfg = isset( $all_options['rate_limits_global'] ) && is_array( $all_options['rate_limits_global'] )
2000 ? $all_options['rate_limits_global']
2001 : array();
2002 $limit_raw = isset( $global_cfg['limit'] ) ? (string) $global_cfg['limit'] : 'unlimited';
2003 // Defensive: if a raw __custom__ ever slips through, fall back to the custom value.
2004 if ( ! ctype_digit( $limit_raw ) && isset( $global_cfg['limit_custom'] ) && ctype_digit( (string) $global_cfg['limit_custom'] ) ) {
2005 $limit_raw = (string) $global_cfg['limit_custom'];
2006 }
2007 $timeframe = isset( $global_cfg['timeframe'] ) ? (string) $global_cfg['timeframe'] : 'daily';
2008 $windows = array( 'hourly' => 3600, 'daily' => 86400, 'weekly' => 604800, 'monthly' => 2592000 );
2009 $window = isset( $windows[ $timeframe ] ) ? $windows[ $timeframe ] : 86400;
2010 $reset_at = $now + $window;
2011 $limit_int = ctype_digit( $limit_raw ) ? (int) $limit_raw : 0;
2012
2013 $text = sprintf(
2014 /* translators: 1: used count, 2: limit, 3: remaining, 4: human-readable time until reset */
2015 esc_html__( '%1$s of %2$s used · %3$s left · resets in %4$s', 'mxchat' ),
2016 number_format_i18n( 0 ),
2017 number_format_i18n( $limit_int ),
2018 number_format_i18n( $limit_int ),
2019 human_time_diff( $now, $reset_at )
2020 );
2021
2022 wp_send_json_success( array(
2023 'count' => 0,
2024 'limit' => $limit_int,
2025 'left' => $limit_int,
2026 'reset_at' => $reset_at,
2027 'pct' => 0,
2028 'text' => $text,
2029 'message' => esc_html__( 'Usage counter reset.', 'mxchat' ),
2030 ) );
2031 }
2032
2033 }
2034
2035 // Initialize the AJAX handler
2036 new MxChat_Ajax_Handler();
2037