You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/TicketTelegramNotifier.php

217 lines
8.3 KiB
PHP

<?php
namespace App\Services;
use App\Models\Configurations;
use App\Models\User;
use TelegramBot\Api\BotApi;
/** Administrator-only ticket alerts. No Telegram user login or ticket reply commands. */
final class TicketTelegramNotifier
{
private const KEY = TicketTelegramConfig::BINDING;
public const BINDING_TTL = 300;
public static function enabled(): bool
{
try {
return (bool) TicketTelegramConfig::publicValues()['enabled'];
} catch (\Throwable $exception) {
return false;
}
}
public static function configured(): bool
{
try {
return (bool) TicketTelegramConfig::publicValues()['configured'];
} catch (\Throwable $exception) {
return false;
}
}
public static function authorizeWebhook(string $header): bool
{
try {
$config = TicketTelegramConfig::runtime(true);
return hash_equals($config['webhook_secret'], $header);
} catch (\Throwable $exception) {
return false;
}
}
public static function bindingStatus(): array
{
$state = self::readState(Configurations::where('name', self::KEY)->first());
$adminId = (int) ($state['bound_admin_id'] ?? 0);
return ['bound' => !empty($state['chat_id']) && self::eligibleAdmin($adminId), 'admin_id' => $adminId];
}
public static function createBinding(int $adminId): array
{
TicketTelegramConfig::runtime(true);
if (!self::eligibleAdmin($adminId)) {
throw new \RuntimeException('只有超级管理员可以绑定工单通知');
}
$code = bin2hex(random_bytes(24));
self::ensureBindingRow();
(new Configurations())->getConnection()->transaction(function () use ($adminId, $code) {
$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);
$row->save();
});
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 false;
}
return (new Configurations())->getConnection()->transaction(function () use ($command) {
$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()
|| !hash_equals((string) ($state['pending_hash'] ?? ''), hash('sha256', $command['code']))
|| !self::eligibleAdmin($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']], JSON_THROW_ON_ERROR);
$row->save();
return true;
});
}
public static function notify(string $event, int $ticketId, string $title, string $content): bool
{
try {
$config = TicketTelegramConfig::runtime(true);
$state = self::readState(Configurations::where('name', self::KEY)->first());
$chatId = $state['chat_id'] ?? null;
if ((!is_string($chatId) && !is_int($chatId))
|| preg_match('/^[1-9][0-9]{0,18}$/D', (string) $chatId) !== 1
|| !self::eligibleAdmin((int) ($state['bound_admin_id'] ?? 0))) {
return false;
}
$label = in_array($event, ['created', '新工单'], true) ? '新工单' : '工单更新';
$plain = strip_tags($title . "\n" . $content);
$text = $label . ' #' . $ticketId . "\n" . mb_substr($plain, 0, 3000, 'UTF-8');
(new BotApi($config['bot_token']))->call('sendMessage', [
'chat_id' => (string) $chatId,
'text' => $text,
'disable_web_page_preview' => 'true',
], 10);
return true;
} catch (\Throwable $exception) {
// SDK error URLs may contain bot secrets. Never log their messages.
error_log('Administrator ticket Telegram delivery failed; ticket=' . $ticketId);
return false;
}
}
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 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 eligibleAdmin(int $adminId): bool
{
$allowed = array_map('intval', explode(',', (string) Config::get('super_admin', '')));
if ($adminId <= 0 || !in_array($adminId, $allowed, true)) {
return false;
}
$user = User::find($adminId);
return $user !== null && (bool) $user->is_admin && (int) $user->enable === 1;
}
}