home($request, $response, $args); } public function home($request, $response, $args) { return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302); } public function instances($request, $response, $args) { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $page = $this->pageNumber($request->getQueryParams()['page'] ?? '1'); $payload = CloudInstancePageService::forActor($actor, $page, 20); $payload['user'] = $this->userBootstrap($user, $actor); return $this->render($response, 'instances', '实例管理', '', '', [ 'cloud_vm_rows' => array_map( fn (array $vm): array => $this->vmListRow($vm), $payload['vms'] ), 'cloud_vm_stats' => $payload['stats'], 'cloud_vm_pagination' => $payload['pagination'], 'cloud_vm_scope_label' => ($actor['is_admin'] ?? false) ? '全部可见实例' : '我的实例', 'cloud_vm_bootstrap_json' => $this->safeJson($payload), ]); } public function detail($request, $response, $args) { $vmId = isset($args['id']) ? (string) $args['id'] : ''; if (preg_match('/^[1-9][0-9]*$/D', $vmId) !== 1) { return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302); } $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); try { $vm = CloudInstancePageService::detailForActor($actor, $vmId); } catch (CloudError $error) { if ($error->httpStatus === 404) { return $response->withHeader('Location', '/user/cloud/instances') ->withStatus(302); } throw $error; } $keys = $this->sshKeyOptions((int) $actor['user_id']); $payload = [ 'vm' => $vm, 'user' => $this->userBootstrap($user, $actor), 'ssh_keys' => $keys, ]; return $this->render($response, 'detail', '实例详情', $vmId, '', [ 'cloud_vm_view' => $this->vmDetailView($vm), 'cloud_detail_ssh_keys' => $keys, 'cloud_detail_has_ssh_keys' => $keys !== [], 'cloud_detail_no_ssh_keys' => $keys === [], 'cloud_vm_bootstrap_json' => $this->safeJson($payload), ]); } public function deploy($request, $response, $args) { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $saleCatalog = CloudDeploymentPageService::saleCatalog(); $regions = $saleCatalog['regions']; $lines = $saleCatalog['lines']; $offers = $saleCatalog['offers']; $linesEnabled = $saleCatalog['lines_enabled'] === true; $catalog = CloudDeploymentPageService::templateCatalogForPage($actor); $templates = is_array($catalog['templates'] ?? null) ? $catalog['templates'] : []; $catalogUnavailable = ($catalog['catalog_unavailable'] ?? false) === true; $keys = $this->sshKeyOptions((int) $actor['user_id']); $defaultRegionId = $regions === [] ? 0 : (int) $regions[0]['id']; $defaultLineId = 0; $firstLineId = 0; foreach ($lines as $line) { if ((int) $line['region_id'] !== $defaultRegionId) { continue; } $firstLineId = $firstLineId ?: (int) $line['id']; if ($line['is_default'] === true) { $defaultLineId = (int) $line['id']; break; } } $defaultLineId = $defaultLineId ?: $firstLineId; $payload = [ 'user' => $this->userBootstrap($user, $actor), 'regions' => $regions, 'lines' => $lines, 'offers' => $offers, 'lines_enabled' => $linesEnabled, 'templates' => $templates, 'ssh_keys' => $keys, 'default_region_id' => $defaultRegionId, 'default_line_id' => $defaultLineId, 'catalog_unavailable' => $catalogUnavailable, ]; return $this->render($response, 'deploy', '部署实例', '', '', [ 'cloud_deploy_regions' => $regions, 'cloud_deploy_lines' => $lines, 'cloud_deploy_offers' => $offers, 'cloud_deploy_lines_enabled' => $linesEnabled, 'cloud_deploy_template_groups' => CloudDeploymentPageService::templateGroups($templates), 'cloud_deploy_ssh_keys' => $keys, 'cloud_deploy_default_region_id' => $defaultRegionId, 'cloud_deploy_default_line_id' => $defaultLineId, 'cloud_deploy_catalog_unavailable' => $catalogUnavailable, 'cloud_deploy_bootstrap_json' => $this->safeJson($payload), ]); } public function isoImages($request, $response, $args) { if (!CloudUserIsoFeature::enabled()) { return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302); } return $this->render($response, 'isos', 'ISO 镜像'); } public function sshKeys($request, $response, $args) { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $keys = CloudDeploymentPageService::sshKeys((int) $actor['user_id']); $payload = [ 'user' => $this->userBootstrap($user, $actor), 'ssh_keys' => $keys, ]; return $this->render($response, 'keys', 'SSH 公钥', '', '', [ 'cloud_ssh_keys' => $keys, 'cloud_ssh_keys_bootstrap_json' => $this->safeJson($payload), ]); } public function invoices($request, $response, $args) { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $query = $request->getQueryParams(); $requestedPage = $query['page'] ?? '1'; $page = !is_array($requestedPage) && preg_match('/^[1-9][0-9]{0,8}$/D', (string) $requestedPage) === 1 ? (int) $requestedPage : 1; $payload = CloudInvoicePageService::forUser((int) $actor['user_id'], $page, 10); $payload['balance'] = (string) $user->money; $rows = array_map(fn (array $invoice): array => $this->invoiceListRow($invoice), $payload['invoices']); $json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_INVALID_UTF8_SUBSTITUTE); return $this->render($response, 'invoices', '账单信息', '', '', [ 'cloud_invoice_rows' => $rows, 'cloud_invoice_pagination' => $payload['pagination'], 'cloud_invoice_balance' => $this->formatUsd($payload['balance']), 'cloud_invoice_bootstrap_json' => $json === false ? '{}' : $json, ]); } public function invoiceDetail($request, $response, $args) { $invoiceId = isset($args['id']) ? (string) $args['id'] : ''; if (preg_match('/^[1-9][0-9]*$/D', $invoiceId) !== 1) { return $response->withHeader('Location', '/user/cloud/invoices')->withStatus(302); } $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); try { $payload = CloudInvoiceDetailPageService::forUser( (int) $invoiceId, (int) $actor['user_id'], $user, (bool) $actor['is_admin'] ); } catch (CloudError $error) { if ($error->httpStatus === 404) { return $response->withHeader('Location', '/user/cloud/invoices') ->withStatus(302); } throw $error; } return $this->render($response, 'invoice-detail', '账单详情', '', $invoiceId, [ 'cloud_invoice_detail_view' => $this->invoiceDetailView($payload), 'cloud_invoice_detail_bootstrap_json' => $this->safeJson($payload), ]); } public function reinstall($request, $response, $args) { $vmId = $this->vmId($args); if ($vmId === null) { return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302); } $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); try { $vm = CloudInstancePageService::detailForActor($actor, $vmId); } catch (CloudError $error) { if ($error->httpStatus === 404) { return $response->withHeader('Location', '/user/cloud/instances') ->withStatus(302); } throw $error; } $vm = $this->reinstallVm($vm); $catalog = CloudDeploymentPageService::templateCatalogForPage($actor); $templates = is_array($catalog['templates'] ?? null) ? $catalog['templates'] : []; $catalogUnavailable = ($catalog['catalog_unavailable'] ?? false) === true; $keys = $this->sshKeyOptions((int) $actor['user_id']); $payload = [ 'user' => $this->userBootstrap($user, $actor), 'vm' => $vm, 'templates' => $templates, 'ssh_keys' => $keys, 'catalog_unavailable' => $catalogUnavailable, ]; return $this->render($response, 'reinstall', '重装系统', $vmId, '', [ 'cloud_reinstall_vm' => $vm, 'cloud_reinstall_template_groups' => CloudDeploymentPageService::templateGroups($templates), 'cloud_reinstall_ssh_keys' => $keys, 'cloud_reinstall_catalog_unavailable' => $catalogUnavailable, 'cloud_reinstall_bootstrap_json' => $this->safeJson($payload), ]); } public function rescue($request, $response, $args) { return $this->renderVmPage($response, $args, 'rescue', '紧急救援'); } private function renderVmPage($response, $args, $page, $title) { $vmId = $this->vmId($args); if ($vmId === null) { return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302); } return $this->render($response, $page, $title, $vmId); } private function render($response, $page, $title, $vmId = '', $invoiceId = '', array $values = []) { $smarty = View::getSmarty('venix'); $smarty->assign('cloud_page', $page); $smarty->assign('cloud_title', $title); $smarty->assign('cloud_vm_id', $vmId); $smarty->assign('cloud_invoice_id', $invoiceId); $smarty->assign('cloud_invoice_rows', []); $smarty->assign('cloud_invoice_pagination', [ 'page' => 1, 'total' => 0, 'total_pages' => 1, 'has_previous' => false, 'has_next' => false, ]); $smarty->assign('cloud_invoice_balance', '$—'); $smarty->assign('cloud_invoice_bootstrap_json', '{}'); $smarty->assign('cloud_invoice_detail_view', []); $smarty->assign('cloud_invoice_detail_bootstrap_json', '{}'); $smarty->assign('cloud_vm_rows', []); $smarty->assign('cloud_vm_stats', [ 'total' => 0, 'running' => 0, 'stopped' => 0, 'other' => 0, ]); $smarty->assign('cloud_vm_pagination', [ 'page' => 1, 'per_page' => 20, 'total' => 0, 'total_pages' => 1, 'page_count' => 0, 'has_previous' => false, 'has_next' => false, 'from' => 0, 'to' => 0, ]); $smarty->assign('cloud_vm_view', []); $smarty->assign('cloud_vm_scope_label', '我的实例'); $smarty->assign('cloud_vm_bootstrap_json', '{}'); $smarty->assign('cloud_detail_ssh_keys', []); $smarty->assign('cloud_detail_has_ssh_keys', false); $smarty->assign('cloud_detail_no_ssh_keys', true); $smarty->assign('cloud_deploy_regions', []); $smarty->assign('cloud_deploy_lines', []); $smarty->assign('cloud_deploy_offers', []); $smarty->assign('cloud_deploy_lines_enabled', false); $smarty->assign('cloud_deploy_template_groups', []); $smarty->assign('cloud_deploy_ssh_keys', []); $smarty->assign('cloud_deploy_default_region_id', 0); $smarty->assign('cloud_deploy_default_line_id', 0); $smarty->assign('cloud_deploy_catalog_unavailable', false); $smarty->assign('cloud_deploy_bootstrap_json', '{}'); $smarty->assign('cloud_ssh_keys', []); $smarty->assign('cloud_ssh_keys_bootstrap_json', '{}'); $smarty->assign('cloud_reinstall_vm', []); $smarty->assign('cloud_reinstall_template_groups', []); $smarty->assign('cloud_reinstall_ssh_keys', []); $smarty->assign('cloud_reinstall_catalog_unavailable', false); $smarty->assign('cloud_reinstall_bootstrap_json', '{}'); $smarty->assign('panel_announcements_bootstrap_json', UserDrawerService::announcementBootstrapJson()); foreach ($values as $name => $value) { $smarty->assign($name, $value); } $response->getBody()->write($smarty->fetch('cloud/page.tpl')); // Every cloud page is authenticated and may contain account- or // tenant-specific data. Invoice list and detail pages are rendered // with user data, so intermediaries must never cache their HTML. return $response->withHeader('Cache-Control', 'private, no-store'); } private function invoiceListRow(array $invoice): array { [$statusLabel, $statusClass] = $this->invoiceStatus( (string) ($invoice['status'] ?? '') ); $fulfillment = strtolower((string) ($invoice['fulfillment_status'] ?? $invoice['job_status'] ?? $invoice['order_status'] ?? '')); [$fulfillmentLabel, $fulfillmentClass] = $this->invoiceFulfillmentStatus( $fulfillment ); $invoice['created_display'] = (int) ($invoice['created_at'] ?? 0) > 0 ? date('Y/m/d H:i:s', (int) $invoice['created_at']) : '时间未记录'; $invoice['amount_display'] = $this->formatUsd($invoice['amount'] ?? null); $invoice['status_label'] = $statusLabel; $invoice['status_class'] = $statusClass; $invoice['fulfillment_label'] = $fulfillmentLabel; $invoice['fulfillment_class'] = $fulfillmentClass; $invoice['show_fulfillment'] = (string) ($invoice['purpose'] ?? '') === 'provision' && in_array(strtolower((string) ($invoice['status'] ?? '')), ['paid', 'refunded'], true) && $fulfillmentLabel !== ''; return $invoice; } private function invoiceDetailView(array $payload): array { $invoice = is_array($payload['invoice'] ?? null) ? $payload['invoice'] : []; $purpose = strtolower((string) ($invoice['purpose'] ?? '')); [$statusLabel, $statusClass] = $this->invoiceStatus( (string) ($invoice['status'] ?? '') ); $created = $this->formatTimestamp($invoice['created_at'] ?? null, '时间未记录'); $facts = [ ['label' => '账单编号', 'value' => '#' . (string) ($invoice['id'] ?? '—')], ['label' => '创建时间', 'value' => $created], ]; if ($purpose === 'provision') { $facts[] = ['label' => '支付截止', 'value' => $this->formatTimestamp( $invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null )]; } elseif ($purpose === 'renewal') { $facts[] = ['label' => '实例到期', 'value' => $this->formatTimestamp( $invoice['due_at'] ?? null )]; if (($invoice['deletion_at'] ?? null) !== null) { $facts[] = ['label' => '最晚支付', 'value' => $this->formatTimestamp( $invoice['deletion_at'] )]; } } elseif (($invoice['payment_deadline_at'] ?? null) !== null) { $facts[] = ['label' => '支付截止', 'value' => $this->formatTimestamp( $invoice['payment_deadline_at'] )]; } if (($invoice['paid_at'] ?? null) !== null) { $facts[] = ['label' => '支付时间', 'value' => $this->formatTimestamp( $invoice['paid_at'] )]; } if (trim((string) ($invoice['paid_via'] ?? '')) !== '') { $facts[] = ['label' => '支付方式', 'value' => $this->paymentLabel( (string) $invoice['paid_via'] )]; } $specification = []; if (in_array($purpose, ['provision', 'renewal'], true)) { $subject = $this->firstText($invoice['requested_name'] ?? null, $invoice['instance_name'] ?? null); $specification[] = ['label' => '实例', 'value' => $subject !== '' ? $subject : ($purpose === 'provision' ? '待创建实例' : '实例')]; $planName = trim((string) ($invoice['plan_name'] ?? '')); $specification[] = ['label' => '套餐', 'value' => $planName !== '' ? $planName : '云服务器套餐']; if (($invoice['cpu_cores'] ?? null) !== null) { $specification[] = ['label' => 'CPU', 'value' => (string) $invoice['cpu_cores'] . ' 核']; } if (($invoice['memory_mib'] ?? null) !== null) { $specification[] = ['label' => '内存', 'value' => $this->formatMemory((int) $invoice['memory_mib'])]; } if (($invoice['disk_gib'] ?? null) !== null) { $specification[] = ['label' => '系统盘', 'value' => (string) $invoice['disk_gib'] . ' GB']; } if (($invoice['bandwidth_mbps'] ?? null) !== null) { $specification[] = ['label' => '带宽', 'value' => (string) $invoice['bandwidth_mbps'] . ' Mbps']; } $specification[] = ['label' => '服务周期', 'value' => max(0, (int) ($invoice['validity_days'] ?? 0)) . ' 天']; $specification[] = ['label' => '周期流量', 'value' => $this->formatBytes( max(0, (int) ($invoice['traffic_quota_bytes'] ?? 0)), true )]; } $paymentMethods = []; $payable = ($invoice['payable'] ?? false) === true; $balancePaymentAllowed = ($payload['balance_payment_allowed'] ?? false) === true; if ($payable && $balancePaymentAllowed) { $paymentMethods[] = [ 'id' => 'balance', 'name' => '账户余额', 'description' => '可用余额 ' . $this->formatUsd($payload['balance'] ?? null), 'selected' => true, ]; } if ($payable) { foreach (is_array($payload['payment_methods'] ?? null) ? $payload['payment_methods'] : [] as $method) { if (!is_array($method) || !isset($method['id'], $method['name'])) { continue; } $paymentMethods[] = [ 'id' => (string) $method['id'], 'name' => (string) $method['name'], 'description' => trim((string) ($method['description'] ?? $method['label'] ?? '')) ?: '在线支付', 'selected' => false, ]; } } if ($paymentMethods !== [] && !in_array(true, array_column($paymentMethods, 'selected'), true)) { $paymentMethods[0]['selected'] = true; } $fulfillment = is_array($invoice['fulfillment'] ?? null) ? $invoice['fulfillment'] : []; $fulfillmentStatus = strtolower($this->firstText( $fulfillment['job_status'] ?? null, $invoice['job_status'] ?? null, $invoice['fulfillment_status'] ?? null, $fulfillment['order_status'] ?? null, $invoice['order_status'] ?? null )); [$fulfillmentLabel, $fulfillmentClass] = $this->invoiceFulfillmentStatus( $fulfillmentStatus ); $showFulfillment = $purpose === 'provision' && (in_array(strtolower((string) ($invoice['status'] ?? '')), ['paid', 'refunded'], true) || $this->firstText($fulfillment['job_id'] ?? null, $invoice['job_id'] ?? null) !== ''); $fulfillmentError = $this->firstText($fulfillment['error'] ?? null, $invoice['error'] ?? null); $fulfillmentMessage = $fulfillmentError; if ($fulfillmentMessage === '') { $fulfillmentMessage = $fulfillmentStatus === 'uncertain' ? '后台正在核对实例创建结果,请勿重复提交。' : ($fulfillmentLabel !== '' ? $fulfillmentLabel : '等待创建'); } return [ 'id' => (string) ($invoice['id'] ?? ''), 'title' => (string) ($invoice['title'] ?? $invoice['type_label'] ?? '账单'), 'created_display' => $created, 'amount_display' => $this->formatUsd($invoice['amount'] ?? null), 'status_label' => $statusLabel, 'status_class' => $statusClass, 'facts' => $facts, 'show_specification' => $specification !== [], 'specification' => $specification, 'show_payment' => $payable && $paymentMethods !== [], 'payment_methods' => $paymentMethods, 'show_fulfillment' => $showFulfillment, 'fulfillment_message' => $fulfillmentMessage, 'fulfillment_label' => $fulfillmentLabel, 'fulfillment_class' => $fulfillmentClass, 'fulfillment_failed' => $fulfillmentMessage !== '' && ($fulfillmentError !== '' || in_array($fulfillmentStatus, ['failed', 'refunded', 'needs_attention'], true)), 'job_id' => $this->firstText($fulfillment['job_id'] ?? null, $invoice['job_id'] ?? null), 'instance_id' => $this->firstText($fulfillment['instance_id'] ?? null, $invoice['instance_id'] ?? null), ]; } private function invoiceStatus(string $status): array { return match (strtolower($status)) { 'open' => ['待支付', 'warning'], 'overdue' => ['已逾期', 'failed'], 'paid' => ['已支付', 'running'], 'refunded' => ['已退款', 'other'], 'void' => ['已失效', 'other'], 'expired' => ['已失效', 'failed'], 'deleting', 'purge_deleting' => ['实例删除中', 'failed'], 'purge_pending' => ['等待永久删除', 'failed'], 'purge_stopping' => ['删除前正在关机', 'failed'], 'purge_force_required' => ['等待管理员确认强制删除', 'failed'], 'delete_failed' => ['自动删除失败', 'failed'], 'purge_stop_failed' => ['删除前关机失败', 'failed'], 'purge_failed' => ['自动删除失败', 'failed'], default => [$status !== '' ? $status : '未知', 'other'], }; } private function invoiceFulfillmentStatus(string $status): array { return match (strtolower($status)) { 'awaiting_payment', 'payment_pending', 'draft' => ['等待支付', 'warning'], 'queued', 'pending' => ['等待创建', 'warning'], 'provisioning', 'running' => ['创建中', 'warning'], 'completed', 'succeeded', 'active' => ['已开通', 'running'], 'failed' => ['创建失败', 'failed'], 'refunded' => ['开通失败,已退款', 'failed'], 'needs_attention' => ['需要管理员核查', 'failed'], 'uncertain' => ['正在核对结果', 'warning'], default => ['', ''], }; } private function formatTimestamp($value, string $fallback = '暂未提供'): string { return is_numeric($value) && (int) $value > 0 ? date('Y/m/d H:i:s', (int) $value) : $fallback; } private function formatMemory(int $memoryMiB): string { $memoryGiB = $memoryMiB / 1024; return number_format($memoryGiB, $memoryGiB === floor($memoryGiB) ? 0 : 1, '.', ',') . ' GB'; } private function formatBytes(int $bytes, bool $unlimitedZero = false): string { if ($bytes === 0 && $unlimitedZero) { return '不限流量'; } $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; $amount = (float) $bytes; $unit = 0; while ($amount >= 1024 && $unit < count($units) - 1) { $amount /= 1024; ++$unit; } $precision = $unit === 0 ? 0 : ($amount >= 100 ? 0 : ($amount >= 10 ? 1 : 2)); return number_format($amount, $precision, '.', '') . ' ' . $units[$unit]; } private function paymentLabel(string $paidVia): string { return match (strtolower(trim($paidVia))) { 'balance' => '账户余额', 'yipay_alipay' => '易支付 · 支付宝', 'yipay_wxpay' => '易支付 · 微信', 'paytaro' => 'Paytaro · 支付宝', 'usdt' => 'USDT-TRC20', default => $paidVia, }; } private function firstText(...$values): string { foreach ($values as $value) { $text = trim((string) ($value ?? '')); if ($text !== '') { return $text; } } return ''; } private function formatUsd($value): string { if (!is_numeric($value) || (float) $value < 0) { return '$—'; } return '$' . number_format((float) $value, 2, '.', ','); } private function pageNumber($value): int { return !is_array($value) && preg_match('/^[1-9][0-9]{0,8}$/D', (string) $value) === 1 ? (int) $value : 1; } private function userBootstrap($user, array $actor): array { return [ 'csrf_token' => AdminCsrf::token(), 'user_id' => (string) $user->id, 'username' => (string) ($user->user_name ?: $user->email), 'admin' => (bool) $actor['is_admin'], ]; } private function safeJson(array $value): string { $json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_INVALID_UTF8_SUBSTITUTE); return $json === false ? '{}' : $json; } private function vmId(array $args): ?string { $vmId = isset($args['id']) ? (string) $args['id'] : ''; return preg_match('/^[1-9][0-9]*$/D', $vmId) === 1 ? $vmId : null; } /** Deployment forms expose only the key identifier and safe display metadata. */ private function sshKeyOptions(int $userId): array { return array_map(static fn (array $key): array => [ 'id' => $key['id'], 'name' => $key['name'], 'fingerprint' => $key['fingerprint'], ], CloudDeploymentPageService::sshKeys($userId)); } /** Keep reinstall bootstrap small and free of internal host identifiers. */ private function reinstallVm(array $vm): array { $keys = [ 'id', 'api_id', 'uuid', 'name', 'state', 'public_ip_cidr', 'public_ip', 'instance_status', 'service_status', 'network_status', 'can_operate', 'can_delete', 'is_owner', ]; $result = array_intersect_key($vm, array_flip($keys)); $address = trim((string) ($result['public_ip_cidr'] ?? $result['public_ip'] ?? '')); $result['public_ip'] = $address === '' ? '' : (explode('/', $address, 2)[0] ?: ''); return $result; } private function vmListRow(array $vm): array { [$stateLabel, $stateClass, $stateSyncLabel, $stateSyncClass] = $this->vmListState($vm); [$systemLabel, $systemValue] = $this->vmSystem($vm); return [ 'api_id' => (string) ($vm['api_id'] ?? $vm['id'] ?? ''), 'uuid' => (string) ($vm['uuid'] ?? ''), 'name' => (string) ($vm['name'] ?? '未命名虚拟机'), 'state_label' => $stateLabel, 'state_class' => $stateClass, 'state_sync_label' => $stateSyncLabel, 'state_sync_class' => $stateSyncClass, 'region' => trim((string) ($vm['region'] ?? '')) ?: '未设置', 'system_label' => $systemLabel, 'system_value' => $systemValue, 'ip' => $this->vmIp($vm), 'has_ip' => $this->vmIp($vm) !== '未获取', 'vcpu' => isset($vm['vcpu']) ? (int) $vm['vcpu'] : (isset($vm['cpu_cores']) ? (int) $vm['cpu_cores'] : null), 'memory_mib' => isset($vm['memory_mib']) ? (int) $vm['memory_mib'] : (isset($vm['ram_mib']) ? (int) $vm['ram_mib'] : null), 'disk_label' => $this->vmDisk($vm), ]; } /** Presentation for the cached list state; operation controls stay live. */ private function vmListState(array $vm): array { $state = strtolower((string) ($vm['state'] ?? 'unknown')); $sync = strtolower(trim((string) ($vm['state_sync_status'] ?? 'pending'))); $hasState = $state !== '' && $state !== 'unknown' && $state !== 'nostate'; if (in_array($sync, ['offline', 'host_offline', 'unavailable', 'host_unreachable'], true)) { return ['暂时无法同步', 'other', '', 'offline']; } if (in_array($sync, ['pending', 'never'], true)) { $hint = trim((string) ($vm['state_label_hint'] ?? '')); if ($hint === '') { $hint = in_array((string) ($vm['instance_status'] ?? ''), ['creating', 'provisioning', 'deploying'], true) ? '部署中' : '等待宿主机同步'; } return [$hint, 'other', '', '']; } if (!$hasState) { $hint = trim((string) ($vm['state_label_hint'] ?? '')); if ($hint === '') { $hint = in_array((string) ($vm['instance_status'] ?? ''), ['creating', 'provisioning', 'deploying'], true) ? '部署中' : '等待宿主机同步'; } return [$hint, 'other', '', '']; } [$label, $class] = $this->vmState($state); if ((bool) ($vm['state_fresh'] ?? false)) { return [$label, $class, '', '']; } return [$label, $class, '状态同步中', 'stale']; } private function vmDetailView(array $vm): array { [$stateLabel, $stateClass, $stateSyncLabel, $stateSyncClass] = $this->vmDetailState($vm); [$systemLabel, $systemValue] = $this->vmSystem($vm); [$serviceLabel, $serviceClass] = $this->serviceStatus( (string) ($vm['service_status'] ?? '') ); [$networkLabel, $networkClass] = $this->networkStatus( (string) ($vm['network_status'] ?? '') ); $quota = max(0, (int) ($vm['traffic_quota_bytes'] ?? 0)); $download = max(0, (int) ($vm['traffic_download_bytes'] ?? 0)); $upload = max(0, (int) ($vm['traffic_upload_bytes'] ?? 0)); $used = max(0, (int) ($vm['traffic_used_bytes'] ?? ($download + $upload))); $remaining = $quota === 0 ? 0 : max(0, $quota - $used); $passwordAvailable = (bool) ($vm['password_available'] ?? false); $vcpu = isset($vm['vcpu']) ? (int) $vm['vcpu'] : (isset($vm['cpu_cores']) ? (int) $vm['cpu_cores'] : null); $memory = isset($vm['memory_mib']) ? (int) $vm['memory_mib'] : (isset($vm['ram_mib']) ? (int) $vm['ram_mib'] : null); return [ 'name' => (string) ($vm['name'] ?? '虚拟机'), 'state_label' => $stateLabel, 'state_class' => $stateClass, 'state_sync_label' => $stateSyncLabel, 'state_sync_class' => $stateSyncClass, 'region' => trim((string) ($vm['region'] ?? '')) ?: '未设置', 'ip' => $this->vmIp($vm), 'created_display' => $this->createdAgo($vm['created_at'] ?? null), 'system_label' => $systemLabel, 'system_value' => $systemValue, 'spec_display' => ($vcpu ?? '—') . ' vCPU · ' . ($memory ?? '—') . ' MiB', 'disk_display' => $this->vmDisk($vm), 'ssh_user' => trim((string) ($vm['login_name'] ?? '')) ?: '未记录', 'password_label' => $passwordAvailable ? '********' : '未记录', 'password_available' => $passwordAvailable, 'can_operate' => (bool) ($vm['can_operate'] ?? false), 'can_settings' => (bool) ($vm['is_owner'] ?? false) && (bool) ($vm['can_operate'] ?? false) && (string) ($vm['os_source'] ?? '') === 'cloud_template', 'guest_hostname' => trim((string) ($vm['guest_hostname'] ?? '')) ?: '未记录', 'can_delete' => (bool) ($vm['can_delete'] ?? false), 'can_rename' => (bool) ($vm['can_rename'] ?? false), 'service_status_label' => $serviceLabel, 'service_status_class' => $serviceClass, 'network_status_label' => $networkLabel, 'network_status_class' => $networkClass, 'period_end_display' => $this->dateTime($vm['current_period_ends_at'] ?? null), 'traffic_rx_display' => $this->formatBytes($download), 'traffic_tx_display' => $this->formatBytes($upload), 'traffic_used_display' => $this->formatBytes($used), 'traffic_total_remaining_display' => $quota === 0 ? '不限流量 / 不限流量' : $this->formatBytes($quota) . ' / ' . $this->formatBytes($remaining), 'traffic_ratio' => $quota === 0 ? '' : number_format( min(100, max(0, ($used / $quota) * 100)), 1, '.', '' ), ]; } /** Render cached power state without turning stale data into a live claim. */ private function vmDetailState(array $vm): array { $state = strtolower((string) ($vm['state'] ?? 'unknown')); $sync = strtolower(trim((string) ($vm['state_sync_status'] ?? 'pending'))); if (in_array($sync, ['offline', 'host_offline', 'unavailable', 'host_unreachable'], true)) { return ['暂时无法同步', 'other', '', 'offline']; } $known = $state !== '' && !in_array($state, ['unknown', 'nostate'], true); if (!$known || in_array($sync, ['pending', 'never'], true)) { $hint = trim((string) ($vm['state_label_hint'] ?? '')); if ($hint === '') { $hint = in_array((string) ($vm['instance_status'] ?? ''), ['creating', 'provisioning', 'deploying'], true) ? '部署中' : '等待宿主机同步'; } return [$hint, 'other', '', '']; } [$label, $class] = $this->vmState($state); if ((bool) ($vm['state_fresh'] ?? false) || in_array($sync, ['', 'fresh'], true)) { return [$label, $class, '', '']; } return [$label, $class, '状态同步中', 'stale']; } private function vmState(string $value): array { $normalized = strtolower((string) preg_replace('/[_\s-]+/', '', $value)); if (in_array($normalized, ['running', 'blocked'], true)) { return ['运行中', 'running']; } if (in_array($normalized, ['shutoff', 'stopped'], true)) { return ['已关机', 'stopped']; } return match ($normalized) { 'shutdown' => ['关机中', 'other'], 'crashed' => ['已崩溃', 'stopped'], 'paused' => ['已暂停', 'other'], 'pmsuspended' => ['已挂起', 'other'], default => ['等待宿主机同步', 'other'], }; } private function vmSystem(array $vm): array { $source = (string) ($vm['os_source'] ?? ''); if ($source === 'iso') { return ['安装镜像', trim((string) ($vm['install_iso'] ?? '')) ?: '未识别']; } if ($source === 'cloud_template') { return ['系统镜像', trim((string) ($vm['os_name'] ?? '')) ?: '未识别']; } $value = trim((string) ($vm['os_name'] ?? '')); if ($value === '') { $value = trim((string) ($vm['install_iso'] ?? '')); } return ['系统', $value !== '' ? $value : '未识别']; } private function vmIp(array $vm): string { $value = trim((string) ($vm['public_ip_cidr'] ?? '')); if ($value === '') { $value = trim((string) ($vm['public_ip'] ?? '')); } return $value === '' ? '未获取' : (explode('/', $value, 2)[0] ?: '未获取'); } private function vmDisk(array $vm): string { $size = 0.0; foreach (is_array($vm['disks'] ?? null) ? $vm['disks'] : [] as $disk) { if (!is_array($disk)) { continue; } $value = $disk['capacity_gib'] ?? $disk['size_gib'] ?? 0; if (is_numeric($value) && (float) $value > 0) { $size += (float) $value; } } if ($size <= 0 && is_numeric($vm['disk_gib'] ?? null)) { $size = max(0, (float) $vm['disk_gib']); } if ($size <= 0) { return '—'; } return rtrim(rtrim(number_format($size, 2, '.', ''), '0'), '.') . ' GiB'; } private function createdAgo($value): string { $timestamp = is_string($value) ? strtotime($value) : false; if ($timestamp === false || $timestamp <= 0) { return '未记录'; } $elapsed = max(0, time() - $timestamp); if ($elapsed < 60) { return '创建于刚刚'; } if ($elapsed < 3600) { return '创建于 ' . intdiv($elapsed, 60) . ' 分钟前'; } if ($elapsed < 86400) { return '创建于 ' . intdiv($elapsed, 3600) . ' 小时前'; } if ($elapsed < 2592000) { return '创建于 ' . intdiv($elapsed, 86400) . ' 天前'; } return '创建于 ' . intdiv($elapsed, 2592000) . ' 个月前'; } private function serviceStatus(string $value): array { $labels = [ 'active' => ['服务有效', 'active'], 'pending' => ['待生效', 'warning'], 'renewing' => ['续费处理中', 'warning'], 'exempt' => ['不受套餐限制', 'active'], 'suspended_expired' => ['已因到期停机', 'stopped'], 'suspended_traffic' => ['已因流量用尽暂停', 'stopped'], 'expired' => ['已到期', 'stopped'], 'deleting' => ['正在永久删除', 'warning'], 'purge_force_required' => ['等待管理员确认强制删除', 'stopped'], 'purge_deleting' => ['正在永久删除', 'warning'], 'delete_failed' => ['自动删除失败,请联系管理员', 'stopped'], ]; return $labels[strtolower(str_replace('-', '_', trim($value)))] ?? [$value !== '' ? $value : '暂未提供', 'unknown']; } private function networkStatus(string $value): array { $labels = [ 'active' => ['网络正常', 'active'], 'blocking' => ['正在暂停网络', 'warning'], 'blocked_traffic' => ['本期流量用尽,已断网', 'stopped'], 'blocked_expired' => ['实例已到期,网络已停用', 'stopped'], 'restoring' => ['正在恢复网络', 'warning'], 'restore_pending' => ['等待恢复网络', 'warning'], 'restore_failed' => ['网络恢复失败,请联系管理员', 'stopped'], 'exempt' => ['网络不受套餐限制', 'active'], ]; return $labels[strtolower(str_replace('-', '_', trim($value)))] ?? [$value !== '' ? $value : '暂未提供', 'unknown']; } private function dateTime($value): string { return is_numeric($value) && (int) $value > 0 ? date('Y/m/d H:i:s', (int) $value) : '暂未提供'; } }