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', '实例管理', '', '', function (UserCopyCatalog $copy) use ($payload, $actor): array { return [ 'cloud_vm_rows' => array_map( fn (array $vm): array => $this->vmListRow($vm, $copy), $payload['vms'] ), 'cloud_vm_stats' => $payload['stats'], 'cloud_vm_pagination' => $payload['pagination'], 'cloud_vm_scope_label' => $copy->text( ($actor['is_admin'] ?? false) ? 'instances.stats.scope_all' : 'instances.stats.scope' ), '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_paid_ip_change_visible' => CloudPaidIpChangeFeature::visible(), 'cloud_vm_bootstrap_json' => $this->safeJson($payload), ]); } public function deploy($request, $response, $args) { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $cloudSnapshot = null; $snapshotKey = $request->getQueryParams()['cloud_snapshot'] ?? null; if ($snapshotKey !== null && $snapshotKey !== '') { if (!is_string($snapshotKey)) { return $response->withHeader( 'Location', '/user/cloud/cloud-snapshots' )->withStatus(302); } try { $cloudSnapshot = CloudDeploymentSnapshotService::deploymentSource( $snapshotKey, $actor ); } catch (CloudError $error) { if (in_array($error->httpStatus, [400, 404, 409], true)) { return $response->withHeader( 'Location', '/user/cloud/cloud-snapshots' )->withStatus(302); } throw $error; } } $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; $defaultOfferId = 0; $defaultOffer = null; foreach ($offers as $offer) { if ((int) $offer['region_id'] === $defaultRegionId && (int) $offer['line_id'] === $defaultLineId && $offer['sellable'] === true) { $defaultOfferId = (int) $offer['id']; $defaultOffer = $offer; break; } } $defaultCyclePrices = []; foreach (($defaultOffer['billing_cycles'] ?? []) as $cycle) { if (is_array($cycle) && isset($cycle['code'], $cycle['price'])) { $defaultCyclePrices[(string) $cycle['code']] = (float) $cycle['price']; } } $formatCyclePrice = static function ( array $prices, string $cycle, int $divisor = 1 ): string { if (!array_key_exists($cycle, $prices)) { return ''; } return '$' . number_format( $prices[$cycle] / $divisor, 2, '.', '' ) . ' USD'; }; $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, 'default_offer_id' => $defaultOfferId, 'catalog_unavailable' => $catalogUnavailable, 'cloud_snapshot' => $cloudSnapshot, ]; 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, $defaultOfferId ), 'cloud_deploy_ssh_keys' => $keys, 'cloud_deploy_default_region_id' => $defaultRegionId, 'cloud_deploy_default_line_id' => $defaultLineId, 'cloud_deploy_default_offer_id' => $defaultOfferId, 'cloud_deploy_price' => $formatCyclePrice( $defaultCyclePrices, 'monthly' ), 'cloud_deploy_quarterly_price' => $formatCyclePrice( $defaultCyclePrices, 'quarterly' ), 'cloud_deploy_quarterly_equivalent' => $formatCyclePrice( $defaultCyclePrices, 'quarterly', 3 ), 'cloud_deploy_annual_price' => $formatCyclePrice( $defaultCyclePrices, 'annual' ), 'cloud_deploy_annual_equivalent' => $formatCyclePrice( $defaultCyclePrices, 'annual', 12 ), 'cloud_deploy_backup_price' => $defaultOffer === null ? '' : '$' . number_format((float) $defaultOffer['backup_price'], 2, '.', '') . ' USD', 'cloud_deploy_snapshot' => $cloudSnapshot, 'cloud_deploy_catalog_unavailable' => $catalogUnavailable, 'cloud_deploy_bootstrap_json' => $this->safeJson($payload), ]); } public function backups($request, $response, $args) { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $page = $this->pageNumber( $request->getQueryParams()['page'] ?? '1' ); $payload = CloudAutomaticBackupService::library( $actor, ['page' => $page, 'per_page' => 20] ); $payload['user'] = $this->userBootstrap($user, $actor); return $this->render($response, 'backups', '云备份', '', '', [ 'cloud_backup_view' => CloudUserPageView::backups($payload), 'cloud_backup_bootstrap_json' => $this->safeJson($payload), ]); } public function cloudSnapshots($request, $response, $args) { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $page = $this->pageNumber( $request->getQueryParams()['page'] ?? '1' ); $payload = CloudDeploymentSnapshotService::library( $actor, ['page' => $page, 'per_page' => 20] ); $payload['user'] = $this->userBootstrap($user, $actor); return $this->render( $response, 'cloud-snapshots', '云快照', '', '', ['cloud_snapshot_bootstrap_json' => $this->safeJson($payload), 'cloud_snapshot_view' => CloudUserPageView::cloudSnapshots($payload)] ); } public function trafficPools($request, $response, $args) { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $payload = CloudTrafficPoolReadModel::forUser( (int) $actor['user_id'] ); $payload['user'] = $this->userBootstrap($user, $actor); return $this->render($response, 'traffic', '流量池', '', '', [ 'cloud_traffic_view' => CloudUserPageView::trafficPools($payload), 'cloud_traffic_bootstrap_json' => $this->safeJson($payload), ]); } public function vpcs($request, $response, $args) { if (!CloudVpcFeature::enabled()) { return $response->withHeader( 'Location', '/user/cloud/instances' )->withStatus(302); } $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $payload = CloudVpcService::library($actor); $payload['user'] = $this->userBootstrap($user, $actor); return $this->render($response, 'vpcs', 'VPC 私网', '', '', [ 'cloud_vpc_view' => CloudUserPageView::vpcs($payload, $request->getQueryParams()), 'cloud_vpc_bootstrap_json' => $this->safeJson($payload), ]); } public function isoImages($request, $response, $args) { if (!CloudUserIsoFeature::enabled()) { return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302); } $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $payload = CloudUserIsoService::listing((int) $actor['user_id']); $payload['can_import'] = (int) $user->enable === 1; $payload['user'] = $this->userBootstrap($user, $actor); return $this->render($response, 'isos', 'ISO 镜像', '', '', [ 'cloud_iso_view' => CloudUserPageView::isos($payload), 'cloud_iso_bootstrap_json' => $this->safeJson($payload), ]); } public function sshKeys($request, $response, $args) { $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $keys = CloudDeploymentPageService::sshKeys((int) $actor['user_id']); $requestedView = $request->getQueryParams()['view'] ?? 'list'; $view = is_string($requestedView) && $requestedView === 'add' ? 'add' : 'list'; $payload = [ 'user' => $this->userBootstrap($user, $actor), 'ssh_keys' => $keys, ]; return $this->render($response, 'keys', 'SSH 公钥', '', '', [ 'cloud_ssh_keys_view' => $view, '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(); $payload = CloudInvoicePageService::withBalance( CloudInvoicePageService::queryForUser( (int) $actor['user_id'], is_array($query) ? $query : [] ), (string) $user->money ); $rows = $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_filter' => $payload['purpose'], 'cloud_invoice_filters' => $payload['filters'], 'cloud_invoice_pagination' => $payload['pagination'], 'cloud_invoice_balance' => $payload['balance_display'], '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' => $payload['presentation'], '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); $hostId = (int) CloudAccess::instance($vmId, $actor)->host_id; $catalog = CloudDeploymentPageService::templateCatalogForHost( $hostId, $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), ]); } private function render($response, $page, $title, $vmId = '', $invoiceId = '', $values = []) { $smarty = View::getSmarty('venix'); $copyPage = [ 'instances' => 'cloud.instances', 'detail' => 'cloud.detail', 'deploy' => 'cloud.deploy', 'backups' => 'cloud.backups', 'cloud-snapshots' => 'cloud.snapshots', 'traffic' => 'cloud.traffic', 'vpcs' => 'cloud.vpcs', 'isos' => 'cloud.isos', 'keys' => 'cloud.keys', 'invoices' => 'cloud.invoices', 'invoice-detail' => 'cloud.invoice_detail', 'reinstall' => 'cloud.reinstall', ][$page] ?? null; $copyCatalog = UserCopyViewRuntime::production()->bindCurrentRequest( $smarty, $copyPage ); $titleCopyKey = [ 'instances' => 'instances.title', 'deploy' => 'deploy.title', 'detail' => 'instance_detail.page_title', 'backups' => 'backups.title', 'cloud-snapshots' => 'snapshots.title', 'traffic' => 'traffic.title', 'vpcs' => 'vpc.home.title', 'isos' => 'isos.title', 'keys' => 'ssh_keys.list.title', 'invoices' => 'billing.list.title', 'invoice-detail' => 'billing.detail.title', 'reinstall' => 'reinstall.title', ][$page] ?? null; if ($titleCopyKey !== null) { $title = $copyCatalog->text($titleCopyKey); } if (is_callable($values)) { $values = $values($copyCatalog); } if (!is_array($values)) { throw new \LogicException('Cloud page values must resolve to an array.'); } $smarty->assign('cloud_page', $page); $smarty->assign('cloud_page_module', [ 'instances' => 'instances', 'detail' => 'detail', 'deploy' => 'deploy', 'backups' => 'backups', 'cloud-snapshots' => 'cloud-snapshots', 'traffic' => 'traffic', 'vpcs' => 'vpcs', 'isos' => 'iso-images', 'keys' => 'ssh-keys', 'invoices' => 'invoices', 'invoice-detail' => 'invoice-detail', 'reinstall' => 'reinstall', ][$page] ?? ''); $smarty->assign('cloud_uses_runtime', in_array($page, [ 'detail', 'deploy', 'backups', 'cloud-snapshots', 'traffic', 'vpcs', 'isos', 'reinstall', ], true)); $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_filter', 'all'); $smarty->assign('cloud_invoice_filters', [ 'page' => 1, 'purpose' => 'all', 'status' => 'all', 'keyword' => '', ]); $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_default_offer_id', 0); $smarty->assign('cloud_deploy_price', ''); $smarty->assign('cloud_deploy_backup_price', ''); $smarty->assign('cloud_deploy_snapshot', null); $smarty->assign('cloud_deploy_catalog_unavailable', false); $smarty->assign('cloud_deploy_bootstrap_json', '{}'); $smarty->assign('cloud_backup_bootstrap_json', '{}'); $smarty->assign('cloud_backup_view', CloudUserPageView::backups([])); $smarty->assign('cloud_snapshot_bootstrap_json', '{}'); $smarty->assign('cloud_snapshot_view', CloudUserPageView::cloudSnapshots([])); $smarty->assign('cloud_traffic_bootstrap_json', '{}'); $smarty->assign('cloud_traffic_view', CloudUserPageView::trafficPools([])); $smarty->assign('cloud_vpc_bootstrap_json', '{}'); $smarty->assign('cloud_vpc_view', CloudUserPageView::vpcs([], [])); $smarty->assign('cloud_iso_bootstrap_json', '{}'); $smarty->assign('cloud_iso_view', CloudUserPageView::isos([])); $smarty->assign('cloud_ssh_keys_view', 'list'); $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 formatBytes(int $bytes): string { $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 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_network_valid', 'public_network', 'public_ipv4', 'public_ipv4_cidr', 'public_ipv6', 'public_ipv6_cidr', '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)); $result['public_ip'] = $this->vmIp($vm, 4, ''); return $result; } private function vmListRow(array $vm, UserCopyCatalog $copy): array { [$stateLabel, $stateClass, $stateSyncLabel, $stateSyncClass] = $this->vmListState($vm, $copy); [$systemLabel, $systemValue] = $this->vmListSystem($vm, $copy); $missingIp = $copy->text('instances.value.not_available'); $ipv4 = $this->vmIp($vm, 4, $missingIp); $ipv6 = $this->vmIp($vm, 6, $missingIp); return [ 'api_id' => (string) ($vm['api_id'] ?? $vm['id'] ?? ''), 'uuid' => (string) ($vm['uuid'] ?? ''), 'name' => trim((string) ($vm['name'] ?? '')) ?: $copy->text('instances.value.unnamed'), 'state_label' => $stateLabel, 'state_class' => $stateClass, 'state_sync_label' => $stateSyncLabel, 'state_sync_class' => $stateSyncClass, 'service_expiry_display' => (string) ($vm['service_status'] ?? '') === 'exempt' ? $copy->text('instances.expiry.permanent') : (is_numeric($vm['service_expires_at'] ?? null) && (int) $vm['service_expires_at'] > 0 ? date('Y/m/d H:i:s', (int) $vm['service_expires_at']) : $copy->text('instances.value.not_available')), 'region' => trim((string) ($vm['region'] ?? '')) ?: $copy->text('instances.value.not_set'), 'system_label' => $systemLabel, 'system_value' => $systemValue, 'ipv4' => $ipv4, 'ipv6' => $ipv6, 'has_ipv4' => $ipv4 !== $missingIp, 'has_ipv6' => $ipv6 !== $missingIp, '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, UserCopyCatalog $copy): array { if ((string) ($vm['network_status'] ?? '') === 'configuration_invalid') { return [$copy->text('instances.state.network_invalid'), 'other', '', '']; } if ((bool) ($vm['service_paused'] ?? false)) { return [$copy->text('instances.state.paused'), 'other', '', '']; } $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 [$copy->text('instances.state.sync_unavailable'), 'other', '', 'offline']; } if (in_array($sync, ['pending', 'never'], true)) { $hint = in_array((string) ($vm['instance_status'] ?? ''), ['creating', 'provisioning', 'deploying'], true) ? $copy->text('instances.state.deploying') : $copy->text('instances.state.awaiting_sync'); return [$hint, 'other', '', '']; } if (!$hasState) { $hint = in_array((string) ($vm['instance_status'] ?? ''), ['creating', 'provisioning', 'deploying'], true) ? $copy->text('instances.state.deploying') : $copy->text('instances.state.awaiting_sync'); return [$hint, 'other', '', '']; } [$copyKey, $class] = $this->vmListStateKey($state); $label = $copy->text($copyKey); if ((bool) ($vm['state_fresh'] ?? false)) { return [$label, $class, '', '']; } return [$label, $class, $copy->text('instances.state.syncing'), 'stale']; } private function vmListStateKey(string $state): array { $normalized = strtolower((string) preg_replace('/[_\s-]+/', '', $state)); if (in_array($normalized, ['running', 'blocked'], true)) { return ['instances.state.running', 'running']; } if (in_array($normalized, ['shutoff', 'stopped'], true)) { return ['instances.state.stopped', 'stopped']; } return match ($normalized) { 'shutdown' => ['instances.state.shutting_down', 'other'], 'crashed' => ['instances.state.crashed', 'stopped'], 'paused' => ['instances.state.paused', 'other'], 'pmsuspended' => ['instances.state.suspended', 'other'], default => ['instances.state.awaiting_sync', 'other'], }; } private function vmListSystem(array $vm, UserCopyCatalog $copy): array { $source = (string) ($vm['os_source'] ?? ''); if ($source === 'iso') { return [ $copy->text('instances.system.iso'), trim((string) ($vm['install_iso'] ?? '')) ?: $copy->text('instances.value.unrecognized'), ]; } if ($source === 'cloud_template') { return [ $copy->text('instances.system.template'), trim((string) ($vm['os_name'] ?? '')) ?: $copy->text('instances.value.unrecognized'), ]; } $value = trim((string) ($vm['os_name'] ?? '')); if ($value === '') { $value = trim((string) ($vm['install_iso'] ?? '')); } return [ $copy->text('instances.system.other'), $value !== '' ? $value : $copy->text('instances.value.unrecognized'), ]; } private function vmDetailView(array $vm): array { [$stateLabel, $stateClass, $stateSyncLabel, $stateSyncClass] = $this->vmDetailState($vm); [$systemLabelCopyKey, $systemValue] = $this->vmDetailSystem($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))); $accountingMode = (string) ( $vm['traffic_accounting_mode'] ?? 'legacy' ); $pool = is_array($vm['traffic_pool'] ?? null) ? $vm['traffic_pool'] : []; $poolProjectionReady = ($pool['projection_ready'] ?? false) === true; $displayQuota = $accountingMode === 'pooled' ? max(0, (int) ($pool['active_entitlement_bytes'] ?? 0)) : $quota; $displayConsumed = $accountingMode === 'pooled' ? max(0, (int) ($pool['active_consumed_bytes'] ?? 0)) : $used; $remaining = $accountingMode === 'pooled' ? max(0, (int) ($pool['available_bytes'] ?? 0)) : ($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); [$createdCopyKey, $createdCopyCount] = $this->createdCopy( $vm['created_at'] ?? null ); return [ 'name' => trim((string) ($vm['name'] ?? '')), 'state_copy_key' => $stateLabel, 'state_class' => $stateClass, 'state_sync_copy_key' => $stateSyncLabel, 'state_sync_class' => $stateSyncClass, 'region' => trim((string) ($vm['region'] ?? '')), 'ipv4' => $this->vmIp($vm, 4, ''), 'ipv6' => $this->vmIp($vm, 6, ''), 'has_ipv4' => $this->vmIp($vm, 4, '') !== '', 'has_ipv6' => $this->vmIp($vm, 6, '') !== '', 'created_copy_key' => $createdCopyKey, 'created_copy_count' => $createdCopyCount, 'system_label_copy_key' => $systemLabelCopyKey, 'system_value' => $systemValue, 'spec_display' => ($vcpu ?? '—') . ' vCPU · ' . ($memory ?? '—') . ' MiB', 'disk_display' => $this->vmDisk($vm), 'ssh_user' => trim((string) ($vm['login_name'] ?? '')), 'password_mask' => $passwordAvailable ? '********' : '', 'password_available' => $passwordAvailable, 'can_operate' => (bool) ($vm['can_operate'] ?? false), 'is_owner' => (bool) ($vm['is_owner'] ?? false), 'can_settings' => (bool) ($vm['is_owner'] ?? false) && (bool) ($vm['can_operate'] ?? false) && (string) ($vm['os_source'] ?? '') === 'cloud_template', 'can_rescue' => (bool) ($vm['can_operate'] ?? false), 'guest_hostname' => trim((string) ($vm['guest_hostname'] ?? '')), 'can_delete' => (bool) ($vm['can_delete'] ?? false), 'can_rename' => (bool) ($vm['can_rename'] ?? false), 'service_status_copy_key' => $serviceLabel, 'service_status_class' => $serviceClass, 'network_status_copy_key' => $networkLabel, 'network_status_class' => $networkClass, 'service_expiry_at' => is_numeric($vm['service_expires_at'] ?? null) ? max(0, (int) $vm['service_expires_at']) : 0, 'traffic_rx_display' => $this->formatBytes($download), 'traffic_tx_display' => $this->formatBytes($upload), 'traffic_used_display' => $this->formatBytes($used), 'traffic_accounting_mode' => $accountingMode, 'traffic_description_copy_key' => $accountingMode === 'pooled' ? ($poolProjectionReady ? 'instance_detail.traffic.pooled_description' : 'instance_detail.traffic.pool_initializing') : 'instance_detail.traffic.description', 'traffic_used_label_copy_key' => $accountingMode === 'pooled' ? 'instance_detail.traffic.instance_sample_total' : 'instance_detail.traffic.used', 'traffic_total_label_copy_key' => $accountingMode === 'pooled' ? 'instance_detail.traffic.pool_total_remaining' : 'instance_detail.traffic.total_remaining', 'traffic_total_remaining_copy_key' => $accountingMode === 'pooled' && !$poolProjectionReady ? 'instance_detail.traffic.preparing_pair' : ($accountingMode === 'unlimited' || ($accountingMode === 'legacy' && $quota === 0) ? 'instance_detail.traffic.unlimited_pair' : ''), 'traffic_total_remaining_display' => $accountingMode === 'pooled' && !$poolProjectionReady ? '' : ($accountingMode === 'unlimited' || ($accountingMode === 'legacy' && $quota === 0) ? '' : $this->formatBytes($displayQuota) . ' / ' . $this->formatBytes($remaining)), 'traffic_ratio' => !$poolProjectionReady && $accountingMode === 'pooled' ? '' : ($displayQuota === 0 ? '' : number_format( min(100, max(0, ($displayConsumed / $displayQuota) * 100)), 1, '.', '' )), 'traffic_pool_name' => $accountingMode === 'pooled' ? trim((string) ($pool['name'] ?? '')) : '', ]; } /** Render cached power state without turning stale data into a live claim. */ private function vmDetailState(array $vm): array { if ((bool) ($vm['service_paused'] ?? false)) { return ['instance_detail.state.paused', 'other', '', '']; } $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 ['instance_detail.state.sync_unavailable', 'other', '', 'offline']; } $known = $state !== '' && !in_array($state, ['unknown', 'nostate'], true); if (!$known || in_array($sync, ['pending', 'never'], true)) { $hint = in_array((string) ($vm['instance_status'] ?? ''), ['creating', 'provisioning', 'deploying'], true) ? 'instance_detail.state.deploying' : 'instance_detail.state.awaiting_sync'; return [$hint, 'other', '', '']; } [$label, $class] = match (strtolower((string) preg_replace( '/[_\s-]+/', '', $state ))) { 'running', 'blocked' => ['instance_detail.state.running', 'running'], 'shutoff', 'stopped' => ['instance_detail.state.stopped', 'stopped'], 'shutdown' => ['instance_detail.state.shutting_down', 'other'], 'crashed' => ['instance_detail.state.crashed', 'stopped'], 'paused' => ['instance_detail.state.paused', 'other'], 'pmsuspended' => ['instance_detail.state.suspended', 'other'], default => ['instance_detail.state.awaiting_sync', 'other'], }; if ((bool) ($vm['state_fresh'] ?? false) || in_array($sync, ['', 'fresh'], true)) { return [$label, $class, '', '']; } return [$label, $class, 'instance_detail.state.sync_pending', 'stale']; } private function vmDetailSystem(array $vm): array { $source = (string) ($vm['os_source'] ?? ''); if ($source === 'iso') { return [ 'instance_detail.system.install_image', trim((string) ($vm['install_iso'] ?? '')), ]; } if ($source === 'cloud_template') { return [ 'instance_detail.system.cloud_image', trim((string) ($vm['os_name'] ?? '')), ]; } $value = trim((string) ($vm['os_name'] ?? '')); if ($value === '') { $value = trim((string) ($vm['install_iso'] ?? '')); } return ['instance_detail.info.system', $value]; } private function vmIp(array $vm, int $family, string $missing = ''): string { if (($vm['public_network_valid'] ?? false) !== true) { return $missing; } $key = $family === 6 ? 'public_ipv6' : 'public_ipv4'; $value = trim((string) ($vm[$key] ?? '')); return $value === '' ? $missing : $value; } 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'; } /** @return array{0:string,1:int} */ private function createdCopy($value): array { $timestamp = is_string($value) ? strtotime($value) : false; if ($timestamp === false || $timestamp <= 0) { return ['instance_detail.value.not_recorded', 0]; } $elapsed = max(0, time() - $timestamp); if ($elapsed < 60) { return ['instance_detail.created.just_now', 0]; } if ($elapsed < 3600) { return ['instance_detail.created.minutes_ago', intdiv($elapsed, 60)]; } if ($elapsed < 86400) { return ['instance_detail.created.hours_ago', intdiv($elapsed, 3600)]; } if ($elapsed < 2592000) { return ['instance_detail.created.days_ago', intdiv($elapsed, 86400)]; } return ['instance_detail.created.months_ago', intdiv($elapsed, 2592000)]; } private function serviceStatus(string $value): array { $labels = [ 'active' => ['instance_detail.service.active', 'active'], 'pending' => ['instance_detail.service.pending', 'warning'], 'renewing' => ['instance_detail.service.renewing', 'warning'], 'exempt' => ['instance_detail.service.exempt', 'active'], 'suspended_expired' => ['instance_detail.service.suspended_expired', 'stopped'], 'suspended_traffic' => ['instance_detail.service.suspended_traffic', 'stopped'], 'expired' => ['instance_detail.service.expired', 'stopped'], 'deleting' => ['instance_detail.service.deleting', 'warning'], 'purge_force_required' => ['instance_detail.service.purge_force_required', 'stopped'], 'purge_deleting' => ['instance_detail.service.deleting', 'warning'], 'delete_failed' => ['instance_detail.service.delete_failed', 'stopped'], ]; return $labels[strtolower(str_replace('-', '_', trim($value)))] ?? ['instance_detail.value.unavailable', 'unknown']; } private function networkStatus(string $value): array { $labels = [ 'active' => ['instance_detail.network.active', 'active'], 'blocking' => ['instance_detail.network.blocking', 'warning'], 'blocked_traffic' => ['instance_detail.network.blocked_traffic', 'stopped'], 'blocked_expired' => ['instance_detail.network.blocked_expired', 'stopped'], 'restoring' => ['instance_detail.network.restoring', 'warning'], 'restore_pending' => ['instance_detail.network.restore_pending', 'warning'], 'restore_failed' => ['instance_detail.network.restore_failed', 'stopped'], 'configuration_invalid' => ['instance_detail.network.configuration_invalid', 'stopped'], 'exempt' => ['instance_detail.network.exempt', 'active'], ]; return $labels[strtolower(str_replace('-', '_', trim($value)))] ?? ['instance_detail.value.unavailable', 'unknown']; } }