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/tests/AdminAnnouncementsViewTest.php

208 lines
14 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
if ((error_reporting() & $severity) && ($severity & (E_WARNING | E_USER_WARNING | E_DEPRECATED))) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
return false;
});
// Synthetic DTOs only; template fixtures never bootstrap the application or query a database.
$announcement = ['id' => '41', 'title' => '香港区域网络维护通知', 'type' => 'maintenance',
'type_label' => '维护', 'body' => "维护时间:2026 年 10 月 2 日 02:00—03:00。\n期间网络可能短暂中断。\n维护完成后将更新本公告。",
'status' => 'published', 'published_at' => '2026-09-30 09:30:00', 'updated_at' => '2026-09-30 10:15:00'];
$withdrawn = array_replace($announcement, ['id' => '42', 'title' => '故障处理进展',
'type' => 'incident', 'type_label' => '故障', 'body' => "当前服务已恢复。\n此公告已撤下,仅后台保留。", 'status' => 'withdrawn']);
$notice = array_replace($announcement, ['id' => '43', 'title' => '控制面板功能更新',
'type' => 'notice', 'type_label' => '通知', 'body' => '账单和任务记录现已支持筛选与分页。']);
$newAnnouncement = ['id' => '', 'title' => '', 'type' => 'notice', 'type_label' => '通知',
'body' => '', 'status' => 'published', 'published_at' => null, 'updated_at' => ''];
$page = ['items' => [$announcement, $withdrawn, $notice],
'pagination' => ['page' => 2, 'per_page' => 20, 'total' => 65, 'total_pages' => 4],
'filters' => ['q' => '', 'type' => 'all', 'status' => 'all', 'page' => 2, 'per_page' => 20]];
$smarty = new Smarty();
$compileDir = sys_get_temp_dir() . '/admin-announcements-view-' . bin2hex(random_bytes(6));
mkdir($compileDir);
$smarty->setCompileDir($compileDir);
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
$smarty->assign('config', ['appName' => 'Venix Test']);
$smarty->assign('cdn', '');
$smarty->assign('user', (object) ['isLogin' => false]);
$smarty->assign('admin_csrf_token', str_repeat('a', 64));
$render = static function (string $view, ?array $data, ?bool $manage = true,
string $error = '', ?bool $announcementManage = null) use ($smarty): string {
if ($manage === null) {
$smarty->clearAssign('admin_can_manage');
} else {
$smarty->assign('admin_can_manage', $manage);
}
if ($announcementManage === null) {
$smarty->clearAssign('announcement_can_manage');
} else {
$smarty->assign('announcement_can_manage', $announcementManage);
}
$smarty->assign('announcements_page', $view === 'index' ? $data : null);
$smarty->assign('announcements_error', $error);
$smarty->assign('announcement', $view === 'index' ? null : $data);
return $smarty->fetch('admin/announcement/' . $view . '.tpl');
};
$html = $render('index', $page);
$createHtml = $render('create', $newAnnouncement);
$editHtml = $render('edit', $announcement);
$withdrawnHtml = $render('edit', $withdrawn);
$readOnlyHtml = $render('index', $page, false);
$failedHtml = $render('index', null, true, '公告数据暂不可用,请稍后重试');
$empty = $page;
$empty['items'] = [];
$empty['pagination'] = ['page' => 1, 'per_page' => 20, 'total' => 0, 'total_pages' => 1];
$emptyHtml = $render('index', $empty);
if (in_array('--fixture', $argv ?? [], true)) {
echo json_encode(['html' => $html, 'create_html' => $createHtml, 'edit_html' => $editHtml,
'readonly_html' => $readOnlyHtml, 'withdrawn_html' => $withdrawnHtml,
'failed_html' => $failedHtml, 'empty_html' => $emptyHtml,
'page' => $page, 'announcement' => $announcement],
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR);
exit;
}
$assert = static function (bool $condition, string $message): void {
if (!$condition) throw new RuntimeException($message);
};
$parse = static function (string $html): DOMXPath {
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
return new DOMXPath($dom);
};
$one = static function (DOMXPath $xpath, string $query) use ($assert): DOMElement {
$matches = $xpath->query($query);
$assert($matches->length === 1 && $matches->item(0) instanceof DOMElement,
'Expected one element matching ' . $query);
return $matches->item(0);
};
foreach ([$html, $createHtml, $editHtml, $readOnlyHtml, $failedHtml, $emptyHtml] as $rendered) {
$xpath = $parse($rendered);
$assert($xpath->query('//script[contains(@src,"admin-announcements.js")]')->length === 1
&& $xpath->query('//script[contains(@src,"admin-csrf.js")]')->length === 1,
'Announcements must load the shared interaction and existing CSRF scripts once.');
$assert($xpath->query('//script[contains(@src,"editor/")] | //link[contains(@href,"editor/")]')->length === 0
&& !str_contains($rendered, 'editormd')
&& $xpath->query('//*[@name="content" or @name="markdown"]')->length === 0,
'A retired editor dependency or generated HTML/Markdown field survived.');
$assert($xpath->query('//*[@data-delete or @id="deleteModal" or @id="annDeleteConfirm"]')->length === 0,
'A hard-delete control survived the withdraw-only workflow.');
}
$index = $parse($html);
$assert($index->query('//tbody[@id="announcement-rows"]/tr[@data-ann-row]')->length === 3
&& $index->query('//tbody//details')->length === 3,
'Announcements and complete expandable bodies must render on the server.');
$assert($one($index, '//tr[@data-ann-row="41"]//details/p')->textContent === $announcement['body']
&& $one($index, '//tr[@data-ann-row="42"]//button[@data-ann-status-button]')->getAttribute('data-ann-next-status') === 'published'
&& $one($index, '//tr[@data-ann-row="41"]//button[@data-ann-status-button]')->getAttribute('data-ann-next-status') === 'withdrawn',
'Body content or publish/withdraw targets diverged from the server DTO.');
$assert($one($index, '//form[@id="announcement-filter"]')->getAttribute('method') === 'get'
&& $one($index, '//form[@id="announcement-filter"]')->getAttribute('action') === '/admin/announcement',
'Filters must remain real server-side GET navigation.');
foreach (['prev' => '1', 'next' => '3'] as $relation => $number) {
$link = $one($index, '//nav[@aria-label="公告列表分页"]/a[@rel="' . $relation . '"]');
parse_str(parse_url($link->getAttribute('href'), PHP_URL_QUERY), $query);
$assert($query === ['q' => '', 'type' => 'all', 'status' => 'all', 'per_page' => '20', 'page' => $number],
'SSR pagination dropped filters or linked to the wrong page.');
}
$filtered = $page;
$filtered['filters'] = ['q' => '维护 & "引号"', 'type' => 'maintenance', 'status' => 'withdrawn', 'page' => 2, 'per_page' => 50];
$filtered['pagination']['per_page'] = 50;
$filteredDom = $parse($render('index', $filtered));
foreach (['type' => 'maintenance', 'status' => 'withdrawn', 'per_page' => '50'] as $name => $value) {
$assert($one($filteredDom, '//select[@name="' . $name . '"]/option[@selected]')->getAttribute('value') === $value,
'SSR selected filter did not match normalized input: ' . $name);
}
parse_str(parse_url($one($filteredDom, '//a[@rel="next"]')->getAttribute('href'), PHP_URL_QUERY), $query);
$assert($query['q'] === $filtered['filters']['q'] && $query['type'] === 'maintenance'
&& $query['status'] === 'withdrawn' && $query['per_page'] === '50',
'Quoted search text or filters did not round-trip through the pagination URL.');
foreach ([[$createHtml, 'POST', '/admin/announcement', $newAnnouncement],
[$editHtml, 'PUT', '/admin/announcement/41', $announcement],
[$withdrawnHtml, 'PUT', '/admin/announcement/42', $withdrawn]] as [$rendered, $method, $url, $dto]) {
$xpath = $parse($rendered);
$form = $one($xpath, '//form[@id="announcement-form"]');
$assert($form->getAttribute('action') === $url && $form->getAttribute('data-method') === $method,
'Announcement save method or resource URL changed.');
$names = [];
foreach ($xpath->query('//form[@id="announcement-form"]//*[@name]') as $input) $names[] = $input->getAttribute('name');
sort($names);
$assert($names === ['body', 'status', 'title', 'type'], 'Form submits fields outside the plain-text contract.');
foreach (['title' => '120', 'body' => '20000'] as $name => $maximum) {
$input = $one($xpath, '//*[@id="announcement-' . $name . '"]');
$assert($input->hasAttribute('required') && $input->getAttribute('maxlength') === $maximum,
'Missing required field or length limit: ' . $name);
$assert($one($xpath, '//label[@for="announcement-' . $name . '"]')->textContent !== '',
'An announcement control lost its label.');
}
$assert($one($xpath, '//input[@name="title"]')->getAttribute('value') === $dto['title']
&& $one($xpath, '//textarea[@name="body"]')->textContent === $dto['body']
&& $one($xpath, '//input[@name="status"]')->getAttribute('value') === $dto['status'],
'Initial title/body or the original publication state was lost.');
$types = [];
foreach ($xpath->query('//select[@name="type"]/option') as $option) $types[] = $option->getAttribute('value');
$assert($types === ['notice', 'maintenance', 'incident']
&& $one($xpath, '//select[@name="type"]/option[@selected]')->getAttribute('value') === $dto['type'],
'Announcement types or the selected value do not match the backend enum.');
$submit = $one($xpath, '//button[@id="announcement-submit"]');
$assert($submit->getAttribute('form') === 'announcement-form' && !$submit->hasAttribute('disabled')
&& $submit->getAttribute('type') === 'submit', 'External save button lost its form ownership.');
}
foreach ([false, null] as $permission) {
$restricted = $parse($render('index', $page, $permission));
$assert($restricted->query('//main//a[contains(@href,"/edit") or contains(@href,"/create")]')->length === 0
&& $restricted->query('//main//*[@data-ann-status-button]')->length === 0
&& $restricted->query('//main//details')->length === 3,
'Read-only administrators must read full bodies without edit/create/status controls.');
$restrictedForm = $parse($render('edit', $announcement, $permission));
$assert($one($restrictedForm, '//button[@id="announcement-submit"]')->hasAttribute('disabled')
&& $one($restrictedForm, '//button[@data-ann-status-button]')->hasAttribute('disabled')
&& $one($restrictedForm, '//textarea[@name="body"]')->hasAttribute('readonly')
&& $one($restrictedForm, '//select[@name="type"]')->hasAttribute('disabled'),
'Missing or read-only management permission unexpectedly enabled editing.');
}
$restrictedOverride = $parse($render('edit', $announcement, true, '', false));
$assert($one($restrictedOverride, '//button[@id="announcement-submit"]')->hasAttribute('disabled'),
'Explicit announcement permission denial was overridden by the general administrator flag.');
$unsafeText = '</textarea><img src=x onerror=alert(1)><script>window.__announcementUnsafe=1</script> & "公告"';
$unsafeDto = array_replace($announcement, ['title' => $unsafeText, 'body' => $unsafeText . "\n下一行", 'type_label' => $unsafeText]);
$unsafeForm = $parse($render('edit', $unsafeDto));
$assert($one($unsafeForm, '//textarea[@name="body"]')->textContent === $unsafeDto['body']
&& $one($unsafeForm, '//input[@name="title"]')->getAttribute('value') === $unsafeText
&& $unsafeForm->query('//*[@onerror]')->length === 0,
'Plain announcement text escaped its form control and became executable markup.');
$unsafePage = $page;
$unsafePage['items'] = [$unsafeDto];
$unsafePage['filters']['q'] = '\" autofocus onfocus=alert(2)';
$unsafeListHtml = $render('index', $unsafePage);
$unsafeList = $parse($unsafeListHtml);
$assert($unsafeList->query('//*[@onerror or @onfocus]')->length === 0
&& $one($unsafeList, '//tbody//details/p')->textContent === $unsafeDto['body']
&& !str_contains($unsafeListHtml, '<script>window.__announcementUnsafe=1</script>'),
'List summaries, labels, search or expanded bodies were not escaped.');
$assert(str_contains($emptyHtml, '没有符合条件的公告。') && !str_contains($emptyHtml, '香港区域网络维护通知')
&& $parse($emptyHtml)->query('//nav[@aria-label="公告列表分页"]')->length === 0,
'Empty results show stale announcements or invalid pagination.');
$assert(str_contains($failedHtml, '公告数据暂不可用,请稍后重试')
&& $one($parse($failedHtml), '//*[@id="announcement-total"]')->textContent === '数据未获取'
&& !str_contains($failedHtml, '共 0 条'), 'An unavailable list was falsely rendered as successful empty data.');
$script = file_get_contents(dirname(__DIR__) . '/public/theme/venix/js/admin-announcements.js');
$assert(str_contains($script, "root.dataset.annCanManage === '1'")
&& !str_contains($script, 'window.ADMIN_CAN_MANAGE')
&& str_contains($script, "payload.set('title', title)")
&& str_contains($script, "payload.set('body', body)")
&& str_contains($script, "'/admin/announcement/' + id + '/status'")
&& !str_contains($script, 'innerHTML') && !str_contains($script, "'DELETE'")
&& !str_contains($script, 'getHTML') && !str_contains($script, 'getMarkdown')
&& !str_contains($script, '/announcement/ajax'),
'Client regressed permissions, plain-text writes, status endpoint or server-side pagination.');
echo "Administrator announcements real Smarty plain-text forms, SSR pagination, publication states, read-only controls and escaping passed.\n";