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 '
' . esc_html__('No messages found for this session.', 'aiutoma') . '
'; } else { 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 '' . 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 '' . 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 ''; 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 '' . 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 ''; } echo ''; echo ''; echo '
'; echo ''; echo '' . esc_html__('No chat sessions found.', 'aiutoma') . '
'; } else { 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); } }