get_error_message(); } else { $body = wp_remote_retrieve_body($response); $json = json_decode($body, true); if (isset($json['ok']) && $json['ok'] === true) { $status = 'success'; $message = __('Webhook registered successfully.', 'aiutoma'); } else { $message = isset($json['description']) ? $json['description'] : __('Unknown Telegram API error.', 'aiutoma'); } } } set_transient('aiutoma_im_admin_notice', ['status' => $status, 'message' => $message], 45); wp_safe_redirect(admin_url('admin.php?page=aiutoma-im')); exit; } public function clear_im_history_action() { if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have permission to perform this action.', 'aiutoma')); } check_admin_referer('aiutoma_clear_im_history'); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified above via check_admin_referer. $platform_to_clear = isset($_GET['platform']) ? sanitize_key(wp_unslash($_GET['platform'])) : ''; $conv_id = ''; if ($platform_to_clear === 'whatsapp') { $t_num = get_option('aiutoma_wa_target_number'); if (!empty($t_num)) { $conv_id = 'whatsapp_' . preg_replace('/[^0-9]/', '', $t_num); } } elseif ($platform_to_clear === 'telegram') { $c_id = get_option('aiutoma_tg_allowed_chat_id'); if (!empty($c_id)) { $conv_id = 'telegram_' . $c_id; } } if (!empty($conv_id)) { delete_transient($conv_id); $file_path = \Aiutoma\Modules\Ai\Ai::get_storage_dir() . '/logs/sessions/' . sanitize_file_name($conv_id) . '.json'; if (file_exists($file_path)) { wp_delete_file($file_path); } /* translators: %s: Platform name */ $notice_msg = sprintf(__('AI Memory wiped for %s. You can now start fresh!', 'aiutoma'), ucfirst($platform_to_clear)); set_transient('aiutoma_im_admin_notice', ['status' => 'success', 'message' => $notice_msg], 45); } wp_safe_redirect(admin_url('admin.php?page=aiutoma-im')); exit; } public function aiutoma_im_page_html() { if (!current_user_can('manage_options')) return; // WhatsApp Saving if (isset($_POST['aiutoma_wa_settings_nonce'])) { check_admin_referer('aiutoma_wa_settings_action', 'aiutoma_wa_settings_nonce'); if (isset($_POST['aiutoma_wa_phone_number_id'])) { update_option('aiutoma_wa_phone_number_id', sanitize_text_field(wp_unslash($_POST['aiutoma_wa_phone_number_id']))); } if (isset($_POST['aiutoma_wa_access_token'])) { update_option('aiutoma_wa_access_token', sanitize_text_field(wp_unslash($_POST['aiutoma_wa_access_token']))); } if (isset($_POST['aiutoma_wa_target_number'])) { update_option('aiutoma_wa_target_number', sanitize_text_field(wp_unslash($_POST['aiutoma_wa_target_number']))); } if (isset($_POST['aiutoma_wa_app_secret'])) { update_option('aiutoma_wa_app_secret', sanitize_text_field(wp_unslash($_POST['aiutoma_wa_app_secret']))); } echo '
' . esc_html__('WhatsApp Settings saved.', 'aiutoma') . '
' . esc_html__('Error: Invalid Telegram Bot Token format. It must look like: 123456789:ABCdefGHIjkl...', 'aiutoma') . '
' . esc_html__('Telegram API Error: Token format is correct, but Telegram rejected it as invalid.', 'aiutoma') . '
' . esc_html__('Telegram Settings saved.', 'aiutoma') . '
' . esc_html__('Global Settings saved.', 'aiutoma') . '
' . esc_html($notice_msg) . '
whatsapp_business_messaging and whatsapp_business_management. Paste token above.@
/newbot and follow instructions to choose a name and username.123456789:ABCdef...) into the field above.');
$display_text = trim(preg_replace("/[\r\n]{3,}/", "\n\n", $display_text));
$this->send_telegram_message($telegram_chat_id, $display_text, $media_url);
}
// Save Session for Playground History
$upload_dir = wp_upload_dir();
$log_dir = \Aiutoma\Modules\Ai\Ai::get_storage_dir() . '/logs/sessions';
if (!is_dir($log_dir)) wp_mkdir_p($log_dir);
$session_id = sanitize_file_name($conversation_id);
$file_path = $log_dir . '/' . $session_id . '.json';
$sess_data = [];
if (file_exists($file_path)) {
$sess_data = json_decode(file_get_contents($file_path), true);
}
if (empty($sess_data)) {
$sess_data = [
'is_full_state' => true,
'id' => $session_id,
'user' => 'IM User (' . ucfirst($platform) . ')',
'first_prompt' => $text,
'html' => '',
'conversation_id' => $conversation_id,
'session_prompts' => []
];
}
$sess_data['date'] = current_time('mysql');
$sess_data['session_prompts'][] = $text;
$transient_data = get_transient($conversation_id);
if ($transient_data) {
$json_data = json_decode($transient_data, true);
if (is_array($json_data)) {
$messages = [];
foreach ($json_data as $msg_array) {
if (is_array($msg_array) && isset($msg_array['role'])) {
$messages[] = \WordPress\AiClient\Messages\DTO\Message::fromArray($msg_array);
}
}
}
if (isset($messages) && is_array($messages)) {
$html = '';
foreach ($messages as $msg) {
$role_obj = method_exists($msg, 'getRole') ? $msg->getRole() : '';
$role = (is_object($role_obj) && property_exists($role_obj, 'value')) ? $role_obj->value : (string) $role_obj;
$content_html = '';
$raw_text = '';
if (method_exists($msg, 'getParts')) {
$parts = $msg->getParts();
foreach ($parts as $part) {
if (method_exists($part, 'getText') && (string)$part->getText() !== '') {
if ($role === 'model') {
$raw_text .= (string) $part->getText() . "\n";
} else {
$content_html .= nl2br(esc_html((string) $part->getText())) . "
";
}
} elseif (method_exists($part, 'getFunctionCall') && $part->getFunctionCall()) {
$func = $part->getFunctionCall();
$name = method_exists($func, 'getName') ? $func->getName() : '';
$args = method_exists($func, 'getArgs') ? wp_json_encode($func->getArgs(), JSON_PRETTY_PRINT) : '';
$content_html .= "🛠️ [Tool Execution]: " . esc_html($name) . "" . esc_html($args) . "
";
} elseif (method_exists($part, 'getFunctionResponse') && $part->getFunctionResponse()) {
$resp = $part->getFunctionResponse();
$name = method_exists($resp, 'getName') ? $resp->getName() : '';
$res = method_exists($resp, 'getResponse') ? wp_json_encode($resp->getResponse(), JSON_PRETTY_PRINT) : '';
$content_html .= "✅ [Tool Response]: " . esc_html($name) . "" . esc_html($res) . "
";
}
}
}
if ($role === 'model' && !empty($raw_text)) {
if (class_exists('\League\CommonMark\CommonMarkConverter')) {
if (class_exists('\League\CommonMark\GithubFlavoredMarkdownConverter')) {
$converter = new \League\CommonMark\GithubFlavoredMarkdownConverter(['html_input' => 'allow', 'allow_unsafe_links' => false]);
} else {
$converter = new \League\CommonMark\CommonMarkConverter(['html_input' => 'allow', 'allow_unsafe_links' => false]);
}
$content_html = wp_kses_post($converter->convert($raw_text)->getContent()) . $content_html;
} else {
$content_html = nl2br(esc_html($raw_text)) . $content_html;
}
}
if ($role === 'user') {
$html .= 'You (' . ucfirst($platform) . '):
' . $content_html . '';
} elseif ($role === 'model') {
$html .= 'AI:
' . $content_html . '';
} elseif ($role === 'tool' || $role === 'function') {
$html .= 'Tool Response:
' . $content_html . '';
}
}
if (is_wp_error($response)) {
$html .= 'Error:
' . esc_html($response->get_error_message()) . '';
} else if ($response instanceof \WP_REST_Response) {
$data = $response->get_data();
if (isset($data['success']) && $data['success'] === false) {
$html .= 'Error:
' . esc_html($data['message'] ?? 'Unknown API Error') . '';
}
}
$sess_data['html'] = $html;
$sess_data['raw_messages'] = base64_encode(wp_json_encode($messages));
}
}
$sess_data['date'] = current_time('mysql');
file_put_contents($file_path, json_encode($sess_data));
}
}
public function send_im_admin_notification($message_text, $media_url = '', $buttons = []) {
$wa_sent = false;
$tg_sent = false;
$target_number = get_option('aiutoma_wa_target_number');
if (!empty($target_number)) {
$this->send_whatsapp_message($message_text, $media_url, $buttons);
$wa_sent = true;
}
$tg_chat_id = get_option('aiutoma_tg_allowed_chat_id');
if (!empty($tg_chat_id)) {
$this->send_telegram_message($tg_chat_id, $message_text, $media_url, $buttons);
$tg_sent = true;
}
return $wa_sent || $tg_sent;
}
private function send_whatsapp_message($message_text, $media_url = '', $buttons = []) {
$phone_number_id = get_option('aiutoma_wa_phone_number_id');
$access_token = get_option('aiutoma_wa_access_token');
$target_number = get_option('aiutoma_wa_target_number');
if (empty($phone_number_id) || empty($access_token) || empty($target_number)) {
return false;
}
if (!empty($buttons)) {
foreach ($buttons as $btn) {
if (!empty($btn['url']) && !empty($btn['text'])) {
$message_text .= "\n\n" . $btn['text'] . ": " . $btn['url'];
}
}
}
// Convert HTML to WhatsApp formatting
$message_text = str_replace(['
', '
', '
', ''], "\n", $message_text);
$message_text = str_ireplace(['', '', '', ''], '*', $message_text);
$message_text = preg_replace('/]*href=["\'](.*?)["\'][^>]*>(.*?)<\/a>/i', '$2: $1', $message_text);
$message_text = wp_strip_all_tags($message_text);
$message_text = html_entity_decode($message_text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$clean_target = preg_replace('/[^0-9]/', '', $target_number);
$url = "https://graph.facebook.com/v18.0/{$phone_number_id}/messages";
$body = [
'messaging_product' => 'whatsapp',
'to' => $clean_target,
];
if (!empty($media_url)) {
$ext = strtolower(pathinfo(wp_parse_url($media_url, PHP_URL_PATH), PATHINFO_EXTENSION));
$is_image = in_array($ext, ['jpg', 'jpeg', 'png', 'webp']);
if ($is_image) {
$body['type'] = 'image';
$body['image'] = [
'link' => $media_url
];
if (!empty($message_text)) {
$body['image']['caption'] = mb_strimwidth($message_text, 0, 1024, '...');
}
} else {
$body['type'] = 'document';
$body['document'] = [
'link' => $media_url
];
if (!empty($message_text)) {
$body['document']['caption'] = mb_strimwidth($message_text, 0, 1024, '...');
}
}
} else {
$body['type'] = 'text';
$body['text'] = [
'body' => $message_text
];
}
$args = [
'body' => wp_json_encode($body),
'headers' => [
'Authorization' => 'Bearer ' . $access_token,
'Content-Type' => 'application/json',
],
'timeout' => 15,
'data_format' => 'body',
];
return wp_remote_post($url, $args);
}
private function send_telegram_message($chat_id, $message_text, $media_url = '', $buttons = []) {
$bot_token = get_option('aiutoma_tg_bot_token');
if (empty($bot_token) || empty($chat_id)) return false;
$api_url = "https://api.telegram.org/bot{$bot_token}/";
$reply_markup = '';
if (!empty($buttons)) {
$inline_keyboard = [];
foreach ($buttons as $btn) {
if (!empty($btn['url']) && !empty($btn['text'])) {
$parsed_host = wp_parse_url($btn['url'], PHP_URL_HOST);
if (in_array($parsed_host, ['localhost', '127.0.0.1'])) {
// Telegram blocks localhost in buttons. Append to text instead.
$message_text .= "\n\n" . $btn['text'] . ": " . $btn['url'];
} else {
$inline_keyboard[] = [['text' => $btn['text'], 'url' => $btn['url']]];
}
}
}
if (!empty($inline_keyboard)) {
$reply_markup = json_encode(['inline_keyboard' => $inline_keyboard]);
}
}
if (!empty($media_url)) {
$ext = strtolower(pathinfo(wp_parse_url($media_url, PHP_URL_PATH), PATHINFO_EXTENSION));
$is_image = in_array($ext, ['jpg', 'jpeg', 'png', 'webp']);
$endpoint = $is_image ? 'sendPhoto' : 'sendDocument';
$media_field = $is_image ? 'photo' : 'document';
$body = [
'chat_id' => $chat_id,
$media_field => $media_url,
'caption' => mb_strimwidth($message_text, 0, 1024, '...'),
'parse_mode' => 'HTML'
];
} else {
$endpoint = 'sendMessage';
$body = [
'chat_id' => $chat_id,
'text' => $message_text,
'parse_mode' => 'HTML'
];
}
if ($reply_markup) {
$body['reply_markup'] = $reply_markup;
}
$args = [
'body' => $body,
'timeout' => 15
];
$response = wp_remote_post($api_url . $endpoint, $args);
if (defined('WP_DEBUG') && WP_DEBUG && (is_wp_error($response) || wp_remote_retrieve_response_code($response) != 200)) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r
error_log('Telegram API Error: ' . print_r($response, true));
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r
error_log('Telegram Payload: ' . print_r($body, true));
}
return $response;
}
}