PluginProbe
MxChat – AI Chatbot & Content Generation for WordPress / 2.4.5
MxChat – AI Chatbot & Content Generation for WordPress v2.4.5
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 +578 -52 2.0.42.4.5 View file →
@@ -1,9 +1,9 @@
1 1 <?php
2 2 /**
3 3 * Plugin Name: MxChat
4 4 * Description: AI chatbot for WordPress with OpenAI, Claude, xAI, DeepSeek, live agent, PDF uploads, WooCommerce, and training on website data.
5 - * Version: 2.0.4
5 + * Version: 2.4.5
6 6 * Author: MxChat
7 7 * Author URI: https://mxchat.ai
8 8 * License: GPLv2 or later
9 9 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
@@ -14,8 +14,10 @@
14 14 if (!defined('ABSPATH')) {
15 15 exit; // Exit if accessed directly.
16 16 }
17 17
18 +// Define plugin version constant for asset versioning
19 +define('MXCHAT_VERSION', '2.4.5');
18 20
19 21 function mxchat_load_textdomain() {
20 22 load_plugin_textdomain('mxchat', false, dirname(plugin_basename(__FILE__)) . '/languages');
21 23 }
@@ -20,25 +22,72 @@
20 22 load_plugin_textdomain('mxchat', false, dirname(plugin_basename(__FILE__)) . '/languages');
21 23 }
22 24 add_action('plugins_loaded', 'mxchat_load_textdomain');
23 25
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';
26 +// Include classes with error handling
27 +function mxchat_include_classes() {
28 + $class_files = array(
29 + 'includes/class-mxchat-integrator.php',
30 + 'includes/class-mxchat-admin.php',
31 + 'includes/class-mxchat-public.php',
32 + 'includes/class-mxchat-utils.php',
33 + 'includes/class-mxchat-user.php',
34 + 'includes/class-mxchat-meta-box.php',
35 + 'includes/pdf-parser/alt_autoload.php',
36 + 'includes/class-mxchat-word-handler.php',
37 + 'admin/class-ajax-handler.php',
38 + 'admin/class-pinecone-manager.php',
39 + 'admin/class-knowledge-manager.php'
40 + );
33 41
34 -function mxchat_activate() {
42 + foreach ($class_files as $file) {
43 + $file_path = plugin_dir_path(__FILE__) . $file;
44 + if (file_exists($file_path)) {
45 + require_once $file_path;
46 + } else {
47 + //error_log('MxChat: Missing class file - ' . $file);
48 + }
49 + }
50 +}
51 +
52 +/**
53 + * Create URL click tracking table
54 + */
55 +function mxchat_create_url_clicks_table() {
35 56 global $wpdb;
57 +
58 + $table_name = $wpdb->prefix . 'mxchat_url_clicks';
59 +
36 60 $charset_collate = $wpdb->get_charset_collate();
61 +
62 + $sql = "CREATE TABLE $table_name (
63 + id mediumint(9) NOT NULL AUTO_INCREMENT,
64 + session_id varchar(100) NOT NULL,
65 + clicked_url text NOT NULL,
66 + message_context text,
67 + click_timestamp datetime DEFAULT CURRENT_TIMESTAMP,
68 + user_ip varchar(45),
69 + user_agent text,
70 + PRIMARY KEY (id),
71 + KEY session_id (session_id),
72 + KEY click_timestamp (click_timestamp)
73 + ) $charset_collate;";
74 +
75 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
76 + dbDelta($sql);
77 +}
37 78
38 - // Chat Transcripts Table
39 - $chat_transcripts_table = $wpdb->prefix . 'mxchat_chat_transcripts';
40 - $sql_chat_transcripts = "CREATE TABLE $chat_transcripts_table (
79 +/**
80 + * FIXED: Robust table creation and column management
81 + */
82 +function mxchat_create_chat_transcripts_table() {
83 + global $wpdb;
84 +
85 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
86 + $charset_collate = $wpdb->get_charset_collate();
87 +
88 + // Create table with ALL columns including user_name from the start
89 + $sql = "CREATE TABLE $table_name (
41 90 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
42 91 user_id MEDIUMINT(9) DEFAULT 0,
43 92 session_id VARCHAR(255) NOT NULL,
44 93 role VARCHAR(255) NOT NULL,
@@ -43,12 +92,206 @@
43 92 session_id VARCHAR(255) NOT NULL,
44 93 role VARCHAR(255) NOT NULL,
45 94 message TEXT NOT NULL,
46 95 user_email VARCHAR(255) DEFAULT NULL,
96 + user_name VARCHAR(100) DEFAULT NULL,
97 + user_identifier VARCHAR(255) DEFAULT NULL,
98 + originating_page_url TEXT DEFAULT NULL,
99 + originating_page_title VARCHAR(500) DEFAULT NULL,
47 100 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
48 - PRIMARY KEY (id)
101 + PRIMARY KEY (id),
102 + KEY session_id (session_id),
103 + KEY user_email (user_email),
104 + KEY timestamp (timestamp)
49 105 ) $charset_collate;";
106 +
107 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
108 + $result = dbDelta($sql);
109 +
110 + // Log the result for debugging
111 + if (empty($result)) {
112 + //error_log("MxChat: dbDelta returned empty result for chat transcripts table");
113 + } else {
114 + //error_log("MxChat: dbDelta result: " . print_r($result, true));
115 + }
116 +
117 + // IMPORTANT: Ensure all columns exist for existing installations
118 + mxchat_ensure_all_columns($table_name);
119 +}
50 120
121 +/**
122 + * Ensure all required columns exist (for upgrades)
123 + */
124 +function mxchat_ensure_all_columns($table_name) {
125 + global $wpdb;
126 +
127 + // First check if table exists
128 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
129 + if (!$table_exists) {
130 + //error_log("MxChat: Table $table_name does not exist, cannot add columns");
131 + return;
132 + }
133 +
134 + // Define all required columns and their types
135 + $required_columns = [
136 + 'user_identifier' => 'VARCHAR(255) DEFAULT NULL',
137 + 'user_email' => 'VARCHAR(255) DEFAULT NULL',
138 + 'user_name' => 'VARCHAR(100) DEFAULT NULL',
139 + 'originating_page_url' => 'TEXT DEFAULT NULL',
140 + 'originating_page_title' => 'VARCHAR(500) DEFAULT NULL'
141 + ];
142 +
143 + // Get existing columns
144 + $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name");
145 + if (empty($existing_columns)) {
146 + //error_log("MxChat: Could not get columns for table $table_name");
147 + return;
148 + }
149 +
150 + $existing_column_names = array_column($existing_columns, 'Field');
151 +
152 + // Add missing columns
153 + foreach ($required_columns as $column_name => $column_definition) {
154 + if (!in_array($column_name, $existing_column_names)) {
155 + $alter_sql = "ALTER TABLE $table_name ADD COLUMN $column_name $column_definition";
156 + $result = $wpdb->query($alter_sql);
157 +
158 + if ($result === false) {
159 + //error_log("MxChat: Failed to add column $column_name to $table_name. Error: " . $wpdb->last_error);
160 + } else {
161 + //error_log("MxChat: Successfully added column $column_name to $table_name");
162 + }
163 + }
164 + }
165 +}
166 +
167 +/**
168 + * Add role restriction column to knowledge base table
169 + */
170 +function mxchat_add_role_restriction_column() {
171 + global $wpdb;
172 + $table_name = $wpdb->prefix . 'mxchat_system_prompt_content';
173 +
174 + // Check if table exists first
175 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
176 + if (!$table_exists) {
177 + //error_log("MxChat: System prompt content table does not exist, cannot add role_restriction column");
178 + return;
179 + }
180 +
181 + // Check if column already exists
182 + $column_exists = $wpdb->get_results(
183 + $wpdb->prepare(
184 + "SHOW COLUMNS FROM {$table_name} LIKE %s",
185 + 'role_restriction'
186 + )
187 + );
188 +
189 + if (empty($column_exists)) {
190 + $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url";
191 + $result = $wpdb->query($alter_sql);
192 +
193 + if ($result === false) {
194 + //error_log("MxChat: Failed to add role_restriction column. Error: " . $wpdb->last_error);
195 + } else {
196 + //error_log("MxChat: Successfully added role_restriction column");
197 +
198 + // Set all existing records to 'public' (everyone can access)
199 + $update_result = $wpdb->query(
200 + "UPDATE {$table_name}
201 + SET role_restriction = 'public'
202 + WHERE role_restriction IS NULL OR role_restriction = ''"
203 + );
204 +
205 + if ($update_result !== false) {
206 + //error_log("MxChat: Updated {$update_result} existing records to public access");
207 + }
208 + }
209 + }
210 +}
211 +
212 +/**
213 + * NEW: Add enabled_bots column to intents table for multi-bot action filtering
214 + */
215 +function mxchat_add_enabled_bots_column() {
216 + global $wpdb;
217 + $table_name = $wpdb->prefix . 'mxchat_intents';
218 +
219 + // Check if table exists first
220 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
221 + if (!$table_exists) {
222 + //error_log("MxChat: Intents table does not exist, cannot add enabled_bots column");
223 + return;
224 + }
225 +
226 + // Check if column already exists
227 + $column_exists = $wpdb->get_results(
228 + $wpdb->prepare(
229 + "SHOW COLUMNS FROM {$table_name} LIKE %s",
230 + 'enabled_bots'
231 + )
232 + );
233 +
234 + if (empty($column_exists)) {
235 + $alter_sql = "ALTER TABLE {$table_name} ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled";
236 + $result = $wpdb->query($alter_sql);
237 +
238 + if ($result === false) {
239 + //error_log("MxChat: Failed to add enabled_bots column. Error: " . $wpdb->last_error);
240 + } else {
241 + //error_log("MxChat: Successfully added enabled_bots column");
242 +
243 + // Set all existing actions to work with 'default' bot for backward compatibility
244 + $default_bots = json_encode(['default']);
245 + $update_result = $wpdb->query(
246 + $wpdb->prepare(
247 + "UPDATE {$table_name}
248 + SET enabled_bots = %s
249 + WHERE enabled_bots IS NULL OR enabled_bots = ''",
250 + $default_bots
251 + )
252 + );
253 +
254 + if ($update_result !== false) {
255 + //error_log("MxChat: Updated {$update_result} existing actions to work with default bot");
256 + }
257 + }
258 + }
259 +}
260 +
261 +/**
262 + * Create Pinecone role restrictions table
263 + */
264 +function mxchat_create_pinecone_roles_table() {
265 + global $wpdb;
266 +
267 + $table_name = $wpdb->prefix . 'mxchat_pinecone_roles';
268 + $charset_collate = $wpdb->get_charset_collate();
269 +
270 + $sql = "CREATE TABLE $table_name (
271 + id mediumint(9) NOT NULL AUTO_INCREMENT,
272 + vector_id varchar(255) NOT NULL,
273 + source_url text,
274 + role_restriction varchar(50) DEFAULT 'public',
275 + updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
276 + PRIMARY KEY (id),
277 + UNIQUE KEY vector_id (vector_id),
278 + KEY role_restriction (role_restriction)
279 + ) $charset_collate;";
280 +
281 + require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
282 + dbDelta($sql);
283 +}
284 +
285 +function mxchat_activate() {
286 + global $wpdb;
287 + $charset_collate = $wpdb->get_charset_collate();
288 +
289 + //error_log("MxChat: Running activation function");
290 +
291 + // Create chat transcripts table with improved function
292 + mxchat_create_chat_transcripts_table();
293 +
51 294 // System Prompt Content Table
52 295 $system_prompt_table = $wpdb->prefix . 'mxchat_system_prompt_content';
53 296 $sql_system_prompt = "CREATE TABLE $system_prompt_table (
54 297 id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
@@ -55,13 +298,14 @@
55 298 url VARCHAR(255) NOT NULL,
56 299 article_content LONGTEXT NOT NULL,
57 300 embedding_vector LONGTEXT,
58 301 source_url VARCHAR(255) DEFAULT NULL,
302 + role_restriction VARCHAR(50) DEFAULT 'public',
59 303 timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
60 304 PRIMARY KEY (id)
61 305 ) $charset_collate;";
62 306
63 - // Intents Table
307 + // Intents Table - NOW INCLUDES enabled_bots column from the start
64 308 $intents_table = $wpdb->prefix . 'mxchat_intents';
65 309 $sql_intents_table = "CREATE TABLE $intents_table (
66 310 id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
67 311 intent_label VARCHAR(255) NOT NULL,
@@ -68,51 +312,261 @@
68 312 phrases TEXT NOT NULL,
69 313 embedding_vector LONGTEXT NOT NULL,
70 314 callback_function VARCHAR(255) NOT NULL,
71 315 similarity_threshold FLOAT DEFAULT 0.85,
316 + enabled TINYINT(1) NOT NULL DEFAULT 1,
317 + enabled_bots LONGTEXT DEFAULT NULL,
72 318 PRIMARY KEY (id)
73 319 ) $charset_collate;";
74 320
75 321 require_once ABSPATH . 'wp-admin/includes/upgrade.php';
76 322
77 - // Create or update tables
78 - dbDelta($sql_chat_transcripts);
323 + // Create other tables
79 324 dbDelta($sql_system_prompt);
80 325 dbDelta($sql_intents_table);
81 326
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');
327 + // Create URL click tracking table
328 + mxchat_create_url_clicks_table();
329 +
330 + //Create Pinecone roles table
331 + mxchat_create_pinecone_roles_table();
85 332
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');
333 + // Ensure additional columns in system prompt table
334 + $existing_system_columns = $wpdb->get_results("SHOW COLUMNS FROM $system_prompt_table");
335 + if (!empty($existing_system_columns)) {
336 + $existing_system_column_names = array_column($existing_system_columns, 'Field');
337 +
338 + if (!in_array('embedding_vector', $existing_system_column_names)) {
339 + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN embedding_vector LONGTEXT");
340 + }
341 + if (!in_array('source_url', $existing_system_column_names)) {
342 + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN source_url VARCHAR(255) DEFAULT NULL");
343 + }
344 + if (!in_array('role_restriction', $existing_system_column_names)) {
345 + $wpdb->query("ALTER TABLE $system_prompt_table ADD COLUMN role_restriction VARCHAR(50) DEFAULT 'public' AFTER source_url");
346 + }
347 + }
89 348
90 349 // Set default thresholds for existing intents
91 350 $wpdb->query("UPDATE {$intents_table} SET similarity_threshold = 0.85 WHERE similarity_threshold IS NULL");
351 +
352 + // Ensure enabled column exists in intents table
353 + $existing_intent_columns = $wpdb->get_results("SHOW COLUMNS FROM $intents_table");
354 + if (!empty($existing_intent_columns)) {
355 + $existing_intent_column_names = array_column($existing_intent_columns, 'Field');
356 +
357 + if (!in_array('enabled', $existing_intent_column_names)) {
358 + $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled TINYINT(1) NOT NULL DEFAULT 1");
359 + }
360 +
361 + // NEW: Ensure enabled_bots column exists for existing installations
362 + if (!in_array('enabled_bots', $existing_intent_column_names)) {
363 + $wpdb->query("ALTER TABLE $intents_table ADD COLUMN enabled_bots LONGTEXT DEFAULT NULL AFTER enabled");
364 +
365 + // Set existing actions to work with default bot
366 + $default_bots = json_encode(['default']);
367 + $wpdb->query($wpdb->prepare(
368 + "UPDATE {$intents_table} SET enabled_bots = %s WHERE enabled_bots IS NULL",
369 + $default_bots
370 + ));
371 + }
372 + }
92 373
93 - // Update plugin version in the database
94 - update_option('mxchat_plugin_version', '2.0.4');
374 + // Setup cron jobs
375 + mxchat_setup_cron_jobs();
376 +
377 + // Update version
378 + update_option('mxchat_plugin_version', MXCHAT_VERSION);
379 +
380 + //error_log("MxChat: Activation function completed");
95 381 }
96 382
383 +/**
384 + * Setup cron jobs on plugin activation
385 + */
386 +function mxchat_setup_cron_jobs() {
387 + // Clear any existing cron jobs first
388 + wp_clear_scheduled_hook('mxchat_reset_rate_limits');
389 +
390 + // Check if WordPress cron is disabled
391 + if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
392 + // Set flag to use fallback system
393 + update_option('mxchat_use_fallback_rate_limits', true);
394 + update_option('mxchat_next_rate_limit_check', time() + 3600);
395 + return;
396 + }
397 +
398 + // Schedule the rate limit reset cron job
399 + $result = wp_schedule_event(time() + 300, 'hourly', 'mxchat_reset_rate_limits');
400 +
401 + if ($result === false) {
402 + // Fallback if scheduling fails
403 + update_option('mxchat_use_fallback_rate_limits', true);
404 + update_option('mxchat_next_rate_limit_check', time() + 3600);
405 + } else {
406 + // Clear fallback flags if cron scheduling succeeded
407 + delete_option('mxchat_use_fallback_rate_limits');
408 + }
409 +}
97 410
98 -function mxchat_add_missing_columns($table, $column_name, $column_type) {
411 +/**
412 + * Clean up on plugin deactivation
413 + */
414 +function mxchat_deactivate() {
415 + // Clear scheduled cron jobs
416 + wp_clear_scheduled_hook('mxchat_reset_rate_limits');
417 +
418 + // Clear fallback options
419 + delete_option('mxchat_use_fallback_rate_limits');
420 + delete_option('mxchat_next_rate_limit_check');
421 + delete_option('mxchat_fallback_check_interval');
422 +}
423 +
424 +/**
425 + * Check if fallback rate limit cleanup is needed
426 + */
427 +function mxchat_check_fallback_rate_limits() {
428 + $use_fallback = get_option('mxchat_use_fallback_rate_limits', false);
429 +
430 + if (!$use_fallback) {
431 + return;
432 + }
433 +
434 + $next_check = get_option('mxchat_next_rate_limit_check', 0);
435 +
436 + if (time() >= $next_check) {
437 + // Only run reset if the MxChat_Integrator class exists
438 + if (class_exists('MxChat_Integrator')) {
439 + $integrator = new MxChat_Integrator();
440 + if (method_exists($integrator, 'mxchat_reset_rate_limits')) {
441 + $integrator->mxchat_reset_rate_limits();
442 + update_option('mxchat_next_rate_limit_check', time() + 3600);
443 + }
444 + }
445 + }
446 +}
447 +
448 +/**
449 + * Robust update checking with role restriction migration
450 + */
451 +function mxchat_check_for_update() {
452 + global $wpdb; // CRITICAL: Declare this at the top
453 +
454 + try {
455 + $current_version = get_option('mxchat_plugin_version', '0.0.0');
456 + $plugin_version = MXCHAT_VERSION;
457 +
458 + // Always run activation to ensure tables exist (safe for existing installations)
459 + if ($current_version !== $plugin_version) {
460 + //error_log("MxChat: Version change detected: $current_version -> $plugin_version");
461 +
462 + // Run live agent update BEFORE updating the stored version
463 + mxchat_handle_live_agent_update();
464 +
465 + //Run role restriction migration for 2.4.1
466 + if (version_compare($current_version, '2.4.1', '<')) {
467 + mxchat_add_role_restriction_column();
468 + }
469 +
470 + // NEW: Run enabled_bots column migration for 2.4.4
471 + if (version_compare($current_version, '2.4.4', '<')) {
472 + mxchat_add_enabled_bots_column();
473 + }
474 +
475 + // Run activation (this will create/update all tables and columns)
476 + mxchat_activate();
477 +
478 + // Run migration functions
479 + mxchat_migrate_live_agent_status();
480 +
481 + // Add the cleanup function for version 2.1.8
482 + if (version_compare($current_version, '2.1.8', '<')) {
483 + $deleted = mxchat_cleanup_orphaned_chat_history();
484 + }
485 +
486 + // Update version LAST
487 + update_option('mxchat_plugin_version', $plugin_version);
488 +
489 + //error_log("MxChat: Updated from version $current_version to $plugin_version");
490 + }
491 +
492 + // CRITICAL: Always ensure tables exist, even if version matches
493 + // This handles cases where tables were manually deleted
494 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
495 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
496 +
497 + if (!$table_exists) {
498 + //error_log("MxChat: Chat transcripts table missing, recreating...");
499 + mxchat_activate(); // Run full activation instead of just table creation
500 + }
501 +
502 + } catch (Exception $e) {
503 + //error_log('MxChat update error: ' . $e->getMessage());
504 + // Don't update version if there was an error
505 + }
506 +}
507 +
508 +/**
509 + * Ensure tables exist on every load for fresh installations
510 + */
511 +function mxchat_ensure_tables_exist() {
99 512 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");
513 +
514 + // Only run for admin users to avoid performance impact
515 + if (!current_user_can('administrator')) {
516 + return;
103 517 }
518 +
519 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
520 + $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
521 +
522 + if (!$table_exists) {
523 + //error_log("MxChat: Tables missing on admin load, running activation");
524 + mxchat_activate();
525 + }
104 526 }
105 527
106 -function mxchat_check_for_update() {
107 - $current_version = get_option('mxchat_plugin_version');
108 - $plugin_version = '2.0.4'; // Update with your latest version
528 +/**
529 + * Clean up orphaned chat history options from the wp_options table
530 + * @return int Number of options deleted
531 + */
532 +function mxchat_cleanup_orphaned_chat_history() {
533 + global $wpdb;
534 + $count = 0;
109 535
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
536 + // Get all option keys that match our pattern
537 + $history_options = $wpdb->get_results(
538 + "SELECT option_name FROM {$wpdb->options}
539 + WHERE option_name LIKE 'mxchat_history_%'"
540 + );
541 +
542 + if (!empty($history_options)) {
543 + foreach ($history_options as $option) {
544 + // Extract the session ID from the option name
545 + $session_id = str_replace('mxchat_history_', '', $option->option_name);
546 +
547 + // Check if this session still exists in the custom table
548 + $table_name = $wpdb->prefix . 'mxchat_chat_transcripts';
549 + $exists = $wpdb->get_var(
550 + $wpdb->prepare(
551 + "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s",
552 + $session_id
553 + )
554 + );
555 +
556 + // If session doesn't exist in the main table, delete the option
557 + if ($exists == 0) {
558 + delete_option($option->option_name);
559 + // Also delete related metadata
560 + delete_option("mxchat_email_{$session_id}");
561 + delete_option("mxchat_name_{$session_id}");
562 + delete_option("mxchat_agent_name_{$session_id}");
563 + $count++;
564 + }
565 + }
114 566 }
567 +
568 + return $count;
115 569 }
116 570
117 571 function mxchat_migrate_live_agent_status() {
118 572 $options = get_option('mxchat_options', []);
@@ -145,16 +599,98 @@
145 599 update_option('mxchat_options', $options);
146 600 }
147 601 }
148 602
603 +function mxchat_handle_live_agent_update() {
604 + // Get the CURRENT stored version (before it gets updated)
605 + $current_version = get_option('mxchat_plugin_version', '0.0.0');
606 + $new_version = '2.2.2';
607 +
608 + // Only run this once for the update to 2.2.2
609 + $update_handled = get_option('mxchat_live_agent_update_2_2_2_handled', false);
610 +
611 + // Check if we're upgrading TO 2.2.2 and haven't handled this yet
612 + if (version_compare($current_version, $new_version, '<') && !$update_handled) {
613 + $options = get_option('mxchat_options', array());
614 +
615 + // Check if live agent was previously enabled
616 + if (isset($options['live_agent_status']) && $options['live_agent_status'] === 'on') {
617 + // Disable live agent
618 + $options['live_agent_status'] = 'off';
619 + update_option('mxchat_options', $options);
620 +
621 + // Set flag to show the notification banner
622 + update_option('mxchat_show_live_agent_disabled_notice', true);
623 + }
624 +
625 + // Mark this update as handled
626 + update_option('mxchat_live_agent_update_2_2_2_handled', true);
627 + }
628 +}
149 629
150 -// Run the update check function on every request
151 -add_action('plugins_loaded', 'mxchat_check_for_update');
630 +// Initialize plugin safely
631 +function mxchat_init() {
632 + // Include all class files first
633 + mxchat_include_classes();
634 +
635 + // Run update check
636 + mxchat_check_for_update();
637 +
638 + // CRITICAL: Ensure tables exist (for fresh installations that don't trigger activation hook)
639 + add_action('admin_init', 'mxchat_ensure_tables_exist', 1);
640 +
641 + // Add fallback rate limit check
642 + add_action('init', 'mxchat_check_fallback_rate_limits', 5);
643 +
644 + // Initialize classes with error handling
645 + try {
646 + // Initialize admin classes
647 + if (is_admin()) {
648 + if (class_exists('MxChat_Knowledge_Manager')) {
649 + $mxchat_knowledge_manager = new MxChat_Knowledge_Manager();
650 +
651 + if (class_exists('MxChat_Admin')) {
652 + $mxchat_admin = new MxChat_Admin($mxchat_knowledge_manager);
653 + }
654 + }
655 +
656 + // Initialize meta box class
657 + if (class_exists('MxChat_Meta_Box')) {
658 + new MxChat_Meta_Box();
659 + }
660 + }
661 +
662 + // Initialize public classes
663 + if (class_exists('MxChat_Public')) {
664 + $mxchat_public = new MxChat_Public();
665 + }
666 +
667 + if (class_exists('MxChat_Integrator')) {
668 + $mxchat_integrator = new MxChat_Integrator();
669 + }
670 +
671 + } catch (Exception $e) {
672 + //error_log('MxChat initialization error: ' . $e->getMessage());
673 +
674 + // Show admin notice if there's an error
675 + if (is_admin()) {
676 + add_action('admin_notices', function() use ($e) {
677 + echo '<div class="notice notice-error"><p>';
678 + echo '<strong>MxChat Error:</strong> Plugin initialization failed. ';
679 + echo 'Please check error logs or contact support. Error: ' . esc_html($e->getMessage());
680 + echo '</p></div>';
681 + });
682 + }
683 + }
684 +}
152 685
686 +// Run initialization on plugins_loaded
687 +add_action('plugins_loaded', 'mxchat_init');
688 +
153 689 // Register activation hook
154 690 register_activation_hook(__FILE__, 'mxchat_activate');
155 691
156 -
692 +// Add cron schedule
157 693 add_filter('cron_schedules', function($schedules) {
158 694 $schedules['one_minute'] = array(
159 695 'interval' => 60,
160 696 'display' => 'Every Minute'
@@ -161,16 +697,6 @@
161 697 );
162 698 return $schedules;
163 699 });
164 700
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();
701 +// Register deactivation hook
702 +register_deactivation_hook(__FILE__, 'mxchat_deactivate');