PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 3.0.9
MxChat – AI Chatbot & Content Generation for WordPress v3.0.9
3.2.21 3.2.20 3.2.19 3.2.18 3.2.17 3.2.16 3.2.15 3.2.14 3.2.12 3.2.13 3.2.11 3.2.10 3.2.9 3.2.8 3.2.7 3.2.6 3.2.5 3.2.4 3.2.3 3.2.2 3.2.1 2.0.3 2.0.4 2.0.5 2.0.6 All 152 releases
← All changes | mxchat-basic.php +1185 -58 2.0.53.0.9 View file →
@@ -1,9 +1,10 @@
1 1 <?php
2 2 /**
3 3 * Plugin Name: MxChat
4 + * Plugin URI: https://mxchat.ai/
4 5 * Description: AI chatbot for WordPress with OpenAI, Claude, xAI, DeepSeek, live agent, PDF uploads, WooCommerce, and training on website data.
5 - * Version: 2.0.5
6 + * Version: 3.0.9
6 7 * Author: MxChat
7 8 * Author URI: https://mxchat.ai
8 9 * License: GPLv2 or later
9 10 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
@@ -14,31 +15,250 @@
14 15 if (!defined('ABSPATH')) {
15 16 exit; // Exit if accessed directly.
16 17 }
17 18
19 +// Define plugin version constant for asset versioning
20 +// Reads version from plugin header automatically
21 +if (!defined('MXCHAT_VERSION')) {
22 + $plugin_data = get_file_data(__FILE__, array('Version' => 'Version'), 'plugin');
23 + define('MXCHAT_VERSION', $plugin_data['Version']);
24 +}
18 25
19 26 function mxchat_load_textdomain() {
20 - load_plugin_textdomain('mxchat', false, dirname(plugin_basename(__FILE__)) . '/languages');
27 + $domain = 'mxchat';
28 + $locale = determine_locale();
29 +
30 + // First, try to load from /wp-content/languages/plugins/ (preserved during updates)
31 + $mo_file = WP_LANG_DIR . '/plugins/' . $domain . '-' . $locale . '.mo';
32 + if (file_exists($mo_file)) {
33 + load_textdomain($domain, $mo_file);
34 + return;
35 + }
36 +
37 + // Fallback to plugin's /languages directory
38 + load_plugin_textdomain($domain, false, dirname(plugin_basename(__FILE__)) . '/languages');
21 39 }
22 -add_action('plugins_loaded', 'mxchat_load_textdomain');
40 +add_action('init', 'mxchat_load_textdomain');
23 41
24 -// Include classes
25 -require_once plugin_dir_path(__FILE__) . 'includes/class-mxchat-integrator.php';
26 -require_once plugin_dir_path(__FILE__) . 'includes/class-mxchat-admin.php';
27 -require_once plugin_dir_path(__FILE__) . 'includes/class-mxchat-public.php';
28 -require_once plugin_dir_path(__FILE__) . 'includes/class-mxchat-utils.php';
29 -require_once plugin_dir_path(__FILE__) . 'includes/class-mxchat-user.php';
30 -require_once plugin_dir_path(__FILE__) . 'includes/class-mxchat-woocommerce.php';
31 -require_once plugin_dir_path(__FILE__) . 'includes/pdf-parser/alt_autoload.php';
32 -require_once plugin_dir_path(__FILE__) . 'includes/class-mxchat-word-handler.php';
42 +/**
43 + * Exclude MxChat assets from caching plugin optimizations
44 + *
45 + * This prevents issues with WP Rocket, LiteSpeed Cache, Autoptimize, WP Super Cache,
46 + * W3 Total Cache, SG Optimizer, and similar plugins that may break the chatbot by
47 + * removing "unused" CSS, minifying/combining JS, or deferring/delaying jQuery.
48 + *
49 + * Both chat-script.js and floating-script.js depend on jQuery, so jQuery must also
50 + * be excluded from any optimization that changes load order or timing.
51 + */
33 52
34 -function mxchat_activate() {
53 +// ── WP Rocket ────────────────────────────────────────────────────────────────
54 +
55 +// Exclude from Remove Unused CSS (RUCSS)
56 +add_filter('rocket_rucss_inline_atts_exclusions', function($exclusions) {
57 + if (!is_array($exclusions)) $exclusions = array();
58 + $exclusions[] = 'mxchat';
59 + return $exclusions;
60 +});
61 +
62 +// Exclude CSS from minification/combination
63 +add_filter('rocket_exclude_css', function($excluded) {
64 + if (!is_array($excluded)) $excluded = array();
65 + $excluded[] = '/plugins/mxchat-basic/css/chat-style.css';
66 + return $excluded;
67 +});
68 +
69 +// Exclude JS from minification/combination
70 +add_filter('rocket_exclude_js', function($excluded) {
71 + if (!is_array($excluded)) $excluded = array();
72 + $excluded[] = '/plugins/mxchat-basic/js/chat-script.js';
73 + $excluded[] = '/plugins/mxchat-basic/js/floating-script.js';
74 + $excluded[] = '/jquery-core';
75 + $excluded[] = '/jquery.min.js';
76 + $excluded[] = '/jquery.js';
77 + $excluded[] = '/jquery-migrate';
78 + return $excluded;
79 +});
80 +
81 +// Exclude JS from defer
82 +add_filter('rocket_exclude_defer_js', function($excluded) {
83 + if (!is_array($excluded)) $excluded = array();
84 + $excluded[] = '/plugins/mxchat-basic/js/chat-script.js';
85 + $excluded[] = '/plugins/mxchat-basic/js/floating-script.js';
86 + $excluded[] = '/jquery-core';
87 + $excluded[] = '/jquery.min.js';
88 + $excluded[] = '/jquery.js';
89 + $excluded[] = '/jquery-migrate';
90 + return $excluded;
91 +});
92 +
93 +// Exclude from delay JS execution
94 +add_filter('rocket_delay_js_exclusions', function($excluded) {
95 + if (!is_array($excluded)) $excluded = array();
96 + $excluded[] = 'mxchat';
97 + $excluded[] = 'chat-script';
98 + $excluded[] = 'floating-script';
99 + $excluded[] = '/jquery-core';
100 + $excluded[] = '/jquery.min.js';
101 + $excluded[] = '/jquery.js';
102 + $excluded[] = '/jquery-migrate';
103 + return $excluded;
104 +});
105 +
106 +// ── LiteSpeed Cache ──────────────────────────────────────────────────────────
107 +
108 +// Exclude CSS from optimization
109 +add_filter('litespeed_optimize_css_excludes', function($excluded) {
110 + if (!is_array($excluded)) $excluded = array();
111 + $excluded[] = 'chat-style.css';
112 + return $excluded;
113 +});
114 +
115 +// Exclude JS from defer
116 +add_filter('litespeed_optm_js_defer_exc', function($excluded) {
117 + if (!is_array($excluded)) $excluded = array();
118 + $excluded[] = 'chat-script.js';
119 + $excluded[] = 'floating-script.js';
120 + $excluded[] = 'jquery.min.js';
121 + $excluded[] = 'jquery.js';
122 + return $excluded;
123 +});
124 +
125 +// Exclude JS from combining
126 +add_filter('litespeed_optm_js_exc', function($excluded) {
127 + if (!is_array($excluded)) $excluded = array();
128 + $excluded[] = 'chat-script.js';
129 + $excluded[] = 'floating-script.js';
130 + $excluded[] = 'jquery.min.js';
131 + $excluded[] = 'jquery.js';
132 + return $excluded;
133 +});
134 +
135 +// ── Autoptimize ──────────────────────────────────────────────────────────────
136 +
137 +// Exclude CSS from optimization (comma-separated strings)
138 +add_filter('autoptimize_filter_css_exclude', function($excluded) {
139 + if (!is_string($excluded)) $excluded = '';
140 + return $excluded . ', mxchat, chat-style.css';
141 +});
142 +
143 +// Exclude JS from optimization (comma-separated strings)
144 +add_filter('autoptimize_filter_js_exclude', function($excluded) {
145 + if (!is_string($excluded)) $excluded = '';
146 + return $excluded . ', mxchat, chat-script.js, floating-script.js, jquery.min.js, jquery.js';
147 +});
148 +
149 +// ── SG Optimizer (SiteGround) ────────────────────────────────────────────────
150 +
151 +add_filter('sgo_js_minify_exclude', function($excluded) {
152 + if (!is_array($excluded)) $excluded = array();
153 + $excluded[] = 'chat-script.js';
154 + $excluded[] = 'floating-script.js';
155 + $excluded[] = 'jquery.min.js';
156 + return $excluded;
157 +});
158 +
159 +add_filter('sgo_javascript_combine_exclude', function($excluded) {
160 + if (!is_array($excluded)) $excluded = array();
161 + $excluded[] = 'chat-script.js';
162 + $excluded[] = 'floating-script.js';
163 + $excluded[] = 'jquery.min.js';
164 + return $excluded;
165 +});
166 +
167 +add_filter('sgo_js_async_exclude', function($excluded) {
168 + if (!is_array($excluded)) $excluded = array();
169 + $excluded[] = 'chat-script.js';
170 + $excluded[] = 'floating-script.js';
171 + $excluded[] = 'jquery.min.js';
172 + return $excluded;
173 +});
174 +
175 +// ── W3 Total Cache ───────────────────────────────────────────────────────────
176 +
177 +add_filter('w3tc_minify_js_do_tag_minification', function($do_minify, $script_tag, $file) {
178 + if (strpos($file, 'chat-script.js') !== false ||
179 + strpos($file, 'floating-script.js') !== false ||
180 + strpos($file, 'jquery.min.js') !== false ||
181 + strpos($file, 'jquery.js') !== false) {
182 + return false;
183 + }
184 + return $do_minify;
185 +}, 10, 3);
186 +
187 +// ── WP Super Cache ──────────────────────────────────────────────────────────
188 +
189 +add_filter('wpsc_rejected_uri', function($rejected) {
190 + if (!is_array($rejected)) $rejected = array();
191 + $rejected[] = 'wp-admin/admin-ajax.php';
192 + return $rejected;
193 +});
194 +
195 +// Include classes with error handling
196 +function mxchat_include_classes() {
197 + $class_files = array(
198 + 'includes/class-mxchat-integrator.php',
199 + 'includes/class-mxchat-admin.php',
200 + 'includes/class-mxchat-public.php',
201 + 'includes/class-mxchat-utils.php',
202 + 'includes/class-mxchat-user.php',
203 + 'includes/class-mxchat-meta-box.php',
204 + 'includes/class-mxchat-chunker.php',
205 + 'includes/pdf-parser/alt_autoload.php',
206 + 'includes/class-mxchat-word-handler.php',
207 + 'includes/class-mxchat-content-generator.php',
208 + 'admin/class-ajax-handler.php',
209 + 'admin/class-pinecone-manager.php',
210 + 'admin/class-knowledge-manager.php'
211 + );
212 +
213 + foreach ($class_files as $file) {
214 + $file_path = plugin_dir_path(__FILE__) . $file;
215 + if (file_exists($file_path)) {
216 + require_once $file_path;
217 + } else {
218 + //error_log('MxChat: Missing class file - ' . $file);
219 + }
220 + }
221 +}
222 +
223 +/**
224 + * Create URL click tracking table
225 + */
226 +function mxchat_create_url_clicks_table() {
35 227 global $wpdb;
228 +
229 + $table_name = $wpdb->prefix . 'mxchat_url_clicks';
230 +
36 231 $charset_collate = $wpdb->get_charset_collate();
232 +
233 + $sql = "CREATE TABLE $table_name (
234 + id mediumint(9) NOT NULL AUTO_INCREMENT,
235 + session_id varchar(100) NOT NULL,
236 + clicked_url text NOT NULL,
237 + message_context text,
238 + click_timestamp datetime DEFAULT CURRENT_TIMESTAMP,
239 + user_ip varchar(45),
240 + user_agent text,
241 + PRIMARY KEY (id),
242 + KEY session_id (session_id),
243 + KEY click_timestamp (click_timestamp)
244 + ) $charset_collate;";
245 +
246 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
247 + dbDelta($sql);
248 +}
37 249
38 - // Chat Transcripts Table
39 - $chat_transcripts_table = $wpdb->prefix . 'mxchat_chat_transcripts';
40 - $sql_chat_transcripts = "CREATE TABLE $chat_transcripts_table (
250 +/**
251 + * FIXED: Robust table creation and column management
252 + */
253 +function mxchat_create_chat_transcripts_table() {
254 + global $wpdb;
255 +
256 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
257 + $charset_collate = $wpdb->get_charset_collate();
258 +
259 + // Create table with ALL columns including user_name from the start
260 + $sql = "CREATE TABLE $table_name (
41 261 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
42 262 user_id MEDIUMINT(9) DEFAULT 0,
43 263 session_id VARCHAR(255) NOT NULL,
44 264 role VARCHAR(255) NOT NULL,
@@ -43,25 +263,485 @@
43 263 session_id VARCHAR(255) NOT NULL,
44 264 role VARCHAR(255) NOT NULL,
45 265 message TEXT NOT NULL,
46 266 user_email VARCHAR(255) DEFAULT NULL,
267 + user_name VARCHAR(100) DEFAULT NULL,
268 + user_identifier VARCHAR(255) DEFAULT NULL,
269 + originating_page_url TEXT DEFAULT NULL,
270 + originating_page_title VARCHAR(500) DEFAULT NULL,
47 271 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
48 - PRIMARY KEY (id)
272 + PRIMARY KEY (id),
273 + KEY session_id (session_id),
274 + KEY user_email (user_email),
275 + KEY timestamp (timestamp)
49 276 ) $charset_collate;";
277 +
278 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
279 + $result = dbDelta($sql);
280 +
281 + // Log the result for debugging
282 + if (empty($result)) {
283 + //error_log("MxChat: dbDelta returned empty result for chat transcripts table");
284 + } else {
285 + //error_log("MxChat: dbDelta result: " . print_r($result, true));
286 + }
287 +
288 + // IMPORTANT: Ensure all columns exist for existing installations
289 + mxchat_ensure_all_columns($table_name);
290 +}
50 291
51 - // System Prompt Content Table
292 +/**
293 + * Ensure all required columns exist (for upgrades)
294 + */
295 +function mxchat_ensure_all_columns($table_name) {
296 + global $wpdb;
297 +
298 + // First check if table exists
299 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
300 + if (!$table_exists) {
301 + //error_log("MxChat: Table $table_name does not exist, cannot add columns");
302 + return;
303 + }
304 +
305 + // Define all required columns and their types
306 + $required_columns = [
307 + 'user_identifier' => 'VARCHAR(255) DEFAULT NULL',
308 + 'user_email' => 'VARCHAR(255) DEFAULT NULL',
309 + 'user_name' => 'VARCHAR(100) DEFAULT NULL',
310 + 'originating_page_url' => 'TEXT DEFAULT NULL',
311 + 'originating_page_title' => 'VARCHAR(500) DEFAULT NULL',
312 + 'rag_context' => 'LONGTEXT DEFAULT NULL'
313 + ];
314 +
315 + // Get existing columns
316 + $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name");
317 + if (empty($existing_columns)) {
318 + //error_log("MxChat: Could not get columns for table $table_name");
319 + return;
320 + }
321 +
322 + $existing_column_names = array_column($existing_columns, 'Field');
323 +
324 + // Add missing columns
325 + foreach ($required_columns as $column_name => $column_definition) {
326 + if (!in_array($column_name, $existing_column_names)) {
327 + $alter_sql = "ALTER TABLE $table_name ADD COLUMN $column_name $column_definition";
328 + $result = $wpdb->query($alter_sql);
329 +
330 + if ($result === false) {
331 + //error_log("MxChat: Failed to add column $column_name to $table_name. Error: " . $wpdb->last_error);
332 + } else {
333 + //error_log("MxChat: Successfully added column $column_name to $table_name");
334 + }
335 + }
336 + }
337 +}
338 +
339 +/**
340 + * Add role restriction column to knowledge base table
341 + */
342 +function mxchat_add_role_restriction_column() {
343 + global $wpdb;
344 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
345 +
346 + // Check if table exists first
347 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
348 + if (!$table_exists) {
349 + //error_log("MxChat: System prompt content table does not exist, cannot add role_restriction column");
350 + return;
351 + }
352 +
353 + // Check if column already exists
354 + $column_exists = $wpdb->get_results(
355 + $wpdb->prepare(
356 + "SHOW COLUMNS FROM {$table_name} LIKE %s",
357 + 'role_restriction'
358 + )
359 + );
360 +
361 + if (empty($column_exists)) {
362 + $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url";
363 + $result = $wpdb->query($alter_sql);
364 +
365 + if ($result === false) {
366 + //error_log("MxChat: Failed to add role_restriction column. Error: " . $wpdb->last_error);
367 + } else {
368 + //error_log("MxChat: Successfully added role_restriction column");
369 +
370 + // Set all existing records to 'public' (everyone can access)
371 + $update_result = $wpdb->query(
372 + "UPDATE {$table_name}
373 + SET role_restriction = 'public'
374 + WHERE role_restriction IS NULL OR role_restriction = ''"
375 + );
376 +
377 + if ($update_result !== false) {
378 + //error_log("MxChat: Updated {$update_result} existing records to public access");
379 + }
380 + }
381 + }
382 +}
383 +
384 +/**
385 + * Add enabled_bots column to intents table for multi-bot action filtering
386 + */
387 +function mxchat_add_enabled_bots_column() {
388 + global $wpdb;
389 + $table_name = $wpdb->prefix . 'mxchat_intents';
390 +
391 + // Check if table exists first
392 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
393 + if (!$table_exists) {
394 + //error_log("MxChat: Intents table does not exist, cannot add enabled_bots column");
395 + return;
396 + }
397 +
398 + // Check if column already exists
399 + $column_exists = $wpdb->get_results(
400 + $wpdb->prepare(
401 + "SHOW COLUMNS FROM {$table_name} LIKE %s",
402 + 'enabled_bots'
403 + )
404 + );
405 +
406 + if (empty($column_exists)) {
407 + $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled";
408 + $result = $wpdb->query($alter_sql);
409 +
410 + if ($result === false) {
411 + //error_log("MxChat: Failed to add enabled_bots column. Error: " . $wpdb->last_error);
412 + } else {
413 + //error_log("MxChat: Successfully added enabled_bots column");
414 +
415 + // Set all existing actions to work with 'default' bot for backward compatibility
416 + $default_bots = json_encode(['default']);
417 + $update_result = $wpdb->query(
418 + $wpdb->prepare(
419 + "UPDATE {$table_name}
420 + SET enabled_bots = %s
421 + WHERE enabled_bots IS NULL OR enabled_bots = ''",
422 + $default_bots
423 + )
424 + );
425 +
426 + if ($update_result !== false) {
427 + //error_log("MxChat: Updated {$update_result} existing actions to work with default bot");
428 + }
429 + }
430 + }
431 +}
432 +
433 +/**
434 + * Create Pinecone role restrictions table with multi-bot support
435 + */
436 +function mxchat_create_pinecone_roles_table() {
437 + global $wpdb;
438 +
439 + $table_name = $wpdb->prefix . 'mxchat_pinecone_roles';
440 + $charset_collate = $wpdb->get_charset_collate();
441 +
442 + $sql = "CREATE TABLE $table_name (
443 + id mediumint(9) NOT NULL AUTO_INCREMENT,
444 + vector_id varchar(255) NOT NULL,
445 + bot_id varchar(50) NOT NULL DEFAULT 'default',
446 + source_url text,
447 + role_restriction varchar(50) DEFAULT 'public',
448 + updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
449 + PRIMARY KEY (id),
450 + UNIQUE KEY vector_bot (vector_id, bot_id),
451 + KEY role_restriction (role_restriction),
452 + KEY bot_id (bot_id)
453 + ) $charset_collate;";
454 +
455 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
456 + dbDelta($sql);
457 +}
458 +
459 +/**
460 + * Add bot_id column to mxchat_pinecone_roles table for multi-bot support
461 + * This migration runs once to update existing installations
462 + */
463 +function mxchat_migrate_pinecone_roles_add_bot_id() {
464 + global $wpdb;
465 +
466 + // Check if migration already ran
467 + $migration_version = get_option('mxchat_pinecone_roles_migration_version', '0');
468 + if (version_compare($migration_version, '2.5.2', '>=')) {
469 + return; // Already migrated
470 + }
471 +
472 + $table_name = $wpdb->prefix . 'mxchat_pinecone_roles';
473 +
474 + // Check if table exists
475 + if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
476 + return; // Table doesn't exist yet
477 + }
478 +
479 + // Check if bot_id column already exists
480 + $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'bot_id'");
481 +
482 + if (empty($column_exists)) {
483 + // Add bot_id column
484 + $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN bot_id VARCHAR(50) NOT NULL DEFAULT 'default' AFTER vector_id");
485 +
486 + // Update the unique key to include bot_id
487 + $wpdb->query("ALTER TABLE {$table_name} DROP INDEX vector_id");
488 + $wpdb->query("ALTER TABLE {$table_name} ADD UNIQUE KEY vector_bot (vector_id, bot_id)");
489 +
490 + // Add index for bot_id
491 + $wpdb->query("ALTER TABLE {$table_name} ADD KEY bot_id (bot_id)");
492 +
493 + error_log('MxChat: Successfully added bot_id column to mxchat_pinecone_roles table');
494 + }
495 +
496 + // Mark migration as complete
497 + update_option('mxchat_pinecone_roles_migration_version', '2.5.2');
498 +}
499 +
500 +/**
501 + * 2.5.6: Add content_type column to mxchat_system_prompt_content table
502 + * Enables filtering knowledge base by content type (posts, pages, PDFs, etc.)
503 + */
504 +function mxchat_migrate_add_content_type_column() {
505 + global $wpdb;
506 +
507 + // Check if migration already ran
508 + $migration_version = get_option('mxchat_content_type_migration_version', '0');
509 + if (version_compare($migration_version, '2.5.6', '>=')) {
510 + return;
511 + }
512 +
513 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
514 +
515 + // Check if table exists
516 + if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
517 + return;
518 + }
519 +
520 + // Check if content_type column already exists
521 + $column_exists = $wpdb->get_results("SHOW COLUMNS FROM {$table_name} LIKE 'content_type'");
522 +
523 + if (empty($column_exists)) {
524 + // Add content_type column with default value 'content' for backwards compatibility
525 + $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN content_type VARCHAR(50) DEFAULT 'content' AFTER role_restriction");
526 +
527 + // Add index for better query performance
528 + $wpdb->query("ALTER TABLE {$table_name} ADD KEY content_type (content_type)");
529 +
530 + error_log('MxChat: Successfully added content_type column to mxchat_system_prompt_content table');
531 + }
532 +
533 + // Mark migration as complete
534 + update_option('mxchat_content_type_migration_version', '2.5.6');
535 +}
536 +
537 +/**
538 + * 2.5.2: Create queue processing tables for reliable background processing
539 + */
540 +function mxchat_create_queue_tables() {
541 + global $wpdb;
542 + $charset_collate = $wpdb->get_charset_collate();
543 +
544 + // Main queue table
545 + $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
546 + $sql_queue = "CREATE TABLE $queue_table (
547 + id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
548 + queue_id varchar(64) NOT NULL,
549 + item_type varchar(20) NOT NULL,
550 + item_data longtext NOT NULL,
551 + status varchar(20) NOT NULL DEFAULT 'pending',
552 + bot_id varchar(50) NOT NULL DEFAULT 'default',
553 + priority int(11) NOT NULL DEFAULT 0,
554 + attempts int(11) NOT NULL DEFAULT 0,
555 + max_attempts int(11) NOT NULL DEFAULT 3,
556 + error_message text DEFAULT NULL,
557 + created_at datetime NOT NULL,
558 + started_at datetime DEFAULT NULL,
559 + completed_at datetime DEFAULT NULL,
560 + PRIMARY KEY (id),
561 + KEY queue_id (queue_id),
562 + KEY status (status),
563 + KEY item_type (item_type),
564 + KEY priority (priority)
565 + ) $charset_collate;";
566 +
567 + // Queue metadata table
568 + $meta_table = $wpdb->prefix . 'mxchat_queue_meta';
569 + $sql_meta = "CREATE TABLE $meta_table (
570 + id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
571 + queue_id varchar(64) NOT NULL,
572 + meta_key varchar(255) NOT NULL,
573 + meta_value longtext,
574 + PRIMARY KEY (id),
575 + KEY queue_id (queue_id),
576 + KEY meta_key (meta_key)
577 + ) $charset_collate;";
578 +
579 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
580 + dbDelta($sql_queue);
581 + dbDelta($sql_meta);
582 +
583 + //error_log("MxChat: Queue tables created/updated successfully");
584 +}
585 +
586 +/**
587 + * Create transcript translations table for persisting translations
588 + */
589 +function mxchat_create_translations_table() {
590 + global $wpdb;
591 + $charset_collate = $wpdb->get_charset_collate();
592 +
593 + $table_name = $wpdb->prefix . 'mxchat_transcript_translations';
594 + $sql = "CREATE TABLE $table_name (
595 + id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
596 + session_id varchar(255) NOT NULL,
597 + language_code varchar(10) NOT NULL,
598 + translations longtext NOT NULL,
599 + created_at datetime NOT NULL,
600 + updated_at datetime NOT NULL,
601 + PRIMARY KEY (id),
602 + UNIQUE KEY session_lang (session_id, language_code),
603 + KEY session_id (session_id)
604 + ) $charset_collate;";
605 +
606 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
607 + dbDelta($sql);
608 +}
609 +
610 +/**
611 + * 2.5.2: Fix URL column size to support long URLs (especially with UTF-8 encoding)
612 + * This fixes "url, source_url. The supplied values may be too long" errors
613 + */
614 +function mxchat_fix_url_column_size() {
615 + global $wpdb;
616 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
617 +
618 + // Check if table exists
619 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
620 + if (!$table_exists) {
621 + return;
622 + }
623 +
624 + // Change url and source_url from VARCHAR to TEXT to handle long URLs
625 + // This is especially important for URLs with UTF-8 encoded characters (Hebrew, Arabic, etc.)
626 + $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN url TEXT");
627 + $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN source_url TEXT");
628 +
629 + //error_log("MxChat: Successfully updated url and source_url columns to TEXT type for long URL support");
630 +}
631 +
632 +/**
633 + * Migrate deprecated AI models to their replacements
634 + * Version 2.5.1: Migrate Claude 3.5 Sonnet (deprecated) to Claude 3.7 Sonnet
635 + * Version 3.0.55: Migrate GPT-4 series models (deprecated 2026-02-17) to GPT-5 series
636 + */
637 +function mxchat_migrate_deprecated_models() {
638 + $options = get_option('mxchat_options', array());
639 + $migrated = false;
640 + $migration_message = '';
641 +
642 + if (!isset($options['model'])) {
643 + return;
644 + }
645 +
646 + $current_model = $options['model'];
647 +
648 + // Migrate deprecated Claude models to Claude Opus 4.6 (recommended replacement per Anthropic)
649 + $deprecated_claude_models = array(
650 + 'claude-3-5-sonnet-20240620', // Retired Oct 28, 2025
651 + 'claude-3-5-sonnet-20241022', // Retired Oct 28, 2025
652 + 'claude-3-7-sonnet-20250219', // Retiring Feb 19, 2026
653 + 'claude-3-opus-20240229', // Retired Jan 5, 2026
654 + 'claude-3-sonnet-20240229', // Legacy
655 + 'claude-3-haiku-20240307', // Legacy
656 + );
657 + if (in_array($current_model, $deprecated_claude_models, true)) {
658 + $options['model'] = 'claude-opus-4-6';
659 + $migrated = true;
660 + $migration_message = sprintf(
661 + __('Your chatbot model has been automatically updated from %s to Claude Opus 4.6 due to Anthropic deprecating older Claude models.', 'mxchat'),
662 + $current_model
663 + );
664 + }
665 +
666 + // Migrate deprecated Claude Haiku 3.5 to Claude Haiku 4.5
667 + if ($current_model === 'claude-3-5-haiku-20241022') {
668 + $options['model'] = 'claude-haiku-4-5-20251001';
669 + $migrated = true;
670 + $migration_message = __('Your chatbot model has been automatically updated from Claude Haiku 3.5 to Claude Haiku 4.5 due to Anthropic deprecating the older model.', 'mxchat');
671 + }
672 +
673 + // Migrate deprecated GPT-4 series and GPT-3.5 Turbo to GPT-5.1 Chat Latest
674 + if (in_array($current_model, array('gpt-4o', 'gpt-4.1-2025-04-14', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'), true)) {
675 + $options['model'] = 'gpt-5.1-chat-latest';
676 + $migrated = true;
677 + $migration_message = sprintf(
678 + __('Your chatbot model has been automatically updated from %s to GPT-5.1 Chat Latest due to OpenAI deprecating older models.', 'mxchat'),
679 + $current_model
680 + );
681 + }
682 +
683 + // Migrate deprecated GPT-4o Mini and GPT-4.1 Mini to GPT-5 Mini
684 + if (in_array($current_model, array('gpt-4o-mini', 'gpt-4.1-mini'), true)) {
685 + $options['model'] = 'gpt-5-mini';
686 + $migrated = true;
687 + $migration_message = sprintf(
688 + __('Your chatbot model has been automatically updated from %s to GPT-5 Mini due to OpenAI deprecating GPT-4 series models.', 'mxchat'),
689 + $current_model
690 + );
691 + }
692 +
693 + if ($migrated) {
694 + update_option('mxchat_options', $options);
695 + update_option('mxchat_model_migrated_notice', true);
696 + update_option('mxchat_model_migration_message', $migration_message);
697 + }
698 +}
699 +
700 +/**
701 + * Show admin notice after model migration
702 + */
703 +function mxchat_show_migration_notice() {
704 + if (get_option('mxchat_model_migrated_notice')) {
705 + $migration_message = get_option('mxchat_model_migration_message', __('Your chatbot model has been automatically updated due to a model deprecation.', 'mxchat'));
706 + ?>
707 + <div class="notice notice-info is-dismissible">
708 + <p>
709 + <strong><?php esc_html_e('MxChat Model Updated', 'mxchat'); ?></strong><br>
710 + <?php echo esc_html($migration_message); ?>
711 + </p>
712 + </div>
713 + <?php
714 + delete_option('mxchat_model_migrated_notice');
715 + delete_option('mxchat_model_migration_message');
716 + }
717 +}
718 +
719 +function mxchat_activate() {
720 + global $wpdb;
721 + $charset_collate = $wpdb->get_charset_collate();
722 +
723 + //error_log("MxChat: Running activation function");
724 +
725 + // Create chat transcripts table with improved function
726 + mxchat_create_chat_transcripts_table();
727 +
728 + // System Prompt Content Table - UPDATED: Use TEXT for url and source_url columns
52 729 $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
53 730 $sql_system_prompt = "CREATE TABLE $system_prompt_table (
54 731 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
55 - url VARCHAR(255) NOT NULL,
732 + url TEXT NOT NULL,
56 733 article_content LONGTEXT NOT NULL,
57 734 embedding_vector LONGTEXT,
58 - source_url VARCHAR(255) DEFAULT NULL,
735 + source_url TEXT DEFAULT NULL,
736 + role_restriction VARCHAR(50) DEFAULT 'public',
737 + content_type VARCHAR(50) DEFAULT 'content',
59 738 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
60 - PRIMARY KEY (id)
739 + PRIMARY KEY (id),
740 + KEY content_type (content_type)
61 741 ) $charset_collate;";
62 742
63 - // Intents Table
743 + // Intents Table - NOW INCLUDES enabled_bots column from the start
64 744 $intents_table = $wpdb->prefix . 'mxchat_intents';
65 745 $sql_intents_table = "CREATE TABLE $intents_table (
66 746 id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
67 747 intent_label VARCHAR(255) NOT NULL,
@@ -68,51 +748,335 @@
68 748 phrases TEXT NOT NULL,
69 749 embedding_vector LONGTEXT NOT NULL,
70 750 callback_function VARCHAR(255) NOT NULL,
71 751 similarity_threshold FLOAT DEFAULT 0.85,
752 + enabled TINYINT(1) NOT NULL DEFAULT 1,
753 + enabled_bots LONGTEXT DEFAULT NULL,
72 754 PRIMARY KEY (id)
73 755 ) $charset_collate;";
74 756
75 757 require_once ABSPATH . 'wp-admin/includes/upgrade.php';
76 758
77 - // Create or update tables
78 - dbDelta($sql_chat_transcripts);
759 + // Create other tables
79 760 dbDelta($sql_system_prompt);
80 761 dbDelta($sql_intents_table);
81 762
82 - // Ensure additional columns in `mxchat_chat_transcripts`
83 - mxchat_add_missing_columns($chat_transcripts_table, 'user_identifier', 'VARCHAR(255)');
84 - mxchat_add_missing_columns($chat_transcripts_table, 'user_email', 'VARCHAR(255) DEFAULT NULL');
763 + // Create URL click tracking table
764 + mxchat_create_url_clicks_table();
765 +
766 + // Create Pinecone roles table
767 + mxchat_create_pinecone_roles_table();
768 +
769 + // NEW 2.5.2: Create queue processing tables
770 + mxchat_create_queue_tables();
85 771
86 - // Ensure additional columns in `mxchat_system_prompt_content`
87 - mxchat_add_missing_columns($system_prompt_table, 'embedding_vector', 'LONGTEXT');
88 - mxchat_add_missing_columns($system_prompt_table, 'source_url', 'VARCHAR(255) DEFAULT NULL');
772 + // Create transcript translations table
773 + mxchat_create_translations_table();
89 774
775 + // Ensure additional columns in system prompt table
776 + $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
777 + if (!empty($existing_system_columns)) {
778 + $existing_system_column_names = array_column($existing_system_columns, 'Field');
779 +
780 + if (!in_array('embedding_vector', $existing_system_column_names)) {
781 + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN embedding_vector LONGTEXT");
782 + }
783 + if (!in_array('source_url', $existing_system_column_names)) {
784 + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN source_url TEXT DEFAULT NULL");
785 + }
786 + if (!in_array('role_restriction', $existing_system_column_names)) {
787 + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url");
788 + }
789 + }
790 +
90 791 // Set default thresholds for existing intents
91 792 $wpdb->query("UPDATE {$intents_table} SET similarity_threshold = 0.85 WHERE similarity_threshold IS NULL");
793 +
794 + // Ensure enabled column exists in intents table
795 + $existing_intent_columns = $wpdb->get_results("SHOW COLUMNS FROM $intents_table");
796 + if (!empty($existing_intent_columns)) {
797 + $existing_intent_column_names = array_column($existing_intent_columns, 'Field');
798 +
799 + if (!in_array('enabled', $existing_intent_column_names)) {
800 + $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
801 + }
802 +
803 + // Ensure enabled_bots column exists for existing installations
804 + if (!in_array('enabled_bots', $existing_intent_column_names)) {
805 + $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled");
806 +
807 + // Set existing actions to work with default bot
808 + $default_bots = json_encode(['default']);
809 + $wpdb->query($wpdb->prepare(
810 + "UPDATE {$intents_table} SET enabled_bots = %s WHERE enabled_bots IS NULL",
811 + $default_bots
812 + ));
813 + }
814 + }
92 815
93 - // Update plugin version in the database
94 - update_option('mxchat_plugin_version', '2.0.5');
816 + // Run migration for existing installations
817 + mxchat_migrate_pinecone_roles_add_bot_id();
818 +
819 + // Setup cron jobs
820 + mxchat_setup_cron_jobs();
821 +
822 + // Update version
823 + update_option('mxchat_plugin_version', MXCHAT_VERSION);
824 +
825 + //error_log("MxChat: Activation function completed");
95 826 }
96 827
828 +/**
829 + * Setup cron jobs on plugin activation
830 + */
831 +function mxchat_setup_cron_jobs() {
832 + // Clear any existing cron jobs first
833 + wp_clear_scheduled_hook('mxchat_reset_rate_limits');
834 +
835 + // Check if WordPress cron is disabled
836 + if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
837 + // Set flag to use fallback system
838 + update_option('mxchat_use_fallback_rate_limits', true);
839 + update_option('mxchat_next_rate_limit_check', time() + 3600);
840 + return;
841 + }
842 +
843 + // Schedule the rate limit reset cron job
844 + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
845 +
846 + if ($result === false) {
847 + // Fallback if scheduling fails
848 + update_option('mxchat_use_fallback_rate_limits', true);
849 + update_option('mxchat_next_rate_limit_check', time() + 3600);
850 + } else {
851 + // Clear fallback flags if cron scheduling succeeded
852 + delete_option('mxchat_use_fallback_rate_limits');
853 + }
854 +
855 + // Schedule transcript cleanup if configured
856 + $transcript_options = get_option('mxchat_transcripts_options', array());
857 + $cleanup_interval = isset($transcript_options['mxchat_auto_delete_transcripts']) ? $transcript_options['mxchat_auto_delete_transcripts'] : 'never';
858 +
859 + if ($cleanup_interval !== 'never') {
860 + // Check if not already scheduled
861 + if (!wp_next_scheduled('mxchat_cleanup_old_transcripts')) {
862 + // Schedule to run daily at 3 AM
863 + $next_run = strtotime('tomorrow 3:00 AM');
864 + wp_schedule_event($next_run, 'daily', 'mxchat_cleanup_old_transcripts');
865 + }
866 + }
867 +}
97 868
98 -function mxchat_add_missing_columns($table, $column_name, $column_type) {
869 +/**
870 + * Clean up on plugin deactivation
871 + */
872 +function mxchat_deactivate() {
873 + // Clear scheduled cron jobs
874 + wp_clear_scheduled_hook('mxchat_reset_rate_limits');
875 + wp_clear_scheduled_hook('mxchat_cleanup_old_transcripts');
876 + wp_clear_scheduled_hook('mxchat_send_delayed_transcript');
877 +
878 + // Clear fallback options
879 + delete_option('mxchat_use_fallback_rate_limits');
880 + delete_option('mxchat_next_rate_limit_check');
881 + delete_option('mxchat_fallback_check_interval');
882 +
883 + // NOTE: We do NOT delete queue tables on deactivation
884 + // This preserves data if user accidentally deactivates the plugin
885 +}
886 +
887 +/**
888 + * Check if fallback rate limit cleanup is needed
889 + */
890 +function mxchat_check_fallback_rate_limits() {
891 + $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
892 +
893 + if (!$use_fallback) {
894 + return;
895 + }
896 +
897 + $next_check = get_option('mxchat_next_rate_limit_check', 0);
898 +
899 + if (time() >= $next_check) {
900 + // Only run reset if the MxChat_Integrator class exists
901 + if (class_exists('MxChat_Integrator')) {
902 + $integrator = new MxChat_Integrator();
903 + if (method_exists($integrator, 'mxchat_reset_rate_limits')) {
904 + $integrator->mxchat_reset_rate_limits();
905 + update_option('mxchat_next_rate_limit_check', time() + 3600);
906 + }
907 + }
908 + }
909 +}
910 +
911 +/**
912 + * Robust update checking with role restriction migration, model deprecation, and queue tables
913 + * CRITICAL: This runs on EVERY page load to ensure tables exist
914 + */
915 +function mxchat_check_for_update() {
99 916 global $wpdb;
100 - $column_exists = $wpdb->get_results($wpdb->prepare("SHOW COLUMNS FROM $table LIKE %s", $column_name));
101 - if (empty($column_exists)) {
102 - $wpdb->query("ALTER TABLE $table ADD COLUMN $column_name $column_type");
917 +
918 + try {
919 + $current_version = get_option('mxchat_plugin_version', '0.0.0');
920 + $plugin_version = MXCHAT_VERSION;
921 +
922 + // Always ensure critical tables exist (even if version matches)
923 + // This handles manual table deletion or fresh installs
924 + $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
925 + $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
926 +
927 + $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$chat_table'") === $chat_table;
928 + $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
929 +
930 + if (!$chat_exists || !$queue_exists) {
931 + //error_log("MxChat: Critical tables missing, running activation");
932 + mxchat_activate();
933 + }
934 +
935 + // Version-specific migrations
936 + if ($current_version !== $plugin_version) {
937 + //error_log("MxChat: Version change detected: $current_version -> $plugin_version");
938 +
939 + // Run live agent update BEFORE updating the stored version
940 + mxchat_handle_live_agent_update();
941 +
942 + // Run theme migration notice for 3.0.1 (AI theme CSS structure changes)
943 + mxchat_handle_theme_migration_notice();
944 +
945 + // Run role restriction migration for 2.4.1
946 + if (version_compare($current_version, '2.4.1', '<')) {
947 + mxchat_add_role_restriction_column();
948 + }
949 +
950 + // Run enabled_bots column migration for 2.4.4
951 + if (version_compare($current_version, '2.4.4', '<')) {
952 + mxchat_add_enabled_bots_column();
953 + }
954 +
955 + // Run model migration for 2.5.1 (Claude deprecation)
956 + if (version_compare($current_version, '2.5.1', '<')) {
957 + mxchat_migrate_deprecated_models();
958 + }
959 +
960 + // 2.5.2: Ensure queue tables exist and fix URL column sizes for all users upgrading to 2.5.2
961 + if (version_compare($current_version, '2.5.2', '<')) {
962 + mxchat_create_queue_tables();
963 + mxchat_fix_url_column_size(); // NEW: Fix URL column size for long URLs
964 + //error_log("MxChat: Queue tables created and URL columns updated for upgrade to 2.5.2");
965 + }
966 +
967 + // 2.6.0: Ensure rag_context column exists for retrieved documents feature
968 + if (version_compare($current_version, '2.6.0', '<')) {
969 + $chat_table = $wpdb->prefix . 'mxchat_chat_transcripts';
970 + mxchat_ensure_all_columns($chat_table);
971 + //error_log("MxChat: rag_context column migration for 2.6.0");
972 + }
973 +
974 + // 3.0.5: Migrate deprecated Gemini embedding model
975 + if (version_compare($current_version, '3.0.5', '<')) {
976 + mxchat_migrate_gemini_embedding_model();
977 + }
978 +
979 + // 3.0.6: Migrate deprecated OpenAI and Claude models
980 + if (version_compare($current_version, '3.0.6', '<')) {
981 + mxchat_migrate_deprecated_models();
982 + }
983 +
984 + // Run full activation to ensure everything is up to date
985 + mxchat_activate();
986 +
987 + // Run migration functions
988 + mxchat_migrate_live_agent_status();
989 +
990 + // Add the cleanup function for version 2.1.8
991 + if (version_compare($current_version, '2.1.8', '<')) {
992 + $deleted = mxchat_cleanup_orphaned_chat_history();
993 + }
994 +
995 + // Update version LAST
996 + update_option('mxchat_plugin_version', $plugin_version);
997 +
998 + //error_log("MxChat: Updated from version $current_version to $plugin_version");
999 + }
1000 +
1001 + } catch (Exception $e) {
1002 + //error_log('MxChat update error: ' . $e->getMessage());
1003 + // Don't update version if there was an error
103 1004 }
104 1005 }
105 1006
106 -function mxchat_check_for_update() {
107 - $current_version = get_option('mxchat_plugin_version');
108 - $plugin_version = '2.0.5'; // Update with your latest version
1007 +/**
1008 + * Ensure tables exist on every admin load for fresh installations
1009 + * This is a safety net for cases where activation hook doesn't fire
1010 + */
1011 +function mxchat_ensure_tables_exist() {
1012 + global $wpdb;
1013 +
1014 + // Only run for admin users to avoid performance impact
1015 + if (!current_user_can('administrator')) {
1016 + return;
1017 + }
1018 +
1019 + // Check if we've already verified tables in this session
1020 + static $tables_checked = false;
1021 + if ($tables_checked) {
1022 + return;
1023 + }
1024 + $tables_checked = true;
1025 +
1026 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1027 + $queue_table = $wpdb->prefix . 'mxchat_processing_queue';
1028 +
1029 + $chat_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
1030 + $queue_exists = $wpdb->get_var("SHOW TABLES LIKE '$queue_table'") === $queue_table;
1031 +
1032 + if (!$chat_exists || !$queue_exists) {
1033 + //error_log("MxChat: Tables missing on admin load, running activation");
1034 + mxchat_activate();
1035 + }
1036 +}
109 1037
110 - if ($current_version !== $plugin_version) {
111 - mxchat_activate(); // Run the activation script to apply schema changes
112 - mxchat_migrate_live_agent_status(); // Add migration for live agent status
113 - update_option('mxchat_plugin_version', $plugin_version); // Update the version
1038 +/**
1039 + * Clean up orphaned chat history options from the wp_options table
1040 + * @return int Number of options deleted
1041 + */
1042 +function mxchat_cleanup_orphaned_chat_history() {
1043 + global $wpdb;
1044 + $count = 0;
1045 +
1046 + // Get all option keys that match our pattern
1047 + $history_options = $wpdb->get_results(
1048 + "SELECT option_name FROM {$wpdb->options}
1049 + WHERE option_name LIKE 'mxchat_history_%'"
1050 + );
1051 +
1052 + if (!empty($history_options)) {
1053 + foreach ($history_options as $option) {
1054 + // Extract the session ID from the option name
1055 + $session_id = str_replace('mxchat_history_', '', $option->option_name);
1056 +
1057 + // Check if this session still exists in the custom table
1058 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
1059 + $exists = $wpdb->get_var(
1060 + $wpdb->prepare(
1061 + "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s",
1062 + $session_id
1063 + )
1064 + );
1065 +
1066 + // If session doesn't exist in the main table, delete the option
1067 + if ($exists == 0) {
1068 + delete_option($option->option_name);
1069 + // Also delete related metadata
1070 + delete_option("mxchat_email_{$session_id}");
1071 + delete_option("mxchat_name_{$session_id}");
1072 + delete_option("mxchat_agent_name_{$session_id}");
1073 + $count++;
1074 + }
1075 + }
114 1076 }
1077 +
1078 + return $count;
115 1079 }
116 1080
117 1081 function mxchat_migrate_live_agent_status() {
118 1082 $options = get_option('mxchat_options', []);
@@ -145,16 +1109,189 @@
145 1109 update_option('mxchat_options', $options);
146 1110 }
147 1111 }
148 1112
1113 +function mxchat_handle_live_agent_update() {
1114 + // Get the CURRENT stored version (before it gets updated)
1115 + $current_version = get_option('mxchat_plugin_version', '0.0.0');
1116 + $new_version = '2.2.2';
149 1117
150 -// Run the update check function on every request
151 -add_action('plugins_loaded', 'mxchat_check_for_update');
1118 + // Only run this once for the update to 2.2.2
1119 + $update_handled = get_option('mxchat_live_agent_update_2_2_2_handled', false);
152 1120
1121 + // Check if we're upgrading TO 2.2.2 and haven't handled this yet
1122 + if (version_compare($current_version, $new_version, '<') && !$update_handled) {
1123 + $options = get_option('mxchat_options', array());
1124 +
1125 + // Check if live agent was previously enabled
1126 + if (isset($options['live_agent_status']) && $options['live_agent_status'] === 'on') {
1127 + // Disable live agent
1128 + $options['live_agent_status'] = 'off';
1129 + update_option('mxchat_options', $options);
1130 +
1131 + // Set flag to show the notification banner
1132 + update_option('mxchat_show_live_agent_disabled_notice', true);
1133 + }
1134 +
1135 + // Mark this update as handled
1136 + update_option('mxchat_live_agent_update_2_2_2_handled', true);
1137 + }
1138 +}
1139 +
1140 +/**
1141 + * Handle theme migration notice for version 3.0.1
1142 + * Shows a dismissible notice to Pro users about migrating AI-generated themes
1143 + */
1144 +function mxchat_handle_theme_migration_notice() {
1145 + // Get the CURRENT stored version (before it gets updated)
1146 + $current_version = get_option('mxchat_plugin_version', '0.0.0');
1147 + $target_version = '3.0.1';
1148 +
1149 + // Only run this once for the update to 3.0.1
1150 + $update_handled = get_option('mxchat_theme_migration_update_3_0_1_handled', false);
1151 +
1152 + // Check if we're upgrading TO 3.0.1 and haven't handled this yet
1153 + if (version_compare($current_version, $target_version, '<') && !$update_handled) {
1154 + // Check if Pro is activated - only show to Pro users
1155 + $license_status = get_option('mxchat_license_status', 'inactive');
1156 + $is_pro = ($license_status === 'active' || $license_status === esc_html__('active', 'mxchat'));
1157 +
1158 + if ($is_pro) {
1159 + // Set flag to show the theme migration notification banner
1160 + update_option('mxchat_show_theme_migration_notice', true);
1161 + }
1162 +
1163 + // Mark this update as handled (whether Pro or not)
1164 + update_option('mxchat_theme_migration_update_3_0_1_handled', true);
1165 + }
1166 +}
1167 +
1168 +// Initialize plugin safely
1169 +function mxchat_init() {
1170 + // Include all class files first
1171 + mxchat_include_classes();
1172 +
1173 + // Run update check (this also ensures tables exist)
1174 + mxchat_check_for_update();
1175 +
1176 + // CRITICAL: Ensure tables exist on admin pages (safety net)
1177 + add_action('admin_init', 'mxchat_ensure_tables_exist', 1);
1178 +
1179 + // Add fallback rate limit check
1180 + add_action('init', 'mxchat_check_fallback_rate_limits', 5);
1181 +
1182 + // Add migration notice hook
1183 + add_action('admin_notices', 'mxchat_show_migration_notice');
1184 +
1185 + // Initialize classes with error handling
1186 + try {
1187 + // Initialize admin classes
1188 + if (is_admin()) {
1189 + if (class_exists('MxChat_Knowledge_Manager')) {
1190 + $mxchat_knowledge_manager = new MxChat_Knowledge_Manager();
1191 +
1192 + if (class_exists('MxChat_Admin')) {
1193 + $mxchat_admin = new MxChat_Admin($mxchat_knowledge_manager);
1194 + }
1195 + }
1196 +
1197 + // Initialize meta box class
1198 + if (class_exists('MxChat_Meta_Box')) {
1199 + new MxChat_Meta_Box();
1200 + }
1201 +
1202 + }
1203 +
1204 + // Initialize content generator globally — it registers wp_head hook
1205 + // for frontend CSS injection, plus wp_ajax_ hooks for admin.
1206 + if (class_exists('MxChat_Content_Generator')) {
1207 + new MxChat_Content_Generator();
1208 + }
1209 +
1210 + // Initialize public classes
1211 + if (class_exists('MxChat_Public')) {
1212 + $mxchat_public = new MxChat_Public();
1213 + }
1214 +
1215 + if (class_exists('MxChat_Integrator')) {
1216 + global $mxchat_integrator;
1217 + $mxchat_integrator = new MxChat_Integrator();
1218 + }
1219 +
1220 + } catch (Exception $e) {
1221 + //error_log('MxChat initialization error: ' . $e->getMessage());
1222 +
1223 + // Show admin notice if there's an error
1224 + if (is_admin()) {
1225 + add_action('admin_notices', function() use ($e) {
1226 + echo '<div class="notice notice-error"><p>';
1227 + echo '<strong>MxChat Error:</strong> Plugin initialization failed. ';
1228 + echo 'Please check error logs or contact support. Error: ' . esc_html($e->getMessage());
1229 + echo '</p></div>';
1230 + });
1231 + }
1232 + }
1233 +}
1234 +
1235 +// Run initialization on plugins_loaded
1236 +add_action('plugins_loaded', 'mxchat_init');
1237 +
1238 +// Run migration check on admin init (for auto-updates without reactivation)
1239 +add_action('admin_init', 'mxchat_check_and_run_migrations');
1240 +
1241 +/**
1242 + * Check and run migrations on admin init
1243 + * This ensures migrations run even when plugin is auto-updated
1244 + */
1245 +function mxchat_check_and_run_migrations() {
1246 + // Only run in admin and not on every request
1247 + static $checked = false;
1248 + if ($checked) {
1249 + return;
1250 + }
1251 + $checked = true;
1252 +
1253 + mxchat_migrate_pinecone_roles_add_bot_id();
1254 + mxchat_migrate_add_content_type_column();
1255 + mxchat_migrate_add_translations_table();
1256 +}
1257 +
1258 +/**
1259 + * Migration: Create transcript translations table (v3.0.4)
1260 + * For users upgrading from versions before 3.0.4
1261 + */
1262 +function mxchat_migrate_add_translations_table() {
1263 + $migration_key = 'mxchat_translations_table_created';
1264 +
1265 + // Check if migration already ran
1266 + if (get_option($migration_key)) {
1267 + return;
1268 + }
1269 +
1270 + // Create the translations table
1271 + mxchat_create_translations_table();
1272 +
1273 + // Mark migration as complete
1274 + update_option($migration_key, '3.0.4');
1275 +}
1276 +
1277 +/**
1278 + * Migration: Update deprecated Gemini embedding model (v3.0.5)
1279 + * Updates gemini-embedding-exp-03-07 to gemini-embedding-001 for users who had it selected
1280 + */
1281 +function mxchat_migrate_gemini_embedding_model() {
1282 + $options = get_option('mxchat_options', array());
1283 +
1284 + if (isset($options['embedding_model']) && $options['embedding_model'] === 'gemini-embedding-exp-03-07') {
1285 + $options['embedding_model'] = 'gemini-embedding-001';
1286 + update_option('mxchat_options', $options);
1287 + }
1288 +}
1289 +
153 1290 // Register activation hook
154 1291 register_activation_hook(__FILE__, 'mxchat_activate');
155 1292
156 -
1293 +// Add cron schedule
157 1294 add_filter('cron_schedules', function($schedules) {
158 1295 $schedules['one_minute'] = array(
159 1296 'interval' => 60,
160 1297 'display' => 'Every Minute'
@@ -161,16 +1298,6 @@
161 1298 );
162 1299 return $schedules;
163 1300 });
164 1301
165 -add_action('init', function() {
166 - add_action('mxchat_process_pdf_pages', array('MxChat_Admin', 'process_pdf_pages_cron'), 10, 5);
167 - add_action('mxchat_process_sitemap_urls', array('MxChat_Admin', 'process_sitemap_urls_cron'), 10, 5);
168 -});
169 -
170 -
171 -// Instantiate classes
172 -if (is_admin()) {
173 - $mxchat_admin = new MxChat_Admin();
174 -}
175 -$mxchat_public = new MxChat_Public();
176 -$mxchat_integrator = new MxChat_Integrator();
1302 +// Register deactivation hook
1303 +register_deactivation_hook(__FILE__, 'mxchat_deactivate');