get_charset_collate(); $sql = "CREATE TABLE {$table_name} ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, user_id BIGINT(20) UNSIGNED NOT NULL, user_message TEXT NOT NULL, bot_response TEXT NOT NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY user_id (user_id), KEY created_at (created_at) ) {$charset_collate};"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.DirectDatabaseQuery.DirectQuery dbDelta( $sql ); update_option( self::TABLE_VERSION_OPTION, self::TABLE_VERSION ); } /** * Returns the full table name including the wpdb prefix. */ public static function table_name() { global $wpdb; return $wpdb->prefix . 'wtofe_chatbot_history'; } /** * Saves a message pair to the database. * * @param int $user_id * @param string $user_message * @param string $bot_response */ public static function save_message( $user_id, $user_message, $bot_response ) { global $wpdb; $user_id = absint( $user_id ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->insert( self::table_name(), array( 'user_id' => $user_id, 'user_message' => wp_kses_post( $user_message ), 'bot_response' => wp_kses_post( $bot_response ), 'created_at' => current_time( 'mysql' ), ), array( '%d', '%s', '%s', '%s' ) ); // INVALIDATE CACHE: Delete the cached history so the new message appears next time wp_cache_delete( "wtofe_chat_history_{$user_id}_5", 'wtofe_chatbot' ); wp_cache_delete( "wtofe_chat_history_{$user_id}_20", 'wtofe_chatbot' ); wp_cache_delete( "wtofe_chat_history_{$user_id}_50", 'wtofe_chatbot' ); } /** * Returns the most recent N messages for a user, oldest first (for context). * * @param int $user_id * @param int $limit * @return array */ public static function get_user_history( $user_id, $limit = 5 ) { global $wpdb; $user_id = absint( $user_id ); $limit = absint( $limit ); // 1. Define a unique cache key for this user $cache_key = "wtofe_chat_history_{$user_id}_{$limit}"; $cache_grp = 'wtofe_chatbot'; // 2. Check if data exists in the Object Cache $cached_history = wp_cache_get( $cache_key, $cache_grp ); if ( false !== $cached_history ) { return $cached_history; // Return instantly from RAM } // 3. If not cached, query the database $table = self::table_name(); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM ( SELECT id, user_id, user_message, bot_response, created_at FROM {$table} WHERE user_id = %d ORDER BY created_at DESC LIMIT %d ) sub ORDER BY created_at ASC", $user_id, $limit ), ARRAY_A ); $history = $rows ?: array(); // 4. Save the result to the cache for 12 hours wp_cache_set( $cache_key, $history, $cache_grp, 12 * HOUR_IN_SECONDS ); return $history; } /** * Returns ALL messages for a user (used in admin display). * * @param int $user_id * @param string $date_from Y-m-d * @param string $date_to Y-m-d * @return array */ public static function get_user_history_admin( $user_id, $date_from = '', $date_to = '' ) { global $wpdb; $table = self::table_name(); if ( $date_from && $date_to ) { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE user_id = %d AND created_at >= %s AND created_at <= %s ORDER BY created_at ASC", absint( $user_id ), $date_from . ' 00:00:00', $date_to . ' 23:59:59' ), ARRAY_A ) ?: array(); } elseif ( $date_from ) { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE user_id = %d AND created_at >= %s ORDER BY created_at ASC", absint( $user_id ), $date_from . ' 00:00:00' ), ARRAY_A ) ?: array(); } elseif ( $date_to ) { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE user_id = %d AND created_at <= %s ORDER BY created_at ASC", absint( $user_id ), $date_to . ' 23:59:59' ), ARRAY_A ) ?: array(); } // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE user_id = %d ORDER BY created_at ASC", absint( $user_id ) ), ARRAY_A ) ?: array(); } /** * Returns a paginated list of users who have chat history. * * @param int $per_page * @param int $page * @return array { users: array, total: int } */ public static function get_users_with_history( $per_page = 20, $page = 1 ) { global $wpdb; $table = self::table_name(); $offset = ( max( 1, $page ) - 1 ) * $per_page; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $total = (int) $wpdb->get_var( "SELECT COUNT(DISTINCT user_id) FROM {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $rows = $wpdb->get_results( $wpdb->prepare( "SELECT user_id, COUNT(*) AS message_count, MAX(created_at) AS last_message FROM {$table} GROUP BY user_id ORDER BY last_message DESC LIMIT %d OFFSET %d", $per_page, $offset ), ARRAY_A ); return array( 'users' => $rows ?: array(), 'total' => $total ); } /** * Clears a single user's entire chat history and invalidates cache. * * @param int $user_id */ public static function clear_user_history( $user_id ) { global $wpdb; $user_id = absint( $user_id ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->delete( self::table_name(), array( 'user_id' => $user_id ), array( '%d' ) ); // INVALIDATE CACHE wp_cache_delete( "wtofe_chat_history_{$user_id}_5", 'wtofe_chatbot' ); wp_cache_delete( "wtofe_chat_history_{$user_id}_20", 'wtofe_chatbot' ); wp_cache_delete( "wtofe_chat_history_{$user_id}_50", 'wtofe_chatbot' ); } /** * Clears history for a user before a given date (admin timeline management). * * @param int $user_id 0 = all users * @param string $before_date Y-m-d format */ public static function clear_history_before( $user_id = 0, $before_date = '' ) { global $wpdb; $table = self::table_name(); if ( $user_id > 0 && $before_date ) { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE user_id = %d AND created_at < %s", $user_id, $before_date . ' 00:00:00' ) ); } elseif ( $user_id > 0 ) { self::clear_user_history( $user_id ); } elseif ( $before_date ) { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE created_at < %s", $before_date . ' 00:00:00' ) ); } else { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( "TRUNCATE TABLE {$table}" ); } } /** * Drops the table on plugin uninstall. */ public static function drop_table() { global $wpdb; $table = self::table_name(); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange $wpdb->query( "DROP TABLE IF EXISTS {$table}" ); delete_option( self::TABLE_VERSION_OPTION ); } }