boundDestination(); return [ 'bound' => $destination !== null, 'admin_id' => $destination?->administratorId, ]; } public static function createBinding(int $adminId): array { TicketTelegramConfig::runtime(true); $code = bin2hex(random_bytes(24)); $connection = (new Configurations())->getConnection(); $connection->transaction(function () use ( $connection, $adminId, $code ): void { $administrator = $connection->table('user') ->where('id', $adminId)->lockForUpdate() ->first(['id', 'is_admin', 'enable']); if ($administrator === null || (int) $administrator->is_admin !== 1 || (int) $administrator->enable !== 1 || !self::channel()->eligibleAdministrator($adminId)) { throw new \RuntimeException( '只有启用的超级管理员可以绑定工单通知' ); } self::ensureBindingRow(); $row = Configurations::where('name', self::KEY)->lockForUpdate()->firstOrFail(); $state = self::readState($row); $state['pending_hash'] = hash('sha256', $code); $state['pending_admin_id'] = $adminId; $state['pending_expires_at'] = time() + self::BINDING_TTL; $row->value = json_encode($state, JSON_THROW_ON_ERROR); if (!$row->save()) { throw new \RuntimeException('Administrator Telegram binding storage failed'); } }, 3); return ['code' => $code, 'expires_in' => self::BINDING_TTL]; } public static function unbind(): void { Configurations::where('name', self::KEY)->delete(); } /** Create the binding state without relying on mass-assignable model attributes. */ private static function ensureBindingRow(): void { if (Configurations::where('name', self::KEY)->first() !== null) { return; } $row = new Configurations(); $row->name = self::KEY; $row->value = '{}'; try { $row->save(); } catch (\Throwable $exception) { // Another request may have created the uniquely named binding row. if (Configurations::where('name', self::KEY)->first() === null) { throw $exception; } } } public static function bindingCommand(array $update): ?array { $message = $update['message'] ?? null; if (!is_array($message) || ($message['chat']['type'] ?? '') !== 'private' || !empty($message['from']['is_bot']) || !empty($message['forward_origin']) || !empty($message['forward_from']) || !empty($message['forward_date'])) { return null; } $chatId = (string) ($message['chat']['id'] ?? ''); $senderId = (string) ($message['from']['id'] ?? ''); if (!preg_match('/^[1-9][0-9]{0,18}$/D', $chatId) || $chatId !== $senderId || !preg_match('/^\/start\s+([a-f0-9]{48})$/D', (string) ($message['text'] ?? ''), $matches)) { return null; } return ['chat_id' => $chatId, 'code' => $matches[1]]; } public static function handleUpdate(array $update): bool { $command = self::bindingCommand($update); if ($command === null) { return self::handleTicketReply($update); } $snapshot = self::readState( Configurations::where('name', self::KEY)->first() ); $expectedAdminId = (int) ($snapshot['pending_admin_id'] ?? 0); if ($expectedAdminId <= 0) { return false; } $connection = (new Configurations())->getConnection(); $bound = $connection->transaction(function () use ( $connection, $command, $expectedAdminId ): bool { $administrator = $connection->table('user') ->where('id', $expectedAdminId)->lockForUpdate() ->first(['id', 'is_admin', 'enable']); $row = Configurations::where('name', self::KEY)->lockForUpdate()->first(); $state = self::readState($row); $adminId = (int) ($state['pending_admin_id'] ?? 0); if ($row === null || (int) ($state['pending_expires_at'] ?? 0) <= time() || $adminId !== $expectedAdminId || !hash_equals((string) ($state['pending_hash'] ?? ''), hash('sha256', $command['code'])) || $administrator === null || (int) $administrator->is_admin !== 1 || (int) $administrator->enable !== 1 || !self::channel()->eligibleAdministrator($adminId)) { return false; } // One-time token consumed atomically; replay cannot change the recipient. $row->value = json_encode([ 'bound_admin_id' => $adminId, 'chat_id' => $command['chat_id'], 'binding_generation' => bin2hex(random_bytes(16)), ], JSON_THROW_ON_ERROR); if (!$row->save()) { throw new \RuntimeException('Administrator Telegram binding storage failed'); } return true; }, 3); if (!$bound) { return false; } // The binding is already committed before the remote acknowledgement. // A transient Telegram failure must not revive the one-time code or // cause Telegram to replay a successful binding transaction. self::sendBindingConfirmation($command['chat_id']); return true; } private static function handleTicketReply(array $update): bool { $command = self::ticketReplyCommand($update); if ($command === null) { return false; } $destination = self::channel()->currentDestination(); if ($destination === null || $destination->chatId !== $command['chat_id']) { return false; } $adminId = $destination->administratorId; $delivery = TicketTelegramDelivery::where( 'binding_generation', $destination->bindingGeneration )->where('chat_id', $command['chat_id']) ->where('telegram_message_id', $command['reply_to_message_id']) ->where('state', 'sent')->first(); try { $abuseDelivery = self::abuseReplyDelivery( $destination, $command['reply_to_message_id'] ); } catch (\Throwable $exception) { error_log('Administrator Telegram abuse reply mapping unavailable'); self::sendReplyAcknowledgement( $command['chat_id'], $command['message_id'], '暂时无法核对这条通知,请勿通过 Telegram 回复,请在管理后台处理。' ); return true; } if ($delivery !== null && $abuseDelivery !== null) { error_log('Administrator Telegram reply target mapping conflict'); self::sendReplyAcknowledgement( $command['chat_id'], $command['message_id'], '这条通知的回复映射存在冲突,请在管理后台处理。' ); return true; } if ($abuseDelivery !== null) { self::sendReplyAcknowledgement( $command['chat_id'], $command['message_id'], '网络滥用告警为只读通知,不能通过 Telegram 回复,请在管理后台处理。' ); return true; } if ($delivery === null || (int) $delivery->bound_admin_id !== $adminId) { self::sendReplyAcknowledgement( $command['chat_id'], $command['message_id'], '无法识别这条工单通知,请在管理后台处理。' ); return true; } try { $result = (new TicketThreadService())->reply(new ReplyTicketCommand( (int) $delivery->ticket_id, $adminId, $command['text'], 1, null, null, true, 'telegram.' . $destination->bindingGeneration . '.update.' . $command['update_id'], 1 )); } catch (TicketReplyStateConflict $exception) { self::sendReplyAcknowledgement( $command['chat_id'], $command['message_id'], $exception->getMessage() ); return true; } catch (TicketIdempotencyConflict $exception) { self::sendReplyAcknowledgement( $command['chat_id'], $command['message_id'], '这条 Telegram 更新已用于其他回复,请在管理后台核对。' ); return true; } catch (\InvalidArgumentException $exception) { self::sendReplyAcknowledgement( $command['chat_id'], $command['message_id'], $exception->getMessage() ); return true; } if ($result === null) { self::sendReplyAcknowledgement( $command['chat_id'], $command['message_id'], '工单已不存在,请在管理后台核对。' ); return true; } if (!$result->wasCreated) { return true; } (new TicketNotificationDispatcher())->dispatch(TicketEvent::adminReply($result)); self::sendReplyAcknowledgement( $command['chat_id'], $command['message_id'], '✅ 已回复工单 #' . (int) $result->root->id . "\n用户已可在工单页面查看。" ); return true; } private static function abuseReplyDelivery( AdministratorTelegramDestination $destination, int $replyToMessageId ): ?object { $connection = (new Configurations())->getConnection(); if (!$connection->getSchemaBuilder()->hasTable( 'cloud_network_alert_deliveries' )) { return null; } return $connection->table('cloud_network_alert_deliveries') ->where('binding_generation', $destination->bindingGeneration) ->where('bound_admin_id', $destination->administratorId) ->where('chat_id', $destination->chatId) ->where('telegram_message_id', $replyToMessageId) ->whereIn('state', ['sent', 'unknown']) ->whereNull('destination_redacted_at')->first(); } private static function ticketReplyCommand(array $update): ?array { $message = $update['message'] ?? null; $updateId = self::positiveIntegerString($update['update_id'] ?? null); if (!is_array($message) || $updateId === null || ($message['chat']['type'] ?? '') !== 'private' || !empty($message['from']['is_bot']) || !empty($message['via_bot']) || !empty($message['sender_chat']) || !empty($message['forward_origin']) || !empty($message['forward_from']) || !empty($message['forward_date'])) { return null; } $chatId = (string) ($message['chat']['id'] ?? ''); $senderId = (string) ($message['from']['id'] ?? ''); $messageId = self::positiveIntegerString($message['message_id'] ?? null); $replyMessageId = self::positiveIntegerString( $message['reply_to_message']['message_id'] ?? null ); $text = $message['text'] ?? null; if (preg_match('/^[1-9][0-9]{0,18}$/D', $chatId) !== 1 || $chatId !== $senderId || $messageId === null || $replyMessageId === null || !is_string($text) || trim($text) === '' || str_starts_with(trim($text), '/')) { return null; } foreach (['animation', 'audio', 'document', 'photo', 'sticker', 'video', 'video_note', 'voice'] as $media) { if (array_key_exists($media, $message)) { return null; } } return [ 'update_id' => $updateId, 'chat_id' => $chatId, 'message_id' => (int) $messageId, 'reply_to_message_id' => (int) $replyMessageId, 'text' => trim($text), ]; } private static function positiveIntegerString(mixed $value): ?string { if ((!is_int($value) && !is_string($value)) || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $value) !== 1) { return null; } $value = (string) $value; $maximum = (string) PHP_INT_MAX; if (strlen($value) > strlen($maximum) || (strlen($value) === strlen($maximum) && strcmp($value, $maximum) > 0)) { return null; } return $value; } private static function sendReplyAcknowledgement( string $chatId, int $replyToMessageId, string $text ): void { try { $destination = self::channel()->currentDestination(); if ($destination === null || $destination->chatId !== $chatId) { return; } self::channel()->send($destination, $text, [ 'reply_to_message_id' => $replyToMessageId, 'allow_sending_without_reply' => 'true', 'disable_web_page_preview' => 'true', ]); } catch (\Throwable $exception) { // The ticket transaction has already committed. Never request a // Telegram replay merely because this best-effort receipt failed. error_log('Administrator Telegram ticket reply confirmation failed'); } } public static function notify(TicketEvent $event): TicketTelegramNotificationResult { $ticketId = (int) $event->result->root->id; try { $public = TicketTelegramConfig::publicValues(); if (!$public['enabled'] || !$public['configured']) { return TicketTelegramNotificationResult::Skipped; } } catch (\Throwable $exception) { error_log('Administrator ticket Telegram configuration check failed'); return TicketTelegramNotificationResult::Failed; } try { $destination = self::channel()->currentDestination(); if ($destination === null) { return TicketTelegramNotificationResult::Skipped; } $text = self::notificationText($event); [$delivery, $ownsDispatch] = self::reserveDelivery( $event, $destination, $text ); if (!$ownsDispatch) { return (string) $delivery->state === 'sent' ? TicketTelegramNotificationResult::Sent : TicketTelegramNotificationResult::Failed; } try { $messageId = self::channel()->send($destination, $text, [ 'disable_web_page_preview' => 'true', ]); $updated = TicketTelegramDelivery::where('id', (int) $delivery->id) ->where('state', 'dispatching')->update([ 'telegram_message_id' => $messageId, 'state' => 'sent', 'sent_at' => time(), 'updated_at' => time(), ]); if ((int) $updated !== 1) { throw new \RuntimeException('Telegram delivery finalization failed'); } return TicketTelegramNotificationResult::Sent; } catch (AdministratorTelegramRateBacklog $exception) { self::deferBackloggedDelivery((int) $delivery->id); return TicketTelegramNotificationResult::Failed; } catch (AdministratorTelegramPreflightException|AdministratorTelegramLocalUnavailable $exception) { self::releasePreflightDelivery((int) $delivery->id); return TicketTelegramNotificationResult::Failed; } catch (\Throwable $exception) { self::markDeliveryUnknown((int) $delivery->id); throw $exception; } } catch (\Throwable $exception) { // SDK error URLs may contain bot secrets. Never log their messages. error_log('Administrator ticket Telegram delivery failed; ticket=' . $ticketId); return TicketTelegramNotificationResult::Failed; } } /** * @return array{TicketTelegramDelivery, bool} */ private static function reserveDelivery( TicketEvent $event, AdministratorTelegramDestination $destination, string $text ): array { $generation = $destination->bindingGeneration; $messageId = (int) $event->result->message->id; $kind = (string) $event->kind; try { $connection = (new Configurations())->getConnection(); return $connection->transaction(function () use ( $connection, $destination, $generation, $messageId, $kind, $event, $text ): array { $ownerId = (int) $event->result->root->userid; $userIds = array_values(array_unique([ $ownerId, $destination->administratorId, ])); sort($userIds, SORT_NUMERIC); $lockedUsers = []; foreach ($userIds as $userId) { $locked = $connection->table('user') ->where('id', $userId)->lockForUpdate() ->first(['id', 'is_admin', 'enable']); if ($locked !== null) { $lockedUsers[(int) $locked->id] = $locked; } } $administrator = $lockedUsers[ $destination->administratorId ] ?? null; if (!isset($lockedUsers[$ownerId])) { throw new \RuntimeException( 'Telegram ticket owner no longer exists' ); } if ($administrator === null || (int) $administrator->is_admin !== 1 || (int) $administrator->enable !== 1 || !self::channel()->eligibleAdministrator( $destination->administratorId )) { throw new AdministratorTelegramPreflightException( AdministratorTelegramPreflightException::DESTINATION_CHANGED, 'Administrator Telegram destination is ineligible' ); } $existing = self::deliveryForEvent( $generation, $messageId, $kind ); if ($existing !== null) { self::settleStaleDispatching($existing); return [$existing, false]; } $delivery = new TicketTelegramDelivery(); $delivery->binding_generation = $generation; $delivery->bound_admin_id = $destination->administratorId; $delivery->chat_id = $destination->chatId; $delivery->ticket_id = (int) $event->result->root->id; $delivery->ticket_message_id = $messageId; $delivery->event_kind = $kind; $delivery->telegram_message_id = null; $delivery->state = 'dispatching'; $delivery->content_hash = hash('sha256', $text); $delivery->created_at = time(); $delivery->sent_at = null; $delivery->updated_at = time(); if (!$delivery->save()) { throw new \RuntimeException( 'Telegram delivery reservation failed' ); } return [$delivery, true]; }, 3); } catch (\Throwable $exception) { // The unique event key elects one sender when dispatchers race. $existing = self::deliveryForEvent($generation, $messageId, $kind); if ($existing !== null) { return [$existing, false]; } throw $exception; } } private static function settleStaleDispatching(TicketTelegramDelivery $delivery): void { if ((string) $delivery->state !== 'dispatching' || (int) $delivery->updated_at > time() - 30) { return; } $updated = TicketTelegramDelivery::where('id', (int) $delivery->id) ->where('state', 'dispatching')->update([ 'telegram_message_id' => null, 'state' => 'unknown', 'updated_at' => time(), ]); if ((int) $updated === 1) { $delivery->telegram_message_id = null; $delivery->state = 'unknown'; $delivery->updated_at = time(); } } private static function deliveryForEvent( string $generation, int $messageId, string $kind ): ?TicketTelegramDelivery { return TicketTelegramDelivery::where('binding_generation', $generation) ->where('ticket_message_id', $messageId) ->where('event_kind', $kind)->first(); } private static function markDeliveryUnknown(int $deliveryId): void { try { TicketTelegramDelivery::where('id', $deliveryId) ->where('state', 'dispatching')->update([ 'telegram_message_id' => null, 'state' => 'unknown', 'updated_at' => time(), ]); } catch (\Throwable $exception) { error_log('Administrator ticket Telegram delivery reconciliation failed'); } } private static function releasePreflightDelivery(int $deliveryId): void { try { TicketTelegramDelivery::where('id', $deliveryId) ->where('state', 'dispatching')->delete(); } catch (\Throwable $exception) { // The remote request is known not to have started. A retained // dispatching row is intentionally fenced and will age to unknown. error_log('Administrator ticket Telegram preflight release failed'); } } private static function deferBackloggedDelivery(int $deliveryId): void { try { $updated = TicketTelegramDelivery::where('id', $deliveryId) ->where('state', 'dispatching')->update([ 'state' => 'failed', 'updated_at' => time(), ]); if ((int) $updated !== 1) { throw new \RuntimeException( 'Telegram delivery backlog settlement failed' ); } } catch (\Throwable $exception) { // The remote call is known not to have started. Retain the // dispatch fence if that known-no-send settlement cannot persist. error_log('Administrator ticket Telegram backlog settlement failed'); } } private static function notificationText(TicketEvent $event): string { $root = $event->result->root; $message = $event->result->message; $ticketId = (int) $root->id; $ownerId = (int) $root->userid; $ownerName = ''; try { $ownerName = self::plainText((string) (User::find($ownerId)?->user_name ?? ''), 80); } catch (\Throwable $exception) { // A missing user projection must not suppress the ticket alert. } $owner = $ownerName === '' ? 'UID ' . $ownerId : $ownerName . '(UID ' . $ownerId . ')'; $instanceName = ''; $instanceId = (int) ($root->instance_id ?? 0); if ($instanceId > 0) { try { $instance = CloudInstance::where('id', $instanceId) ->where('user_id', $ownerId)->first(); $instanceName = self::plainText((string) ($instance?->name ?? ''), 100); } catch (\Throwable $exception) { // Ticket notifications remain available if the instance projection is unavailable. } } $label = $event->kind === 'created' ? '🆕 新工单' : '💬 用户回复'; $type = [ 'pre_sales' => '售前', 'after_sales' => '售后', 'technical' => '技术支持', 'finance' => '财务', ][(string) ($root->ticket_type ?? '')] ?? '技术支持'; $priority = [ 'high' => '高', 'medium' => '中', 'low' => '低', ][(string) ($root->priority ?? '')] ?? '中'; $status = (int) ($root->status ?? 0) === 1 ? '等待管理员' : '已关闭'; $timestamp = (int) ($message->datetime ?? time()); $adminUrl = rtrim((string) Config::get('baseUrl'), '/') . '/admin/ticket/' . $ticketId . '/view'; $title = self::plainText((string) $root->title, 180); $content = self::plainText((string) $message->content, 2500, true); $attachments = count($event->result->attachments); $lines = [ $label . ' #' . $ticketId, '', '主题:' . ($title === '' ? '未命名工单' : $title), '用户:' . $owner, '分类:' . $type, '优先级:' . $priority, '状态:' . $status, ]; if ($instanceName !== '') { $lines[] = '关联实例:' . $instanceName; } $lines[] = '提交时间:' . gmdate('Y-m-d H:i:s', $timestamp) . ' UTC'; $lines[] = ''; $lines[] = '用户内容:'; $lines[] = $content === '' ? '(无文本内容)' : $content; if ($attachments > 0) { $lines[] = ''; $lines[] = '附件:' . $attachments . ' 个,请在后台查看'; } $lines[] = '后台地址:' . $adminUrl; $lines[] = ''; $lines[] = (int) ($root->status ?? 0) === 1 ? '↩️ 直接回复本消息即可回复用户' : '工单已关闭,请在管理后台查看'; return mb_substr(implode("\n", $lines), 0, 4096, 'UTF-8'); } private static function plainText(string $value, int $limit, bool $multiline = false): string { $value = html_entity_decode(strip_tags($value), ENT_QUOTES | ENT_HTML5, 'UTF-8'); $value = str_replace(["\r\n", "\r"], "\n", $value); $value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $value) ?? ''; if ($multiline) { $value = preg_replace('/[ \t]+/u', ' ', $value) ?? ''; $value = preg_replace('/\n{3,}/u', "\n\n", $value) ?? ''; } else { $value = preg_replace('/\s+/u', ' ', $value) ?? ''; } return mb_substr(trim($value), 0, $limit, 'UTF-8'); } public static function registerWebhook(): bool { try { $config = TicketTelegramConfig::runtime(true); } catch (\Throwable $exception) { throw new \RuntimeException(self::safeConfigurationMessage($exception)); } try { $result = (new BotApi($config['bot_token']))->call('setWebhook', [ 'url' => $config['webhook_base_url'] . '/telegram_callback', 'secret_token' => $config['webhook_secret'], 'allowed_updates' => '["message"]', ], 10); if ($result !== true) { throw new \RuntimeException('Webhook registration rejected'); } return true; } catch (\Throwable $exception) { throw new \RuntimeException('Telegram webhook 注册失败,请检查 HTTPS、出站网络和 bot 配置'); } } private static function readState($row): array { $state = $row === null ? [] : json_decode((string) $row->value, true); return is_array($state) ? $state : []; } private static function sendBindingConfirmation(string $chatId): void { try { $destination = self::channel()->currentDestination(); if ($destination === null || $destination->chatId !== $chatId) { return; } self::channel()->send( $destination, "绑定成功\n此 Telegram 账号已绑定为管理员工单提醒接收账号。", [ 'disable_web_page_preview' => 'true', ] ); } catch (\Throwable $exception) { // SDK error URLs may contain bot secrets. Never log their messages. error_log('Administrator Telegram binding confirmation failed'); } } private static function safeConfigurationMessage(\Throwable $exception): string { $message = $exception->getMessage(); foreach ([ 'Telegram 工单提醒', 'Telegram 凭据', 'Telegram 机器人 Token', 'Telegram Webhook 密钥', 'Telegram 通信域名', 'PHP sodium ', '请在工单系统的 Telegram ', ] as $safePrefix) { if (str_starts_with($message, $safePrefix)) { return $message; } } return 'Telegram 配置读取失败,请检查数据库与服务器日志'; } private static function channel(): AdministratorTelegramChannel { return new AdministratorTelegramChannel(); } }