feat(web): localize public entry pages
parent
ad21830be5
commit
24faed1428
@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
final class PublicLocale
|
||||
{
|
||||
public const COOKIE_NAME = 'venix_public_locale';
|
||||
public const COOKIE_TTL = 31536000;
|
||||
public const ENGLISH = 'en';
|
||||
public const CHINESE = 'zh-CN';
|
||||
|
||||
public static function resolve(array $query, array $cookies, string $acceptLanguage): string
|
||||
{
|
||||
$requested = self::requestedLocale($query);
|
||||
if ($requested !== null) {
|
||||
return $requested;
|
||||
}
|
||||
|
||||
$cookieLocale = self::normalizeLocale($cookies[self::COOKIE_NAME] ?? null);
|
||||
if ($cookieLocale !== null) {
|
||||
return $cookieLocale;
|
||||
}
|
||||
|
||||
return self::browserLocale($acceptLanguage);
|
||||
}
|
||||
|
||||
public static function requestedLocale(array $query): ?string
|
||||
{
|
||||
return self::normalizeLocale($query['lang'] ?? null);
|
||||
}
|
||||
|
||||
public static function normalizeLocale($value): ?string
|
||||
{
|
||||
if (!is_string($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$locale = strtolower(str_replace('_', '-', trim($value)));
|
||||
if ($locale === 'zh' || str_starts_with($locale, 'zh-')) {
|
||||
return self::CHINESE;
|
||||
}
|
||||
if ($locale === 'en' || str_starts_with($locale, 'en-')) {
|
||||
return self::ENGLISH;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function browserLocale(string $acceptLanguage): string
|
||||
{
|
||||
$acceptLanguage = trim($acceptLanguage);
|
||||
if ($acceptLanguage === '') {
|
||||
return self::CHINESE;
|
||||
}
|
||||
|
||||
$supported = [];
|
||||
foreach (explode(',', $acceptLanguage) as $position => $entry) {
|
||||
$parts = array_map('trim', explode(';', $entry));
|
||||
$locale = self::normalizeLocale(array_shift($parts));
|
||||
if ($locale === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$quality = 1.0;
|
||||
foreach ($parts as $parameter) {
|
||||
if (stripos($parameter, 'q=') !== 0) {
|
||||
continue;
|
||||
}
|
||||
$qualityValue = substr($parameter, 2);
|
||||
$quality = is_numeric($qualityValue) ? (float) $qualityValue : 0.0;
|
||||
break;
|
||||
}
|
||||
if ($quality <= 0.0 || $quality > 1.0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$supported[] = [
|
||||
'locale' => $locale,
|
||||
'quality' => $quality,
|
||||
'position' => $position,
|
||||
];
|
||||
}
|
||||
|
||||
usort($supported, static function (array $left, array $right): int {
|
||||
if ($left['quality'] === $right['quality']) {
|
||||
return $left['position'] <=> $right['position'];
|
||||
}
|
||||
return $left['quality'] < $right['quality'] ? 1 : -1;
|
||||
});
|
||||
|
||||
return $supported[0]['locale'] ?? self::ENGLISH;
|
||||
}
|
||||
|
||||
public static function templateLanguage(string $locale): string
|
||||
{
|
||||
return self::normalizeLocale($locale) === self::ENGLISH ? 'true' : 'false';
|
||||
}
|
||||
|
||||
public static function switchUrl(string $locale, string $requestUri): string
|
||||
{
|
||||
$locale = self::normalizeLocale($locale) ?? self::CHINESE;
|
||||
$parts = parse_url($requestUri);
|
||||
if (!is_array($parts) || isset($parts['scheme']) || isset($parts['host'])) {
|
||||
$parts = ['path' => '/'];
|
||||
}
|
||||
$path = is_array($parts) && isset($parts['path']) ? (string) $parts['path'] : '/';
|
||||
if ($path === '' || $path[0] !== '/' || str_starts_with($path, '//')
|
||||
|| preg_match('/[\x00-\x1F\x7F]/', $path)) {
|
||||
$path = '/';
|
||||
}
|
||||
|
||||
$query = [];
|
||||
if (is_array($parts) && isset($parts['query'])) {
|
||||
parse_str((string) $parts['query'], $query);
|
||||
}
|
||||
$query['lang'] = $locale;
|
||||
|
||||
return $path . '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986);
|
||||
}
|
||||
|
||||
public static function viewData(string $locale, string $requestUri): array
|
||||
{
|
||||
$locale = self::normalizeLocale($locale) ?? self::CHINESE;
|
||||
|
||||
return [
|
||||
'public_locale' => $locale,
|
||||
'language' => self::templateLanguage($locale),
|
||||
'language_zh_url' => self::switchUrl(self::CHINESE, $requestUri),
|
||||
'language_en_url' => self::switchUrl(self::ENGLISH, $requestUri),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1 +0,0 @@
|
||||
<p class="auth-copyright">© 2026 {$auth_app_name|escape:"html"}. All rights reserved.</p>
|
||||
@ -0,0 +1,2 @@
|
||||
{include file='home/site_footer.tpl'}
|
||||
{include file='auth/layout_scripts.tpl'}
|
||||
@ -0,0 +1,4 @@
|
||||
<span class="landing-language-switch" role="group" aria-label="{if $language == 'true'}Choose language{else}选择语言{/if}">
|
||||
<a class="{if $language != 'true'}is-active{/if}" href="{$language_zh_url|escape:'html'}" lang="zh-CN" hreflang="zh-CN"{if $language != 'true'} aria-current="true"{/if}>中文</a>
|
||||
<a class="{if $language == 'true'}is-active{/if}" href="{$language_en_url|escape:'html'}" lang="en" hreflang="en"{if $language == 'true'} aria-current="true"{/if}>EN</a>
|
||||
</span>
|
||||
@ -0,0 +1,8 @@
|
||||
{include file='home/language_switch.tpl'}
|
||||
{if $user->isLogin}
|
||||
{if $user->isAdmin()}<a class="landing-nav-login" href="/admin">{if $language == 'true'}Admin{else}管理后台{/if}</a>{/if}
|
||||
<a class="landing-button landing-button-small landing-button-primary" href="/user">{if $language == 'true'}Open console{else}进入控制台{/if}<i class="mdi mdi-arrow-right" aria-hidden="true"></i></a>
|
||||
{else}
|
||||
<a class="landing-nav-login{if $home_active|default:'' == 'login' || $home_active|default:'' == 'password-reset' || $home_active|default:'' == 'password-token'} is-active{/if}" href="/auth/login">{if $language == 'true'}Log in{else}登录{/if}</a>
|
||||
<a class="landing-button landing-button-small landing-button-primary{if $home_active|default:'' == 'register'} is-active{/if}" href="/auth/register">{if $language == 'true'}Create account{else}创建账户{/if}<i class="mdi mdi-arrow-right" aria-hidden="true"></i></a>
|
||||
{/if}
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026102418' scope='global'}
|
||||
{assign var=venix_asset_version value='2026102419' scope='global'}
|
||||
|
||||
@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\PublicLocale;
|
||||
|
||||
$assertSame = static function ($expected, $actual, string $message): void {
|
||||
if ($expected !== $actual) {
|
||||
throw new RuntimeException($message . ' Expected ' . var_export($expected, true)
|
||||
. ', got ' . var_export($actual, true) . '.');
|
||||
}
|
||||
};
|
||||
|
||||
$assertSame(PublicLocale::ENGLISH, PublicLocale::resolve(
|
||||
['lang' => 'en-US'],
|
||||
[PublicLocale::COOKIE_NAME => 'zh-CN'],
|
||||
'zh-CN,zh;q=0.9'
|
||||
), 'An explicit English selection must override the cookie and browser preference.');
|
||||
$assertSame(PublicLocale::CHINESE, PublicLocale::resolve(
|
||||
['lang' => 'zh'],
|
||||
[PublicLocale::COOKIE_NAME => 'en'],
|
||||
'en-US,en;q=0.9'
|
||||
), 'An explicit Chinese selection must override the cookie and browser preference.');
|
||||
$assertSame(PublicLocale::ENGLISH, PublicLocale::resolve(
|
||||
[],
|
||||
[PublicLocale::COOKIE_NAME => 'en'],
|
||||
'zh-CN,zh;q=0.9'
|
||||
), 'A saved manual selection must override automatic browser detection.');
|
||||
$assertSame(PublicLocale::CHINESE, PublicLocale::resolve(
|
||||
[],
|
||||
[],
|
||||
'zh-CN,zh;q=0.9,en;q=0.8'
|
||||
), 'A Chinese browser preference was not detected.');
|
||||
$assertSame(PublicLocale::ENGLISH, PublicLocale::resolve(
|
||||
[],
|
||||
[],
|
||||
'en-US,en;q=0.9,zh;q=0.8'
|
||||
), 'An English browser preference was not detected.');
|
||||
$assertSame(PublicLocale::CHINESE, PublicLocale::resolve(
|
||||
[],
|
||||
[],
|
||||
'fr-FR,zh;q=0.8,en;q=0.6'
|
||||
), 'Unsupported languages must be skipped in favor of the best supported preference.');
|
||||
$assertSame(PublicLocale::ENGLISH, PublicLocale::resolve(
|
||||
[],
|
||||
[],
|
||||
'fr-FR,fr;q=0.9'
|
||||
), 'A non-Chinese browser with no supported preference must fall back to English.');
|
||||
$assertSame(PublicLocale::CHINESE, PublicLocale::resolve([], [], ''),
|
||||
'Requests without a browser language must retain the existing Chinese default.');
|
||||
$assertSame(PublicLocale::ENGLISH, PublicLocale::browserLocale('zh-CN;q=0,en;q=0.5'),
|
||||
'A language excluded with q=0 must not be selected.');
|
||||
|
||||
$englishUrl = PublicLocale::switchUrl('en', '/auth/register?aff=ABCDEFGH&source=landing');
|
||||
$assertSame('/auth/register?aff=ABCDEFGH&source=landing&lang=en', $englishUrl,
|
||||
'Language switching must preserve registration referral parameters.');
|
||||
$chineseUrl = PublicLocale::switchUrl('zh-CN', '/auth/register?aff=ABCDEFGH&lang=en');
|
||||
$assertSame('/auth/register?aff=ABCDEFGH&lang=zh-CN', $chineseUrl,
|
||||
'Language switching must replace, rather than duplicate, the current locale.');
|
||||
$assertSame('/?lang=en', PublicLocale::switchUrl('en', '//external.example/path?x=1'),
|
||||
'Language switching must never emit a protocol-relative external URL.');
|
||||
|
||||
$viewData = PublicLocale::viewData('en', '/password/reset?from=login');
|
||||
$assertSame('en', $viewData['public_locale'], 'The resolved public locale is missing from view data.');
|
||||
$assertSame('true', $viewData['language'], 'English must retain the legacy template language flag.');
|
||||
$assertSame('/password/reset?from=login&lang=zh-CN', $viewData['language_zh_url'],
|
||||
'The Chinese switch URL is incorrect.');
|
||||
$assertSame('/password/reset?from=login&lang=en', $viewData['language_en_url'],
|
||||
'The English switch URL is incorrect.');
|
||||
|
||||
echo "Public locale detection and switching tests passed.\n";
|
||||
@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
$root = dirname(__DIR__, 2);
|
||||
$read = static function (string $path) use ($root): string {
|
||||
$content = file_get_contents($root . '/' . $path);
|
||||
if ($content === false) {
|
||||
throw new RuntimeException('Cannot read ' . $path);
|
||||
}
|
||||
return $content;
|
||||
};
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$locale = $read('web/app/Services/PublicLocale.php');
|
||||
$base = $read('web/app/Controllers/BaseController.php');
|
||||
$home = $read('web/app/Controllers/HomeController.php');
|
||||
$auth = $read('web/app/Controllers/AuthController.php');
|
||||
$password = $read('web/app/Controllers/PasswordController.php');
|
||||
$legal = $read('web/app/Controllers/LegalController.php');
|
||||
|
||||
$assert(str_contains($locale, "COOKIE_NAME = 'venix_public_locale'")
|
||||
&& str_contains($locale, 'HTTP_ACCEPT_LANGUAGE') === false
|
||||
&& str_contains($locale, 'browserLocale(')
|
||||
&& str_contains($locale, "\$query['lang']"),
|
||||
'The public locale resolver is missing explicit selection, cookie, or browser-language support.');
|
||||
$assert(str_contains($base, 'PublicLocale::requestedLocale($query)')
|
||||
&& str_contains($base, 'Cookie::set([')
|
||||
&& str_contains($base, "\$_SERVER['HTTP_ACCEPT_LANGUAGE']")
|
||||
&& str_contains($base, 'PublicLocale::viewData('),
|
||||
'The shared controller does not persist and expose the resolved public locale.');
|
||||
foreach ([$home, $auth, $password] as $controller) {
|
||||
$assert(str_contains($controller, '$this->initializePublicLocale();'),
|
||||
'A public-page controller does not initialize the shared locale resolver.');
|
||||
$assert(str_contains($controller, '$this->publicView()'),
|
||||
'A public-page controller does not expose shared locale data to its templates.');
|
||||
}
|
||||
$assert(str_contains($legal, '$this->publicLocale')
|
||||
&& str_contains($legal, "withHeader('Vary', 'Accept-Language, Cookie')"),
|
||||
'Legal pages do not use the shared locale or declare cache variance.');
|
||||
foreach ([$base, $home, $auth, $password, $legal] as $controller) {
|
||||
$assert(!str_contains($controller, "Configurations::where('name', 'language'")
|
||||
&& !str_contains($controller, "Config::get('language'"),
|
||||
'A public page still depends on the removed administrator language setting.');
|
||||
}
|
||||
|
||||
$layoutHeader = $read('web/resources/views/venix/auth/layout_header.tpl');
|
||||
$layoutFooter = $read('web/resources/views/venix/auth/layout_footer.tpl');
|
||||
$siteHeader = $read('web/resources/views/venix/home/site_header.tpl');
|
||||
$navActions = $read('web/resources/views/venix/home/nav_actions.tpl');
|
||||
$languageSwitch = $read('web/resources/views/venix/home/language_switch.tpl');
|
||||
$siteFooter = $read('web/resources/views/venix/home/site_footer.tpl');
|
||||
$css = $read('web/public/theme/venix/css/home.css');
|
||||
$accountCss = $read('web/public/cloud/account.css');
|
||||
|
||||
$assert(str_contains($layoutHeader, "include file='home/site_header.tpl'")
|
||||
&& str_contains($layoutHeader, 'theme/venix/css/home.css'),
|
||||
'Authentication pages do not reuse the landing-page header and its stylesheet.');
|
||||
$assert(str_contains($layoutFooter, "include file='home/site_footer.tpl'"),
|
||||
'Authentication pages do not reuse the landing-page footer.');
|
||||
foreach (['auth/login.tpl', 'auth/register.tpl', 'password/reset.tpl', 'password/token.tpl'] as $templatePath) {
|
||||
$template = $read('web/resources/views/venix/' . $templatePath);
|
||||
$assert(str_contains($template, "include file='auth/layout_footer.tpl'"),
|
||||
$templatePath . ' does not include the persistent public footer.');
|
||||
$assert(!str_contains($template, "include file='auth/copyright.tpl'"),
|
||||
$templatePath . ' still includes the retired local copyright fragment.');
|
||||
}
|
||||
$assert(str_contains($siteHeader, "include file='home/nav_actions.tpl'")
|
||||
&& str_contains($navActions, "include file='home/language_switch.tpl'")
|
||||
&& str_contains($languageSwitch, '$language_zh_url')
|
||||
&& str_contains($languageSwitch, '$language_en_url'),
|
||||
'The shared navigation does not expose both language switch targets.');
|
||||
$assert(!str_contains($siteHeader, '?lang=en') && !str_contains($siteFooter, '?lang=en'),
|
||||
'Public navigation still hard-codes English query parameters instead of using the locale cookie.');
|
||||
$assert(preg_match('/\.landing-site-header\s*\{[^}]*position:\s*fixed;/s', $css) === 1
|
||||
&& str_contains($css, '.landing-language-switch')
|
||||
&& str_contains($css, '.landing-mobile-nav-actions')
|
||||
&& str_contains($accountCss, 'padding-top: 88px;')
|
||||
&& str_contains($accountCss, 'padding-top: 76px;'),
|
||||
'Persistent desktop or mobile public-navigation styling is incomplete.');
|
||||
$assert(str_contains($read('web/resources/views/venix/layout_assets.tpl'), "value='2026102419'"),
|
||||
'The shared browser asset version was not advanced with the navigation styles.');
|
||||
|
||||
echo "Public page locale and shared-layout contract tests passed.\n";
|
||||
@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\PublicLocale;
|
||||
|
||||
final class PublicPageGuestForLocaleTest
|
||||
{
|
||||
public bool $isLogin = false;
|
||||
|
||||
public function isAdmin(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$directory = sys_get_temp_dir() . '/virt-public-locale-render-' . bin2hex(random_bytes(8));
|
||||
if (!mkdir($directory, 0700)) {
|
||||
throw new RuntimeException('Cannot create private public-page render directory.');
|
||||
}
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$smarty = new Smarty();
|
||||
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
|
||||
$smarty->setCompileDir($directory);
|
||||
$smarty->setCacheDir($directory);
|
||||
foreach (['urlencode', 'number_format', 'date'] as $modifier) {
|
||||
$smarty->registerPlugin('modifier', $modifier, $modifier);
|
||||
}
|
||||
$smarty->assign([
|
||||
'appName' => 'Locale Test Cloud',
|
||||
'config' => [
|
||||
'appName' => 'Locale Test Cloud',
|
||||
'jump_delay' => 500,
|
||||
],
|
||||
'cdn' => '',
|
||||
'backup_cdn' => '',
|
||||
'seo' => '',
|
||||
'user' => new PublicPageGuestForLocaleTest(),
|
||||
'captch_login' => 'false',
|
||||
'captch_reg' => 'false',
|
||||
'captch_respass' => 'false',
|
||||
'enable_invite_code' => 'false',
|
||||
'enable_email_verify' => 'false',
|
||||
'invite_required' => false,
|
||||
'tos_reg' => 'true',
|
||||
'code' => '',
|
||||
'aff_code' => '',
|
||||
'aff' => 0,
|
||||
'aff_method' => '',
|
||||
'token' => str_repeat('a', 64),
|
||||
]);
|
||||
|
||||
$pages = [
|
||||
'index.tpl' => ['Your cloud resources', '你的云资源'],
|
||||
'auth/login.tpl' => ['Log in to your account', '登录账户'],
|
||||
'auth/register.tpl' => ['Create your account', '注册新账户'],
|
||||
'password/reset.tpl' => ['Request a password reset', '重置密码请求'],
|
||||
'password/token.tpl' => ['Enter and confirm your new password.', '输入并确认你的新密码。'],
|
||||
];
|
||||
|
||||
try {
|
||||
foreach ([PublicLocale::ENGLISH, PublicLocale::CHINESE] as $locale) {
|
||||
$smarty->assign(PublicLocale::viewData($locale, '/auth/register?aff=ABCDEFGH'));
|
||||
$expectedFlag = $locale === PublicLocale::ENGLISH ? 0 : 1;
|
||||
foreach ($pages as $template => $copy) {
|
||||
$html = $smarty->fetch($template);
|
||||
$assert(str_contains($html, '<html lang="' . $locale . '">'),
|
||||
$template . ' rendered the wrong HTML language for ' . $locale . '.');
|
||||
$assert(str_contains($html, $copy[$expectedFlag]),
|
||||
$template . ' did not render its ' . $locale . ' copy.');
|
||||
$assert(substr_count($html, 'class="landing-site-header"') === 1,
|
||||
$template . ' did not render exactly one shared site header.');
|
||||
$assert(substr_count($html, 'class="landing-site-footer"') === 1,
|
||||
$template . ' did not render exactly one shared site footer.');
|
||||
$assert(str_contains($html, 'lang="zh-CN" hreflang="zh-CN"')
|
||||
&& str_contains($html, 'lang="en" hreflang="en"'),
|
||||
$template . ' is missing one of the language switch links.');
|
||||
$assert(str_contains($html, 'aff=ABCDEFGH&lang=en')
|
||||
&& str_contains($html, 'aff=ABCDEFGH&lang=zh-CN'),
|
||||
$template . ' did not preserve query parameters in language switch links.');
|
||||
$assert(str_contains($html, '© 2026 Locale Test Cloud. All rights reserved.'),
|
||||
$template . ' is missing the persistent dynamic copyright footer.');
|
||||
$assert(!str_contains($html, 'auth-site-nav') && !str_contains($html, 'auth-copyright'),
|
||||
$template . ' rendered a retired authentication-only header or footer.');
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$generatedFiles = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::CHILD_FIRST
|
||||
);
|
||||
foreach ($generatedFiles as $generated) {
|
||||
if ($generated->isFile()) {
|
||||
unlink($generated->getPathname());
|
||||
} elseif ($generated->isDir()) {
|
||||
rmdir($generated->getPathname());
|
||||
}
|
||||
}
|
||||
rmdir($directory);
|
||||
}
|
||||
|
||||
echo "Public landing and authentication pages rendered in Chinese and English.\n";
|
||||
Loading…
Reference in New Issue