get_col($wpdb->prepare(" SELECT comment_id FROM {$wpdb->commentmeta} WHERE meta_key = 'aiutoma_session_id' AND meta_value = %s ", $sid)); foreach ($comment_ids as $c_id) { wp_delete_comment(intval($c_id), true); } delete_transient('aiutoma_chatbot_' . $sid); delete_transient('aiutoma_chatbot_' . $sid . '_email'); delete_transient('aiutoma_chatbot_manual_' . $sid); } wp_safe_redirect(admin_url('admin.php?page=aiutoma-chatbot-logs')); exit; } $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : ''; if (in_array($action, ['delete_message', 'delete_session'], true)) { check_admin_referer('aiutoma_delete_log'); if ($action === 'delete_message' && !empty($_GET['comment_id'])) { wp_delete_comment(intval($_GET['comment_id']), true); wp_safe_redirect(admin_url('admin.php?page=aiutoma-chatbot-logs&action=view&session_id=' . urlencode($session_id))); exit; } elseif ($action === 'delete_session' && !empty($session_id)) { // Fetch comment IDs directly via SQL to bypass WPML filtering which hides comments with post_ID = 0 $comment_ids = $wpdb->get_col($wpdb->prepare(" SELECT comment_id FROM {$wpdb->commentmeta} WHERE meta_key = 'aiutoma_session_id' AND meta_value = %s ", $session_id)); foreach ($comment_ids as $c_id) { wp_delete_comment(intval($c_id), true); } delete_transient('aiutoma_chatbot_' . $session_id); delete_transient('aiutoma_chatbot_' . $session_id . '_email'); delete_transient('aiutoma_chatbot_manual_' . $session_id); wp_safe_redirect(admin_url('admin.php?page=aiutoma-chatbot-logs')); exit; } } } public function aiutoma_chatbot_logs_page_html() { global $wpdb; $action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : 'list'; $session_id = isset($_GET['session_id']) ? sanitize_text_field(wp_unslash($_GET['session_id'])) : ''; echo '
'; if ($action === 'view' && !empty($session_id)) { // View Single Thread echo '

' . esc_html__('Chat Session', 'aiutoma') . '

'; echo '' . esc_html__('Back to Logs', 'aiutoma') . ''; echo '
'; $comments = get_comments([ 'type' => 'aiutoma_chat', 'meta_key' => 'aiutoma_session_id', 'meta_value' => $session_id, 'orderby' => 'comment_date_gmt', 'order' => 'ASC', 'status' => 'all' ]); if (empty($comments)) { echo '

' . esc_html__('No messages found for this session.', 'aiutoma') . '

'; } else { echo '
'; $email = ''; $session_user_id = 0; $user_ip = ''; $user_agent = ''; $session_total_tokens = 0; foreach ($comments as $c) { $tokens = (int) get_comment_meta($c->comment_ID, 'aiutoma_tokens_total', true); $session_total_tokens += $tokens; if ($c->comment_author === 'Aiutoma' || strpos($c->comment_author, 'Operator') !== false) { continue; } if (!empty($c->comment_author_email) && empty($email)) { $email = $c->comment_author_email; } // Try extracting from text if email is not yet set natively if (empty($email) && preg_match('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/', $c->comment_content, $m)) { $email = $m[0]; } if (!empty($c->user_id) && $c->user_id > 0 && empty($session_user_id)) { $session_user_id = $c->user_id; } if (!empty($c->comment_author_IP) && empty($user_ip)) { $user_ip = $c->comment_author_IP; } if (!empty($c->comment_agent) && empty($user_agent)) { $user_agent = $c->comment_agent; } } /* translators: %s: Session ID */ echo '

' . esc_html(sprintf(__('Session ID: %s', 'aiutoma'), $session_id)) . '

'; $del_session_url = wp_nonce_url(admin_url('admin.php?page=aiutoma-chatbot-logs&action=delete_session&session_id=' . urlencode($session_id)), 'aiutoma_delete_log'); echo '

'; echo ''; echo '' . esc_html__('Delete Session', 'aiutoma') . ''; echo '

'; echo '
'; $total_sessions = 1; $last_seen = ''; if (!empty($email)) { $other_sessions_query = $wpdb->prepare(" SELECT m.meta_value AS session_id, MAX(c.comment_date) as last_activity FROM {$wpdb->comments} c INNER JOIN {$wpdb->commentmeta} m ON c.comment_ID = m.comment_id WHERE c.comment_type = 'aiutoma_chat' AND m.meta_key = 'aiutoma_session_id' AND c.comment_author_email = %s AND c.comment_author != 'Aiutoma' GROUP BY m.meta_value ORDER BY last_activity DESC ", $email); } else if (!empty($user_ip)) { $other_sessions_query = $wpdb->prepare(" SELECT m.meta_value AS session_id, MAX(c.comment_date) as last_activity FROM {$wpdb->comments} c INNER JOIN {$wpdb->commentmeta} m ON c.comment_ID = m.comment_id WHERE c.comment_type = 'aiutoma_chat' AND m.meta_key = 'aiutoma_session_id' AND c.comment_author_IP = %s AND c.comment_author != 'Aiutoma' GROUP BY m.meta_value ORDER BY last_activity DESC ", $user_ip); } if (isset($other_sessions_query)) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared $user_sessions = $wpdb->get_results($other_sessions_query); if (!empty($user_sessions)) { $total_sessions = count($user_sessions); $last_seen = $user_sessions[0]->last_activity; } } echo '
'; // Column 1: Info echo '
'; echo '

' . esc_html__('User Info', 'aiutoma') . '

'; if ($session_user_id > 0) { $user_link = get_edit_user_link($session_user_id); $user_obj = get_userdata($session_user_id); $user_name = $user_obj ? $user_obj->display_name : __('User', 'aiutoma'); echo '

' . esc_html__('Name:', 'aiutoma') . ' ' . esc_html($user_name) . '

'; } else { $name_to_show = ''; foreach ($comments as $c) { if ($c->comment_author !== 'Aiutoma' && $c->comment_author !== 'Visitor' && strpos($c->comment_author, 'Operator') === false) { $name_to_show = $c->comment_author; break; } else if (preg_match('/^My name is (.*?) and my email is/', $c->comment_content, $nm)) { $name_to_show = trim($nm[1]); break; } } echo '

' . esc_html__('Name:', 'aiutoma') . ' ' . esc_html($name_to_show ?: 'Visitor') . '

'; } if ($email) { echo '

' . esc_html__('Email:', 'aiutoma') . ' ' . esc_html($email) . '

'; } if ($user_ip) { echo '

' . esc_html__('IP:', 'aiutoma') . ' ' . esc_html($user_ip) . '

'; } if ($user_agent) { echo '

' . esc_html__('Browser:', 'aiutoma') . ' ' . esc_html(substr($user_agent, 0, 50)) . '...

'; } echo '
'; // Column 2: Stats echo '
'; echo '

' . esc_html__('Chat Stats', 'aiutoma') . '

'; echo '

' . esc_html__('Total Sessions:', 'aiutoma') . ' ' . esc_html($total_sessions) . '

'; if ($last_seen) { echo '

' . esc_html__('Last Seen:', 'aiutoma') . ' ' . esc_html($last_seen) . '

'; } if ($session_total_tokens > 0) { echo '

' . esc_html__('Session Tokens:', 'aiutoma') . ' ' . esc_html(number_format_i18n($session_total_tokens)) . '

'; } $filter_url = admin_url('admin.php?page=aiutoma-chatbot-logs'); if ($email) { $filter_url = add_query_arg('filter_email', urlencode($email), $filter_url); } else if ($user_ip) { $filter_url = add_query_arg('filter_ip', urlencode($user_ip), $filter_url); } echo '

' . esc_html__('View All User Sessions', 'aiutoma') . '

'; echo '
'; // Column 3: WooCommerce if (class_exists('WooCommerce') && $email) { echo '
'; echo '

' . esc_html__('WooCommerce', 'aiutoma') . '

'; $customer_orders = wc_get_orders([ 'email' => $email, 'limit' => -1, 'return' => 'ids' ]); $order_count = count($customer_orders); echo '

' . esc_html__('Orders:', 'aiutoma') . ' ' . esc_html($order_count) . '

'; if ($session_user_id > 0) { $cart_meta = get_user_meta($session_user_id, '_woocommerce_persistent_cart_' . get_current_blog_id(), true); if (!empty($cart_meta['cart'])) { $cart_count = array_sum(wp_list_pluck($cart_meta['cart'], 'quantity')); echo '

' . esc_html__('Items in Cart:', 'aiutoma') . ' ' . esc_html($cart_count) . '

'; echo '
    '; foreach ($cart_meta['cart'] as $item) { $product = wc_get_product($item['variation_id'] > 0 ? $item['variation_id'] : $item['product_id']); if ($product) { echo '
  • ' . esc_html($item['quantity']) . 'x ' . esc_html($product->get_name()) . '
  • '; } } echo '
'; } else { echo '

' . esc_html__('Cart:', 'aiutoma') . ' ' . esc_html__('Empty', 'aiutoma') . '

'; } } else { echo '

' . esc_html__('Cart items only visible for logged-in users.', 'aiutoma') . '

'; } if ($order_count > 0) { if (class_exists('\Automattic\WooCommerce\Utilities\OrderUtil') && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()) { $woo_link = admin_url('admin.php?page=wc-orders&_billing_email=' . urlencode($email)); } else { $woo_link = admin_url('edit.php?post_type=shop_order&s=' . urlencode($email)); } echo '

' . esc_html__('View Orders', 'aiutoma') . '

'; } echo '
'; } echo '
'; // close panel echo '
'; foreach ($comments as $c) { $is_ai = $c->comment_author === 'Aiutoma'; $is_sys = $c->comment_author === 'System'; $is_op = strpos($c->comment_author, 'Operator') !== false; if ($is_sys) { $msg_class = 'aiutoma-chatbot-msg-system'; $author_name_html = '' . esc_html__('System Notice', 'aiutoma') . ''; } else if ($is_op) { $msg_class = 'aiutoma-chatbot-msg-operator'; $author_name_html = esc_html($c->comment_author); } else if ($is_ai) { $msg_class = 'aiutoma-chatbot-msg-ai'; $ai_name = get_option('aiutoma_chatbot_name', 'AI Bot'); if (empty($ai_name)) { $ai_name = 'AI Bot'; } $ai_name = apply_filters('wpml_translate_single_string', $ai_name, 'aiutoma', 'chatbot_name'); $author_name_html = esc_html($ai_name); } else { $msg_class = 'aiutoma-chatbot-msg-user'; $author_display = ($c->comment_author === 'Visitor') ? 'You' : $c->comment_author; $author_name_html = esc_html($author_display); if (!empty($c->user_id) && $c->user_id > 0) { $user_link = get_edit_user_link($c->user_id); $author_name_html = '' . esc_html($author_display) . ''; } } $del_msg_url = wp_nonce_url(admin_url('admin.php?page=aiutoma-chatbot-logs&action=delete_message&comment_id=' . $c->comment_ID . '&session_id=' . urlencode($session_id)), 'aiutoma_delete_log'); $edit_msg_url = get_edit_comment_link($c->comment_ID); echo '
'; echo '
'; echo ''; echo ''; echo '
'; echo '' . wp_kses_post($author_name_html) . ' (' . esc_html($c->comment_date) . ')'; $msg_tokens = (int) get_comment_meta($c->comment_ID, 'aiutoma_tokens_total', true); if ($msg_tokens > 0) { echo ' ' . esc_html(number_format_i18n($msg_tokens)) . ' tokens'; } echo '
' . wp_kses_post($c->comment_content) . '
'; echo '
'; } echo '
'; $manual_mode = get_transient('aiutoma_chatbot_manual_' . $session_id); echo '
'; echo '

' . esc_html__('Operator Takeover', 'aiutoma') . '

'; echo '

'; echo ''; echo '

'; echo '
'; echo ''; echo '
'; echo '
'; echo '
'; } } else { // List Sessions echo '

' . esc_html__('Chatbot Logs', 'aiutoma') . '

'; $search_val = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : ''; if (!empty($_GET['filter_email']) || !empty($_GET['filter_ip']) || !empty($search_val)) { echo ' ' . esc_html__('Clear Filter', 'aiutoma') . ''; } // Search Form echo '
'; echo ''; echo ''; echo '
'; echo '
'; $per_page = 20; $paged = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1; $offset = ($paged - 1) * $per_page; $where_clause = "c.comment_type = 'aiutoma_chat' AND m.meta_key = 'aiutoma_session_id'"; $having_clause = "HAVING MAX(CASE WHEN c.comment_author != 'Aiutoma' THEN 1 ELSE 0 END) = 1 AND m.meta_value != ''"; $op_like = 'Operator%'; if (!empty($_GET['filter_email'])) { $having_clause .= $wpdb->prepare(" AND MAX(CASE WHEN c.comment_author != 'Aiutoma' AND c.comment_author NOT LIKE %s THEN c.comment_author_email ELSE NULL END) = %s", $op_like, sanitize_text_field($_GET['filter_email'])); } else if (!empty($_GET['filter_ip'])) { $having_clause .= $wpdb->prepare(" AND MAX(CASE WHEN c.comment_author != 'Aiutoma' AND c.comment_author NOT LIKE %s THEN c.comment_author_IP ELSE NULL END) = %s", $op_like, sanitize_text_field($_GET['filter_ip'])); } if (!empty($search_val)) { $like_val = '%' . $wpdb->esc_like($search_val) . '%'; $having_clause .= $wpdb->prepare(" AND ( MAX(CASE WHEN c.comment_author != 'Aiutoma' AND c.comment_author NOT LIKE %s THEN c.comment_author ELSE NULL END) LIKE %s OR MAX(CASE WHEN c.comment_author != 'Aiutoma' AND c.comment_author NOT LIKE %s THEN c.comment_author_email ELSE NULL END) LIKE %s )", $op_like, $like_val, $op_like, $like_val); } // Get unique session IDs using SQL since WP_Comment_Query doesn't support GROUP BY meta_value natively $query = " SELECT m.meta_value AS session_id, MAX(c.comment_date) AS last_activity, MAX(CASE WHEN c.comment_author != 'Aiutoma' AND c.comment_author NOT LIKE %s THEN c.comment_author_email ELSE NULL END) AS comment_author_email, MAX(CASE WHEN c.comment_author != 'Aiutoma' AND c.comment_author NOT LIKE %s THEN c.comment_author ELSE NULL END) AS comment_author, MAX(CASE WHEN c.comment_author != 'Aiutoma' AND c.comment_author NOT LIKE %s THEN c.user_id ELSE 0 END) AS user_id, MAX(CASE WHEN c.comment_author != 'Aiutoma' AND c.comment_author NOT LIKE %s THEN c.comment_author_IP ELSE NULL END) AS comment_author_IP, MAX(CASE WHEN c.comment_author != 'Aiutoma' AND c.comment_author NOT LIKE %s THEN c.comment_agent ELSE NULL END) AS comment_agent FROM {$wpdb->comments} c INNER JOIN {$wpdb->commentmeta} m ON c.comment_ID = m.comment_id WHERE {$where_clause} GROUP BY m.meta_value {$having_clause} ORDER BY last_activity DESC LIMIT %d OFFSET %d "; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $sessions = $wpdb->get_results($wpdb->prepare($query, $op_like, $op_like, $op_like, $op_like, $op_like, $per_page, $offset)); $total_query = " SELECT COUNT(*) FROM ( SELECT m.meta_value FROM {$wpdb->comments} c INNER JOIN {$wpdb->commentmeta} m ON c.comment_ID = m.comment_id WHERE {$where_clause} GROUP BY m.meta_value {$having_clause} ) AS count_table "; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $total_sessions = $wpdb->get_var($total_query); $total_pages = ceil($total_sessions / $per_page); if (empty($sessions)) { echo '

' . esc_html__('No chat sessions found.', 'aiutoma') . '

'; } else { echo '
'; wp_nonce_field('aiutoma_bulk_delete_logs'); echo '
'; echo '
'; echo ''; echo ''; echo '
'; echo '
'; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; foreach ($sessions as $s) { $view_url = admin_url('admin.php?page=aiutoma-chatbot-logs&action=view&session_id=' . urlencode($s->session_id)); $display_name = !empty($s->comment_author) ? $s->comment_author : 'Visitor'; if (!empty($s->user_id) && $s->user_id > 0) { $user_link = get_edit_user_link($s->user_id); $display_name_html = '' . esc_html($display_name) . ''; } else { $display_name_html = esc_html($display_name); } echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; $del_session_url = wp_nonce_url(admin_url('admin.php?page=aiutoma-chatbot-logs&action=delete_session&session_id=' . urlencode($s->session_id)), 'aiutoma_delete_log'); echo ''; echo ''; } echo '
' . esc_html__('Session ID', 'aiutoma') . '' . esc_html__('User', 'aiutoma') . '' . esc_html__('Email', 'aiutoma') . '' . esc_html__('IP', 'aiutoma') . '' . esc_html__('Browser', 'aiutoma') . '' . esc_html__('Last Activity', 'aiutoma') . '' . esc_html__('Actions', 'aiutoma') . '
' . esc_html($s->session_id) . '' . wp_kses_post($display_name_html) . '' . esc_html($s->comment_author_email) . '' . esc_html($s->comment_author_IP) . '' . esc_html($s->comment_agent) . '' . esc_html($s->last_activity) . ''; echo ''; echo ''; echo '
'; if ($total_pages > 1) { $page_links = paginate_links([ 'base' => add_query_arg('paged', '%#%'), 'format' => '', 'prev_text' => __('«', 'aiutoma'), 'next_text' => __('»', 'aiutoma'), 'total' => $total_pages, 'current' => $paged ]); if ($page_links) { echo '
' . wp_kses_post($page_links) . '
'; } } echo '
'; } } // Add new activity alert logic ?>

'; } public function handle_summarize_session_request(\WP_REST_Request $request) { $session_id = sanitize_text_field($request->get_param('session_id')); if (empty($session_id)) { return new \WP_REST_Response(['success' => false, 'message' => __('Missing session ID.', 'aiutoma')], 400); } $comments = get_comments([ 'type' => 'aiutoma_chat', 'meta_key' => 'aiutoma_session_id', 'meta_value' => $session_id, 'orderby' => 'comment_date_gmt', 'order' => 'ASC', 'status' => 'all' ]); if (empty($comments)) { return new \WP_REST_Response(['success' => false, 'message' => __('No messages found for this session.', 'aiutoma')], 404); } $chat_transcript = ""; foreach ($comments as $c) { $author = ($c->comment_author === 'Aiutoma') ? 'AI' : 'User'; $chat_transcript .= "{$author}: " . wp_strip_all_tags($c->comment_content) . "\n"; } if (!class_exists('\WordPress\AiClient\AiClient')) { return new \WP_REST_Response(['success' => false, 'message' => __('AI Client not available.', 'aiutoma')], 500); } $prompt = "Please provide a brief and concise summary (digest) of the following chat session between a User and an AI Assistant. Highlight the main topics discussed and any conclusions or resolutions.\n\n"; $prompt .= "CHAT TRANSCRIPT:\n" . $chat_transcript; try { $ai_query = \WordPress\AiClient\AiClient::prompt([ new \WordPress\AiClient\Messages\DTO\UserMessage([ new \WordPress\AiClient\Messages\DTO\MessagePart($prompt) ]) ]); $configured_model = get_option('aiutoma_chatbot_model', ''); if ($configured_model && strpos($configured_model, '|') !== false) { list($selectedProvider, $selectedModel) = explode('|', $configured_model); $ai_query->usingModelPreference([$selectedProvider, $selectedModel]); } $res = $ai_query->generateResult(); $summary = $res->toText(); // Format markdown to simple HTML for display if (class_exists('Parsedown')) { $parsedown = new \Parsedown(); $summary_html = $parsedown->text($summary); } else { $summary_html = nl2br(esc_html($summary)); } return new \WP_REST_Response(['success' => true, 'summary' => wp_kses_post($summary_html)], 200); } catch (\Exception $e) { return new \WP_REST_Response(['success' => false, 'message' => $e->getMessage()], 500); } } public function handle_chatbot_toggle_manual(\WP_REST_Request $request) { $session_id = sanitize_text_field($request->get_param('session_id')); $manual = (bool)$request->get_param('manual'); if (empty($session_id)) { return new \WP_REST_Response(['success' => false, 'message' => __('Missing session ID.', 'aiutoma')], 400); } if ($manual) { set_transient('aiutoma_chatbot_manual_' . $session_id, 1, 12 * HOUR_IN_SECONDS); } else { delete_transient('aiutoma_chatbot_manual_' . $session_id); } // Insert a system notice for the handover global $wpdb; $post_id = (int) $wpdb->get_var($wpdb->prepare(" SELECT c.comment_post_ID FROM {$wpdb->comments} c INNER JOIN {$wpdb->commentmeta} m ON c.comment_ID = m.comment_id WHERE m.meta_key = 'aiutoma_session_id' AND m.meta_value = %s LIMIT 1 ", $session_id)); $current_user = wp_get_current_user(); $operator_label = $current_user->exists() ? $current_user->display_name : __('Operator', 'aiutoma'); if ($manual) { /* translators: %s: operator name */ $notice_text = sprintf(__('A human operator (%s) has joined the chat.', 'aiutoma'), $operator_label); } else { $notice_text = __('The human operator has left the chat. The AI assistant is active again.', 'aiutoma'); } $comment_id = wp_insert_comment([ 'comment_post_ID' => $post_id, 'comment_author' => 'System', 'comment_author_email' => '', 'comment_author_url' => '', 'comment_parent' => 0, 'user_id' => 0, 'comment_content' => wp_slash($notice_text), 'comment_type' => 'aiutoma_chat', 'comment_approved' => 1 ]); if ($comment_id) { update_comment_meta($comment_id, 'aiutoma_session_id', $session_id); update_comment_meta($comment_id, 'aiutoma_chat_log', 1); } return new \WP_REST_Response(['success' => true], 200); } public function handle_chatbot_operator_send(\WP_REST_Request $request) { $session_id = sanitize_text_field($request->get_param('session_id')); $message = sanitize_text_field($request->get_param('message')); if (empty($session_id) || empty($message)) { return new \WP_REST_Response(['success' => false, 'message' => __('Missing parameters.', 'aiutoma')], 400); } $current_user = wp_get_current_user(); $author_name = 'Operator (' . $current_user->display_name . ')'; global $wpdb; $post_id = (int) $wpdb->get_var($wpdb->prepare(" SELECT c.comment_post_ID FROM {$wpdb->comments} c INNER JOIN {$wpdb->commentmeta} m ON c.comment_ID = m.comment_id WHERE m.meta_key = 'aiutoma_session_id' AND m.meta_value = %s LIMIT 1 ", $session_id)); $comment_id = wp_insert_comment([ 'comment_post_ID' => $post_id, 'comment_author' => wp_slash($author_name), 'comment_author_email' => $current_user->user_email, 'comment_author_url' => '', 'comment_parent' => 0, 'user_id' => $current_user->ID, 'comment_content' => wp_slash($message), 'comment_type' => 'aiutoma_chat', 'comment_approved' => 1 ]); if ($comment_id) { update_comment_meta($comment_id, 'aiutoma_session_id', $session_id); update_comment_meta($comment_id, 'aiutoma_chat_log', 1); return new \WP_REST_Response(['success' => true, 'comment_id' => $comment_id], 200); } return new \WP_REST_Response(['success' => false, 'message' => __('Failed to insert message.', 'aiutoma')], 500); } }