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

193 lines
6.8 KiB
PHP

<?php
namespace App\Services\UserCopy;
use App\Services\PublicLocale;
use App\Utils\Cookie;
use Smarty;
/**
* User-page runtime seam for locale selection, Smarty copy and browser data.
*
* The implementation reads only the immutable runtime catalog and the
* source-owned Chinese fallback. Target-locale copy never lives in source.
*/
final class UserCopyViewRuntime
{
/** @var list<array{locale:string,display_name:string,source:bool}>|null */
private ?array $availableLocalesCache = null;
public function __construct(private readonly UserCopyRuntimeReader $reader)
{
}
public static function production(): self
{
$webRoot = dirname(__DIR__, 3);
$source = new UserCopySourceCatalog(UserCopyManifest::load());
return new self(new UserCopyRuntimeReader(
$webRoot . '/storage/framework/user-copy',
$source
));
}
public function bindCurrentRequest(
Smarty $smarty,
?string $page = null
): UserCopyCatalog {
$locale = $this->resolveCurrentRequestLocale();
$requestUri = isset($_SERVER['REQUEST_URI'])
? (string) $_SERVER['REQUEST_URI'] : '/';
return $this->bind($smarty, $locale, $requestUri, $page);
}
/** @return list<array{locale:string,display_name:string,source:bool}> */
public function availableLocales(): array
{
return $this->availableLocalesCache ??=
$this->reader->availableLocales();
}
public function resolveCurrentRequestLocale(): string
{
$query = is_array($_GET) ? $_GET : [];
$cookies = is_array($_COOKIE) ? $_COOKIE : [];
$available = $this->availableLocales();
$requested = PublicLocale::requestedLocale($query, $available);
if ($requested !== null) {
Cookie::set([
PublicLocale::COOKIE_NAME => $requested,
], time() + PublicLocale::COOKIE_TTL);
$cookies[PublicLocale::COOKIE_NAME] = $requested;
}
$locale = PublicLocale::resolve(
$query,
$cookies,
isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])
? (string) $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '',
$available
);
return $locale;
}
public function bind(
Smarty $smarty,
string $locale,
string $requestUri,
?string $page = null
): UserCopyCatalog {
$available = $this->availableLocales();
$locale = PublicLocale::normalizeLocale($locale, $available)
?? PublicLocale::CHINESE;
$catalog = $page === null
? new UserCopyCatalog($this->reader, $locale, ['common'])
: UserCopyCatalog::forPage($this->reader, $locale, $page);
$snapshot = $catalog->catalog();
$bootstrap = json_encode([
'schema' => 1,
'locale' => $catalog->locale(),
'generation' => $catalog->generation(),
'messages' => $snapshot['messages'],
'metadata' => $snapshot['metadata'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
| JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_THROW_ON_ERROR);
$pageKey = is_string($page) ? trim($page) : '';
$csrfToken = trim((string) $smarty->getTemplateVars(
'admin_csrf_token'
));
$canAuthor = (bool) $smarty->getTemplateVars('admin_can_manage');
$editorEnabled = $canAuthor
&& $pageKey !== ''
&& preg_match('/\A[a-f0-9]{64}\z/D', $csrfToken) === 1;
$editorBootstrap = $editorEnabled ? json_encode([
'schema' => 1,
'page' => $pageKey,
'runtime_locale' => $catalog->locale(),
'csrf_token' => $csrfToken,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
| JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_THROW_ON_ERROR) : '{}';
$languages = array_map(
static fn (array $language): array => [
'locale' => $language['locale'],
'display_name' => $language['display_name'],
'source' => $language['source'],
'url' => PublicLocale::switchUrl(
$language['locale'],
$requestUri
),
'active' => $language['locale'] === $catalog->locale(),
],
$available
);
$smarty->assign([
'user_copy_locale' => $catalog->locale(),
'user_copy_generation' => $catalog->generation(),
'user_copy_bootstrap_json' => $bootstrap,
'user_copy_page' => $pageKey,
'user_copy_editor_enabled' => $editorEnabled,
'user_copy_editor_bootstrap_json' => $editorBootstrap,
'user_copy_languages' => $languages,
'user_copy_language_zh_url' => PublicLocale::switchUrl(
PublicLocale::CHINESE,
$requestUri
),
'user_copy_language_en_url' => PublicLocale::switchUrl(
PublicLocale::ENGLISH,
$requestUri
),
]);
$smarty->unregisterPlugin('function', 'user_copy');
$smarty->registerPlugin(
'function',
'user_copy',
static function (array $parameters) use ($catalog): string {
$key = isset($parameters['key'])
? (string) $parameters['key'] : '';
unset($parameters['key']);
return htmlspecialchars(
$catalog->text($key, $parameters),
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
);
}
);
$messages = is_array($snapshot['messages'] ?? null)
? $snapshot['messages'] : [];
$smarty->unregisterPlugin('function', 'user_copy_binding');
$smarty->registerPlugin(
'function',
'user_copy_binding',
static function (array $parameters) use (
$canAuthor,
$messages
): string {
$key = isset($parameters['key'])
? (string) $parameters['key'] : '';
if (preg_match(
'/\A[a-z0-9][a-z0-9._-]{1,190}\z/D',
$key
) !== 1 || !array_key_exists($key, $messages)) {
throw new UserCopyCatalogException(
'Unknown user copy binding key: ' . $key
);
}
if (!$canAuthor) {
return '';
}
return ' data-user-copy-key="' . htmlspecialchars(
$key,
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
) . '"';
}
);
return $catalog;
}
}