feat(multi-language): Add multi-language support and routing updates
Add configuration for multiple languages in the Website Manager
This commit is contained in:
@@ -13,6 +13,14 @@ Plugi is a website boilerplate with a drag-and-drop page builder.
|
|||||||
|
|
||||||
See the [Plugi documentation](https://plugi.paulspenke.com/) for the full installation guide, including manual deployment, Docker development, security, and troubleshooting.
|
See the [Plugi documentation](https://plugi.paulspenke.com/) for the full installation guide, including manual deployment, Docker development, security, and troubleshooting.
|
||||||
|
|
||||||
|
## Multilingual pages
|
||||||
|
|
||||||
|
In Website Manager settings, enable the languages the site should use and select a default site language from that enabled list. Older installations without a saved `default_language` continue to use their saved `admin_language` value until a default is saved.
|
||||||
|
|
||||||
|
Each page translation has its own editable route. New routes use `/slug` for the default language and `/{locale}/slug` for other enabled languages. Saving a changed route adds a leading slash, removes trailing and repeated slashes (except `/`), and lowercases static path segments; route matching also ignores case and slash variants. Named parameters such as `{id}` and a trailing `*` wildcard remain supported.
|
||||||
|
|
||||||
|
Changing the default language affects new route suggestions but does not rewrite existing page URLs. Disabling a language makes its routes unavailable publicly while keeping its translations; re-enabling it restores those routes. See the [Plugi documentation](https://plugi.paulspenke.com/) for the full guide.
|
||||||
|
|
||||||
## Local Docker development
|
## Local Docker development
|
||||||
|
|
||||||
The supplied Compose stack uses PHP 8.4 and MySQL 8.0 and is for local development only. Copy `.env.dist` to `.env` and `config.dist.php` to `config.php`, replace the sample database and MySQL root passwords, then run:
|
The supplied Compose stack uses PHP 8.4 and MySQL 8.0 and is for local development only. Copy `.env.dist` to `.env` and `config.dist.php` to `config.php`, replace the sample database and MySQL root passwords, then run:
|
||||||
|
|||||||
@@ -67,7 +67,9 @@ return [
|
|||||||
'required' => 'Pflichtfeld',
|
'required' => 'Pflichtfeld',
|
||||||
'website-languages' => 'Website Sprachen',
|
'website-languages' => 'Website Sprachen',
|
||||||
'languages-selector-placeholder' => 'Wähle eine oder mehr Sprachen aus',
|
'languages-selector-placeholder' => 'Wähle eine oder mehr Sprachen aus',
|
||||||
'admin-language' => 'Admin Sprache',
|
'default-language' => 'Standardsprache der Website',
|
||||||
|
'default-language-requires-enabled' => 'Die Standardsprache muss oben ebenfalls aktiviert sein.',
|
||||||
|
'invalid-default-language' => 'Die Standardsprache muss in der Liste der Website-Sprachen aktiviert sein.',
|
||||||
'selected-theme' => 'Ausgewähltes Template',
|
'selected-theme' => 'Ausgewähltes Template',
|
||||||
'save-settings' => 'Einstellungen speichern',
|
'save-settings' => 'Einstellungen speichern',
|
||||||
'settings-updated' => 'Einstellungen aktualisiert',
|
'settings-updated' => 'Einstellungen aktualisiert',
|
||||||
|
|||||||
@@ -67,7 +67,9 @@ return [
|
|||||||
'required' => 'Required',
|
'required' => 'Required',
|
||||||
'website-languages' => 'Website languages',
|
'website-languages' => 'Website languages',
|
||||||
'languages-selector-placeholder' => 'Select one or more languages',
|
'languages-selector-placeholder' => 'Select one or more languages',
|
||||||
'admin-language' => 'Admin Language',
|
'default-language' => 'Default site language',
|
||||||
|
'default-language-requires-enabled' => 'The default language must also be enabled above.',
|
||||||
|
'invalid-default-language' => 'The default language must be enabled in the website languages list.',
|
||||||
'selected-theme' => 'Selected theme',
|
'selected-theme' => 'Selected theme',
|
||||||
'save-settings' => 'Save settings',
|
'save-settings' => 'Save settings',
|
||||||
'settings-updated' => 'Settings successfully updated',
|
'settings-updated' => 'Settings successfully updated',
|
||||||
|
|||||||
@@ -66,7 +66,9 @@ return [
|
|||||||
'required' => 'Obligatoriskt',
|
'required' => 'Obligatoriskt',
|
||||||
'website-languages' => 'Webbplatsspråk',
|
'website-languages' => 'Webbplatsspråk',
|
||||||
'languages-selector-placeholder' => 'Välj ett eller flera språk',
|
'languages-selector-placeholder' => 'Välj ett eller flera språk',
|
||||||
'admin-language' => 'Administratörsspråk',
|
'default-language' => 'Webbplatsens standardspråk',
|
||||||
|
'default-language-requires-enabled' => 'Standardspråket måste också vara aktiverat ovan.',
|
||||||
|
'invalid-default-language' => 'Standardspråket måste vara aktiverat i listan över webbplatsspråk.',
|
||||||
'selected-theme' => 'Valt tema',
|
'selected-theme' => 'Valt tema',
|
||||||
'save-settings' => 'Spara inställningar',
|
'save-settings' => 'Spara inställningar',
|
||||||
'settings-updated' => 'Inställningarna har uppdaterats',
|
'settings-updated' => 'Inställningarna har uppdaterats',
|
||||||
|
|||||||
@@ -281,10 +281,15 @@ if (! function_exists('phpb_current_relative_url')) {
|
|||||||
|
|
||||||
if (! function_exists('phpb_current_language')) {
|
if (! function_exists('phpb_current_language')) {
|
||||||
/**
|
/**
|
||||||
* Give the current language based on the current URL.
|
* Give the resolved request language or fall back to the current URL and site default.
|
||||||
*/
|
*/
|
||||||
function phpb_current_language(): string
|
function phpb_current_language(): string
|
||||||
{
|
{
|
||||||
|
global $phpb_request_language;
|
||||||
|
if (isset($phpb_request_language) && is_string($phpb_request_language)) {
|
||||||
|
return $phpb_request_language;
|
||||||
|
}
|
||||||
|
|
||||||
$urlComponents = explode('/', phpb_current_relative_url());
|
$urlComponents = explode('/', phpb_current_relative_url());
|
||||||
// remove empty values and reset array key numbering
|
// remove empty values and reset array key numbering
|
||||||
$urlComponents = array_values(array_filter($urlComponents));
|
$urlComponents = array_values(array_filter($urlComponents));
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace Plugi\Modules\Router;
|
|||||||
use Plugi\Contracts\PageContract;
|
use Plugi\Contracts\PageContract;
|
||||||
use Plugi\Contracts\PageTranslationContract;
|
use Plugi\Contracts\PageTranslationContract;
|
||||||
use Plugi\Contracts\RouterContract;
|
use Plugi\Contracts\RouterContract;
|
||||||
|
use Plugi\PageTranslationService;
|
||||||
use Plugi\Repositories\PageRepository;
|
use Plugi\Repositories\PageRepository;
|
||||||
use Plugi\Repositories\PageTranslationRepository;
|
use Plugi\Repositories\PageTranslationRepository;
|
||||||
|
|
||||||
@@ -49,23 +50,46 @@ class DatabasePageRouter implements RouterContract
|
|||||||
*/
|
*/
|
||||||
public function resolve($url)
|
public function resolve($url)
|
||||||
{
|
{
|
||||||
// strip URL query parameters
|
$this->routeParameters = [];
|
||||||
$url = explode('?', $url, 2)[0];
|
$this->routeToPageTranslationIdMapping = [];
|
||||||
// split URL into segments using / as separator
|
$translationService = new PageTranslationService();
|
||||||
|
$url = preg_split('/[?#]/', $url, 2)[0] ?? '';
|
||||||
|
$url = preg_replace('#/+#', '/', '/' . trim($url, '/')) ?: '/';
|
||||||
$urlSegments = explode('/', $url);
|
$urlSegments = explode('/', $url);
|
||||||
|
|
||||||
// request all routes and convert each to its segments using / as separator
|
$activeLanguages = phpb_active_languages();
|
||||||
$pageTranslations = $this->pageTranslationRepository->getAll(['id', 'route']);
|
$pageTranslations = $this->pageTranslationRepository->getAll(['id', 'route', 'locale']);
|
||||||
$routes = [];
|
$routes = [];
|
||||||
foreach ($pageTranslations as $pageTranslation) {
|
foreach ($pageTranslations as $pageTranslation) {
|
||||||
$route = $pageTranslation->route;
|
if (! array_key_exists($pageTranslation->locale, $activeLanguages)) {
|
||||||
$this->routeToPageTranslationIdMapping[$route] = $pageTranslation->id;
|
continue;
|
||||||
$routeSegments = explode('/', $route);
|
}
|
||||||
$routes[] = $routeSegments;
|
if (! is_string($pageTranslation->route) || trim($pageTranslation->route) === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$route = $translationService->normalizeRoute($pageTranslation->route);
|
||||||
|
$routeKey = $translationService->getRouteKey($route);
|
||||||
|
if (isset($routes[$routeKey])) {
|
||||||
|
$routes[$routeKey] = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$routes[$routeKey] = [
|
||||||
|
'route' => $route,
|
||||||
|
'translationId' => $pageTranslation->id,
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
// sort routes into the order for evaluation
|
$routeSegments = [];
|
||||||
$orderedRoutes = $this->getRoutesInOrder($routes);
|
foreach ($routes as $route) {
|
||||||
|
if ($route === false) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$this->routeToPageTranslationIdMapping[$route['route']] = $route['translationId'];
|
||||||
|
$routeSegments[] = explode('/', $route['route']);
|
||||||
|
}
|
||||||
|
$orderedRoutes = $this->getRoutesInOrder($routeSegments);
|
||||||
|
|
||||||
// match each route with current URL segments and return the corresponding page once we find a match
|
// match each route with current URL segments and return the corresponding page once we find a match
|
||||||
foreach ($orderedRoutes as $routeSegments) {
|
foreach ($orderedRoutes as $routeSegments) {
|
||||||
@@ -186,7 +210,7 @@ class DatabasePageRouter implements RouterContract
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
// the URL segment matches if equal to the route segment
|
// the URL segment matches if equal to the route segment
|
||||||
if ($urlSegment === $routeSegment) {
|
if (strtolower($urlSegment) === strtolower($routeSegment)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -329,6 +329,15 @@ class WebsiteManager implements WebsiteManagerContract
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
phpb_redirect(
|
||||||
|
phpb_url("website_manager", ["tab" => "settings"]),
|
||||||
|
[
|
||||||
|
"message-type" => "error",
|
||||||
|
"message" => phpb_trans(
|
||||||
|
"website-manager.invalid-default-language",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ if (isset($page)) {
|
|||||||
|
|
||||||
$pageTranslations = $page ? $page->getTranslations() : [];
|
$pageTranslations = $page ? $page->getTranslations() : [];
|
||||||
$activeLanguages = phpb_active_languages();
|
$activeLanguages = phpb_active_languages();
|
||||||
|
$routeService = new \Plugi\PageTranslationService();
|
||||||
$fieldValue = static function (string $field, ?string $languageCode = null) use ($page, $pageTranslations): string {
|
$fieldValue = static function (string $field, ?string $languageCode = null) use ($page, $pageTranslations): string {
|
||||||
if ($languageCode !== null) {
|
if ($languageCode !== null) {
|
||||||
$postedValues = $_POST[$field] ?? null;
|
$postedValues = $_POST[$field] ?? null;
|
||||||
@@ -112,6 +113,7 @@ $javascriptValue = static function (string $value): string {
|
|||||||
<?php
|
<?php
|
||||||
$firstLang = true;
|
$firstLang = true;
|
||||||
foreach ($activeLanguages as $languageCode => $languageTranslation):
|
foreach ($activeLanguages as $languageCode => $languageTranslation):
|
||||||
|
$routePrefix = $routeService->getGeneratedRoutePrefix($languageCode, $firstLang);
|
||||||
$savedTranslation = $pageTranslations[$languageCode] ?? null;
|
$savedTranslation = $pageTranslations[$languageCode] ?? null;
|
||||||
$hasSavedTranslation = is_array($savedTranslation);
|
$hasSavedTranslation = is_array($savedTranslation);
|
||||||
$translationType = $fieldValue('type') !== '' ? $fieldValue('type') : ($page?->get('type') ?? 'static');
|
$translationType = $fieldValue('type') !== '' ? $fieldValue('type') : ($page?->get('type') ?? 'static');
|
||||||
@@ -147,7 +149,7 @@ $javascriptValue = static function (string $value): string {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
<div class="space-y-3" x-data="{route: <?= $javascriptValue($fieldValue('route', $languageCode)) ?>, empty: true, locale: <?= $javascriptValue($firstLang ? '' : '/' . $languageCode) ?>}" x-init="empty = route.length === 0">
|
<div class="space-y-3" x-data="{route: <?= $javascriptValue($fieldValue('route', $languageCode)) ?>, empty: true, locale: <?= $javascriptValue($routePrefix) ?>}" x-init="empty = route.length === 0">
|
||||||
<div class="form-control w-full">
|
<div class="form-control w-full">
|
||||||
<label class="label" for="<?= phpb_e($languageCode) ?>-page-title">
|
<label class="label" for="<?= phpb_e($languageCode) ?>-page-title">
|
||||||
<span class="label-text"><?= phpb_trans('website-manager.page-title') ?></span>
|
<span class="label-text"><?= phpb_trans('website-manager.page-title') ?></span>
|
||||||
|
|||||||
@@ -2,12 +2,20 @@
|
|||||||
|
|
||||||
use Plugi\Extensions;
|
use Plugi\Extensions;
|
||||||
|
|
||||||
$settingIns = phpb_instance('setting');
|
$activeLanguages = phpb_active_languages();
|
||||||
?>
|
?>
|
||||||
|
|
||||||
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'settings', 'action' => 'update', 'tab' => 'settings']) ?>">
|
<form method="post" action="<?= phpb_url("website_manager", [
|
||||||
|
"route" => "settings",
|
||||||
|
"action" => "update",
|
||||||
|
"tab" => "settings",
|
||||||
|
]) ?>">
|
||||||
<?php phpb_csrf_field(); ?>
|
<?php phpb_csrf_field(); ?>
|
||||||
<div class="space-y-6" x-data="{activeTab: 0, tabs: ['Website','Language','Theme','Extensions']}">
|
<div class="space-y-6" x-data="{activeTab: 0, tabs: ['Website','Language','Theme','Extensions'], enabledLanguages: <?= str_replace(
|
||||||
|
'"',
|
||||||
|
"'",
|
||||||
|
json_encode(array_keys($activeLanguages)),
|
||||||
|
) ?>}">
|
||||||
<header class="space-y-1">
|
<header class="space-y-1">
|
||||||
<h2 class="text-xl font-bold tracking-tight text-base-content">Site settings</h2>
|
<h2 class="text-xl font-bold tracking-tight text-base-content">Site settings</h2>
|
||||||
<p class="text-sm text-base-content/60">Configure language, appearance, and extension options for this site.</p>
|
<p class="text-sm text-base-content/60">Configure language, appearance, and extension options for this site.</p>
|
||||||
@@ -22,37 +30,53 @@ $settingIns = phpb_instance('setting');
|
|||||||
</div>
|
</div>
|
||||||
<div id="settings-panel-1" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-1" tabindex="0" x-show="activeTab === 1">
|
<div id="settings-panel-1" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-1" tabindex="0" x-show="activeTab === 1">
|
||||||
<section class="space-y-4 rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
<section class="space-y-4 rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
||||||
<h2 class="text-lg font-semibold"><?= phpb_trans('website-manager.website-languages') ?></h2>
|
<h2 class="text-lg font-semibold"><?= phpb_trans(
|
||||||
|
"website-manager.website-languages",
|
||||||
|
) ?></h2>
|
||||||
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
<?php
|
<?php foreach (
|
||||||
foreach (phpb_trans('languages') as $locale => $localeText):
|
phpb_trans("languages")
|
||||||
?>
|
as $locale => $localeText
|
||||||
|
): ?>
|
||||||
<div class="form-control">
|
<div class="form-control">
|
||||||
<label class="flex cursor-pointer items-center justify-between gap-4 rounded-box border border-base-300 bg-base-100 px-4 py-3 transition-colors hover:border-primary/40 hover:bg-base-200/50">
|
<label class="flex cursor-pointer items-center justify-between gap-4 rounded-box border border-base-300 bg-base-100 px-4 py-3 transition-colors hover:border-primary/40 hover:bg-base-200/50">
|
||||||
<span class="label-text"><?= phpb_e($localeText) ?></span>
|
<span class="label-text"><?= phpb_e(
|
||||||
<input type="checkbox" name="languages[]" value="<?= phpb_e($locale) ?>" <?= phpb_e($settingIns::has('languages', $locale)) ? 'checked' : '' ?> class="checkbox checkbox-sm" />
|
$localeText,
|
||||||
|
) ?></span>
|
||||||
|
<input type="checkbox" name="languages[]" value="<?= phpb_e(
|
||||||
|
$locale,
|
||||||
|
) ?>" <?= isset($activeLanguages[$locale])
|
||||||
|
? "checked"
|
||||||
|
: "" ?> @change="enabledLanguages = $event.target.checked ? [...enabledLanguages, $event.target.value] : enabledLanguages.filter(language => language !== $event.target.value)" class="checkbox checkbox-sm" />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<?php
|
<?php endforeach; ?>
|
||||||
endforeach;
|
|
||||||
?>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<section class="max-w-2xl rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
<section class="max-w-2xl rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
||||||
<div class="form-control w-full">
|
<div class="form-control w-full">
|
||||||
<label for="admin_language" class="label">
|
<label for="default_language" class="label">
|
||||||
<span class="label-text"><?= phpb_trans('website-manager.admin-language') ?> <strong><?= phpb_current_language() ?></strong></span>
|
<span class="label-text"><?= phpb_trans(
|
||||||
|
"website-manager.default-language",
|
||||||
|
) ?></span>
|
||||||
</label>
|
</label>
|
||||||
<select class="select select-bordered w-full" id="admin_language" name="admin_language" title="<?= phpb_trans('website-manager.languages-selector-placeholder') ?>" required>
|
<select class="select select-bordered w-full" id="default_language" name="default_language" title="<?= phpb_trans(
|
||||||
<?php
|
"website-manager.languages-selector-placeholder",
|
||||||
$beLanguages = ['de', 'en', 'sv'];
|
) ?>" required>
|
||||||
foreach ($beLanguages as $locale):
|
<?php foreach (
|
||||||
?>
|
phpb_trans("languages")
|
||||||
<option value="<?= phpb_e($locale) ?>" <?= phpb_e(phpb_config('general.language') === $locale ? 'selected' : '') ?>><?= phpb_e(phpb_trans('languages.'.$locale)) ?></option>
|
as $locale => $localeText
|
||||||
<?php
|
): ?>
|
||||||
endforeach;
|
<option value="<?= phpb_e($locale) ?>" <?= phpb_e(
|
||||||
?>
|
phpb_config("general.language") === $locale ? "selected" : "",
|
||||||
|
) ?> :disabled="!enabledLanguages.includes('<?= phpb_e(
|
||||||
|
$locale,
|
||||||
|
) ?>')"><?= phpb_e($localeText) ?></option>
|
||||||
|
<?php endforeach; ?>
|
||||||
</select>
|
</select>
|
||||||
|
<p class="mt-2 text-sm text-base-content/60"><?= phpb_trans(
|
||||||
|
"website-manager.default-language-requires-enabled",
|
||||||
|
) ?></p>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
@@ -60,74 +84,82 @@ $settingIns = phpb_instance('setting');
|
|||||||
<section class="max-w-2xl rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
<section class="max-w-2xl rounded-box border border-base-300 bg-base-100 p-4 sm:p-6">
|
||||||
<div class="form-control w-full">
|
<div class="form-control w-full">
|
||||||
<label for="selected_theme" class="label">
|
<label for="selected_theme" class="label">
|
||||||
<span class="label-text"><?= phpb_trans('website-manager.selected-theme') ?></span>
|
<span class="label-text"><?= phpb_trans(
|
||||||
|
"website-manager.selected-theme",
|
||||||
|
) ?></span>
|
||||||
</label>
|
</label>
|
||||||
<select class="select select-bordered w-full" id="selected_theme" name="selected_theme" title="<?= phpb_trans('website-manager.languages-selector-placeholder') ?>" required>
|
<select class="select select-bordered w-full" id="selected_theme" name="selected_theme" title="<?= phpb_trans(
|
||||||
|
"website-manager.languages-selector-placeholder",
|
||||||
|
) ?>" required>
|
||||||
<?php
|
<?php
|
||||||
$themes = phpb_themes();
|
$themes = phpb_themes();
|
||||||
foreach ($themes as $theme => $themeConfig):
|
foreach ($themes as $theme => $themeConfig): ?>
|
||||||
?>
|
<option value="<?= phpb_e($theme) ?>" <?= phpb_e(
|
||||||
<option value="<?= phpb_e($theme) ?>" <?= phpb_e(phpb_config('theme.active_theme') === $theme ? 'selected' : '') ?>><?= phpb_e($themeConfig['title']) ?></option>
|
phpb_config("theme.active_theme") === $theme ? "selected" : "",
|
||||||
<?php
|
) ?>><?= phpb_e($themeConfig["title"]) ?></option>
|
||||||
endforeach;
|
<?php endforeach;
|
||||||
?>
|
?>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
<div id="settings-panel-3" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-3" tabindex="0" x-show="activeTab === 3">
|
<div id="settings-panel-3" class="space-y-6" role="tabpanel" aria-labelledby="settings-tab-3" tabindex="0" x-show="activeTab === 3">
|
||||||
<div class="flex flex-col gap-4">
|
<div class="flex flex-col gap-4">
|
||||||
<?php
|
<?php foreach (Extensions::getConfigs() as $extKey => $config):
|
||||||
foreach (Extensions::getConfigs() as $extKey => $config):
|
if (count(Extensions::getSettings($extKey)) === 0) {
|
||||||
if(count(Extensions::getSettings($extKey)) === 0){
|
|
||||||
continue;
|
continue;
|
||||||
}
|
} ?>
|
||||||
?>
|
|
||||||
<details class="collapse collapse-arrow border border-base-300 bg-base-100">
|
<details class="collapse collapse-arrow border border-base-300 bg-base-100">
|
||||||
<summary class="collapse-title text-lg font-semibold"><?= phpb_e($config['title']) ?></summary>
|
<summary class="collapse-title text-lg font-semibold"><?= phpb_e(
|
||||||
|
$config["title"],
|
||||||
|
) ?></summary>
|
||||||
<div class="collapse-content">
|
<div class="collapse-content">
|
||||||
<div class="space-y-4">
|
<div class="space-y-4">
|
||||||
<?php
|
<?php foreach (
|
||||||
foreach (Extensions::getSettings($extKey) as $setting):
|
Extensions::getSettings($extKey)
|
||||||
?>
|
as $setting
|
||||||
<?php
|
): ?>
|
||||||
if ($setting['type'] === 'text'):
|
<?php if ($setting["type"] === "text"): ?>
|
||||||
?>
|
|
||||||
<label class="form-control w-full gap-2">
|
<label class="form-control w-full gap-2">
|
||||||
<span class="label-text"><?= phpb_e($setting['label'] ?: $setting['name']) ?></span>
|
<span class="label-text"><?= phpb_e(
|
||||||
<input type="text" name="<?= phpb_e($setting['key']) ?>" value="<?= phpb_e($setting['value']) ?>" class="input input-bordered w-full" />
|
$setting["label"] ?:
|
||||||
|
$setting["name"],
|
||||||
|
) ?></span>
|
||||||
|
<input type="text" name="<?= phpb_e(
|
||||||
|
$setting["key"],
|
||||||
|
) ?>" value="<?= phpb_e(
|
||||||
|
$setting["value"],
|
||||||
|
) ?>" class="input input-bordered w-full" />
|
||||||
</label>
|
</label>
|
||||||
<?php
|
<?php endif; ?>
|
||||||
endif;
|
<?php if ($setting["type"] === "toggle"): ?>
|
||||||
?>
|
<div class="form-control" x-data="{state: <?= phpb_e(
|
||||||
<?php
|
$setting["value"],
|
||||||
if ($setting['type'] === 'toggle'):
|
) ?>}">
|
||||||
?>
|
|
||||||
<div class="form-control" x-data="{state: <?= phpb_e($setting['value']) ?>}">
|
|
||||||
<label class="label cursor-pointer">
|
<label class="label cursor-pointer">
|
||||||
<span class="label-text"><?= phpb_e($setting['label'] ?: $setting['name']) ?></span>
|
<span class="label-text"><?= phpb_e(
|
||||||
<input type='hidden' :value="state" name="<?= phpb_e($setting['key']) ?>">
|
$setting["label"] ?:
|
||||||
|
$setting["name"],
|
||||||
|
) ?></span>
|
||||||
|
<input type='hidden' :value="state" name="<?= phpb_e(
|
||||||
|
$setting["key"],
|
||||||
|
) ?>">
|
||||||
<input type="checkbox" class="toggle" x-model="state" />
|
<input type="checkbox" class="toggle" x-model="state" />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<?php
|
<?php endif; ?>
|
||||||
endif;
|
<?php endforeach; ?>
|
||||||
?>
|
|
||||||
<?php
|
|
||||||
endforeach;
|
|
||||||
?>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
<?php
|
<?php
|
||||||
endforeach;
|
endforeach; ?>
|
||||||
?>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex justify-end border-t border-base-300 pt-6">
|
<div class="flex justify-end border-t border-base-300 pt-6">
|
||||||
<button type="submit" class="btn btn-primary">
|
<button type="submit" class="btn btn-primary">
|
||||||
<i class="ph-bold ph-floppy-disk" aria-hidden="true"></i>
|
<i class="ph-bold ph-floppy-disk" aria-hidden="true"></i>
|
||||||
<?= phpb_trans('website-manager.save-settings'); ?>
|
<?= phpb_trans("website-manager.save-settings") ?>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -138,10 +170,16 @@ $settingIns = phpb_instance('setting');
|
|||||||
|
|
||||||
|
|
||||||
<!-- <div class="mt-8">-->
|
<!-- <div class="mt-8">-->
|
||||||
<!-- --><?php //= phpb_trans('website-manager.pagebuilder-block-images') ?>
|
<!-- --><?php
|
||||||
|
//= phpb_trans('website-manager.pagebuilder-block-images')
|
||||||
|
?>
|
||||||
<!-- </div>-->
|
<!-- </div>-->
|
||||||
<!-- <a href="--><?php //= phpb_url('website_manager', ['route' => 'settings', 'action' => 'renderBlockThumbs']) ?><!--" class="btn btn-secondary btn-sm mr-1">-->
|
<!-- <a href="--><?php
|
||||||
<!-- --><?php //= phpb_trans('website-manager.render-thumbs') ?>
|
//= phpb_url('website_manager', ['route' => 'settings', 'action' => 'renderBlockThumbs'])
|
||||||
|
?><!--" class="btn btn-secondary btn-sm mr-1">-->
|
||||||
|
<!-- --><?php
|
||||||
|
//= phpb_trans('website-manager.render-thumbs')
|
||||||
|
?>
|
||||||
<!-- </a>-->
|
<!-- </a>-->
|
||||||
|
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -6,6 +6,30 @@ use Plugi\Repositories\PageTranslationRepository;
|
|||||||
|
|
||||||
class PageTranslationService
|
class PageTranslationService
|
||||||
{
|
{
|
||||||
|
public function normalizeRoute(string $route): string
|
||||||
|
{
|
||||||
|
$route = preg_split('/[?#]/', trim($route), 2)[0] ?? '';
|
||||||
|
$segments = preg_split('#/+#', trim($route, '/'), -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
||||||
|
foreach ($segments as &$segment) {
|
||||||
|
if ($segment !== '*' && ! preg_match('/^\{[^{}]+\}$/', $segment)) {
|
||||||
|
$segment = strtolower($segment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unset($segment);
|
||||||
|
|
||||||
|
return $segments === [] ? '/' : '/' . implode('/', $segments);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getRouteKey(string $route): string
|
||||||
|
{
|
||||||
|
return strtolower($this->normalizeRoute($route));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getGeneratedRoutePrefix(string $locale, bool $isDefaultLocale): string
|
||||||
|
{
|
||||||
|
return $isDefaultLocale ? '' : '/' . $locale;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return the requested locale, configured default, or first available locale, in that order.
|
* Return the requested locale, configured default, or first available locale, in that order.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -209,7 +209,7 @@ class Plugi
|
|||||||
$phpb_db = new DB();
|
$phpb_db = new DB();
|
||||||
$theme = Setting::get('selected_theme');
|
$theme = Setting::get('selected_theme');
|
||||||
if ($theme) $phpb_config['theme']['active_theme'] = $theme;
|
if ($theme) $phpb_config['theme']['active_theme'] = $theme;
|
||||||
$language = Setting::get('admin_language');
|
$language = Setting::get('default_language') ?? Setting::get('admin_language');
|
||||||
if ($language) $phpb_config['general']['language'] = $language;
|
if ($language) $phpb_config['general']['language'] = $language;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,7 +223,7 @@ class Plugi
|
|||||||
global $phpb_config;
|
global $phpb_config;
|
||||||
$theme = Setting::get('selected_theme');
|
$theme = Setting::get('selected_theme');
|
||||||
if ($theme) $phpb_config['theme']['active_theme'] = $theme;
|
if ($theme) $phpb_config['theme']['active_theme'] = $theme;
|
||||||
$language = Setting::get('admin_language');
|
$language = Setting::get('default_language') ?? Setting::get('admin_language');
|
||||||
if ($language) $phpb_config['general']['language'] = $language;
|
if ($language) $phpb_config['general']['language'] = $language;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -473,9 +473,16 @@ class Plugi
|
|||||||
$previewToken = $_GET['previewToken'] ?? null;
|
$previewToken = $_GET['previewToken'] ?? null;
|
||||||
$isAuthenticatedPreview = $this->isAuthenticatedPreviewRequest($previewToken);
|
$isAuthenticatedPreview = $this->isAuthenticatedPreviewRequest($previewToken);
|
||||||
|
|
||||||
|
$pageTranslation = $this->resolvePageLanguageVariantFromUrl(phpb_current_relative_url());
|
||||||
|
if ($pageTranslation) {
|
||||||
|
global $phpb_request_language;
|
||||||
|
$phpb_request_language = $pageTranslation->locale;
|
||||||
|
$this->loadTranslations($pageTranslation->locale);
|
||||||
|
}
|
||||||
|
|
||||||
// try to find page in cache
|
// try to find page in cache
|
||||||
$cache = phpb_instance('cache');
|
$cache = phpb_instance('cache');
|
||||||
if (! $hasPreviewToken &&
|
if ($pageTranslation && ! $hasPreviewToken &&
|
||||||
phpb_config('cache.enabled') &&
|
phpb_config('cache.enabled') &&
|
||||||
! isset($_GET['ignore_cache']) &&
|
! isset($_GET['ignore_cache']) &&
|
||||||
! isset($_GET['refresh_cache']) &&
|
! isset($_GET['refresh_cache']) &&
|
||||||
@@ -490,11 +497,7 @@ class Plugi
|
|||||||
}
|
}
|
||||||
|
|
||||||
// let the page router resolve the current URL
|
// let the page router resolve the current URL
|
||||||
$page = null;
|
$page = $pageTranslation?->getPage();
|
||||||
$pageTranslation = $this->resolvePageLanguageVariantFromUrl(phpb_current_relative_url());
|
|
||||||
if ($pageTranslation) {
|
|
||||||
$page = $pageTranslation->getPage();
|
|
||||||
}
|
|
||||||
// if the URL cannot be resolved, but the lowercase version of the URL can be resolved, redirect to the lowercase URL
|
// if the URL cannot be resolved, but the lowercase version of the URL can be resolved, redirect to the lowercase URL
|
||||||
if (($page->logic ?? '') === 'page-not-found' && phpb_current_relative_url() !== strtolower(phpb_current_relative_url())) {
|
if (($page->logic ?? '') === 'page-not-found' && phpb_current_relative_url() !== strtolower(phpb_current_relative_url())) {
|
||||||
$pageLowerCaseUrlTranslation = $this->resolvePageLanguageVariantFromUrl(strtolower(phpb_current_relative_url()));
|
$pageLowerCaseUrlTranslation = $this->resolvePageLanguageVariantFromUrl(strtolower(phpb_current_relative_url()));
|
||||||
|
|||||||
@@ -121,8 +121,12 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
if ($updateResult) {
|
if ($updateResult) {
|
||||||
|
$newRoutes = [];
|
||||||
|
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
||||||
|
$newRoutes[] = $translationService->normalizeRoute($data['route'][$languageCode]);
|
||||||
|
}
|
||||||
$translationService->invalidateRoutes(
|
$translationService->invalidateRoutes(
|
||||||
array_merge($oldRoutes, array_values($data["route"])),
|
array_merge($oldRoutes, $newRoutes),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return $updateResult;
|
return $updateResult;
|
||||||
@@ -146,26 +150,35 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
|||||||
}
|
}
|
||||||
|
|
||||||
$pageTranslationRepository = new PageTranslationRepository();
|
$pageTranslationRepository = new PageTranslationRepository();
|
||||||
if (
|
$translationService = new PageTranslationService();
|
||||||
!$pageTranslationRepository->destroyWhere(
|
$existingTranslations = [];
|
||||||
phpb_config("page.translation.foreign_key"),
|
foreach ($pageTranslationRepository->getForPages([$page->getId()]) as $existingTranslation) {
|
||||||
$page->getId(),
|
$existingTranslations[$existingTranslation->locale] = $existingTranslation;
|
||||||
)
|
|
||||||
) {
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
||||||
$translation = $pageTranslationRepository->create([
|
$existingTranslation = $existingTranslations[$languageCode] ?? null;
|
||||||
|
$route = $data['route'][$languageCode];
|
||||||
|
if (! $existingTranslation || $route !== $existingTranslation->route) {
|
||||||
|
$route = $translationService->normalizeRoute($route);
|
||||||
|
}
|
||||||
|
$translationData = [
|
||||||
phpb_config("page.translation.foreign_key") => $page->getId(),
|
phpb_config("page.translation.foreign_key") => $page->getId(),
|
||||||
"locale" => $languageCode,
|
"locale" => $languageCode,
|
||||||
"title" => $data["title"][$languageCode],
|
"title" => $data["title"][$languageCode],
|
||||||
"meta_title" => $data["meta_title"][$languageCode],
|
"meta_title" => $data["meta_title"][$languageCode],
|
||||||
"meta_description" => $data["meta_description"][$languageCode],
|
"meta_description" => $data["meta_description"][$languageCode],
|
||||||
"route" => $data["route"][$languageCode],
|
"route" => $route,
|
||||||
"target" => $data["target"][$languageCode],
|
"target" => $data["target"][$languageCode],
|
||||||
]);
|
];
|
||||||
if (!($translation instanceof PageTranslationContract)) {
|
if ($existingTranslation) {
|
||||||
return false;
|
if (! $pageTranslationRepository->update($existingTranslation, $translationData)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$translation = $pageTranslationRepository->create($translationData);
|
||||||
|
if (! ($translation instanceof PageTranslationContract)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,17 +246,49 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
|
|||||||
array $activeLanguages,
|
array $activeLanguages,
|
||||||
$pageId = null,
|
$pageId = null,
|
||||||
): bool {
|
): bool {
|
||||||
|
$translationService = new PageTranslationService();
|
||||||
|
$existingTranslations = [];
|
||||||
|
if ($pageId !== null) {
|
||||||
|
foreach ((new PageTranslationRepository())->getForPages([$pageId]) as $translation) {
|
||||||
|
$existingTranslations[$translation->locale] = $translation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$routes = [];
|
$routes = [];
|
||||||
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
foreach ($activeLanguages as $languageCode => $languageTranslation) {
|
||||||
$route = $data["route"][$languageCode];
|
$route = $data["route"][$languageCode];
|
||||||
if (array_key_exists($route, $routes)) {
|
$routeKey = $translationService->getRouteKey($route);
|
||||||
return true;
|
if (array_key_exists($routeKey, $routes)) {
|
||||||
|
$unchangedRoutes = $pageId !== null;
|
||||||
|
foreach (array_keys($routes[$routeKey]) as $existingLocale) {
|
||||||
|
if (($existingTranslations[$existingLocale]->route ?? null) !== $data['route'][$existingLocale]) {
|
||||||
|
$unchangedRoutes = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (! $unchangedRoutes || ($existingTranslations[$languageCode]->route ?? null) !== $route) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$routes[$routeKey][$languageCode] = $route;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($routes as $routeKey => $localizedRoutes) {
|
||||||
|
foreach ($existingTranslations as $existingLocale => $translation) {
|
||||||
|
if (isset($activeLanguages[$existingLocale]) || $translationService->getRouteKey((string) $translation->route) !== $routeKey) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
foreach ($localizedRoutes as $languageCode => $route) {
|
||||||
|
if (($existingTranslations[$languageCode]->route ?? null) !== $route) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
$routes[$route] = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$pageTranslationRepository = new PageTranslationRepository();
|
$pageTranslationRepository = new PageTranslationRepository();
|
||||||
foreach (array_keys($routes) as $route) {
|
foreach ($routes as $localizedRoutes) {
|
||||||
|
$route = reset($localizedRoutes);
|
||||||
if ($pageTranslationRepository->routeExists($route, $pageId)) {
|
if ($pageTranslationRepository->routeExists($route, $pageId)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace Plugi\Repositories;
|
namespace Plugi\Repositories;
|
||||||
|
|
||||||
use Plugi\Contracts\PageTranslationRepositoryContract;
|
use Plugi\Contracts\PageTranslationRepositoryContract;
|
||||||
|
use Plugi\PageTranslationService;
|
||||||
|
|
||||||
class PageTranslationRepository extends BaseRepository implements PageTranslationRepositoryContract
|
class PageTranslationRepository extends BaseRepository implements PageTranslationRepositoryContract
|
||||||
{
|
{
|
||||||
@@ -39,16 +40,23 @@ class PageTranslationRepository extends BaseRepository implements PageTranslatio
|
|||||||
*/
|
*/
|
||||||
public function routeExists(string $route, $excludedPageId = null): bool
|
public function routeExists(string $route, $excludedPageId = null): bool
|
||||||
{
|
{
|
||||||
$query = "SELECT 1 FROM {$this->table} WHERE route = ?";
|
$foreignKey = $this->removeNonAlphaNumeric(phpb_config('page.translation.foreign_key'));
|
||||||
$parameters = [$route];
|
$routes = $this->db->select("SELECT route, {$foreignKey} FROM {$this->table}", []);
|
||||||
if ($excludedPageId !== null) {
|
$translationService = new PageTranslationService();
|
||||||
$foreignKey = $this->removeNonAlphaNumeric(phpb_config('page.translation.foreign_key'));
|
$routeKey = $translationService->getRouteKey($route);
|
||||||
$query .= " AND {$foreignKey} != ?";
|
foreach ($routes as $translation) {
|
||||||
$parameters[] = $excludedPageId;
|
if ($excludedPageId !== null && (string) $translation[$foreignKey] === (string) $excludedPageId) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (! is_string($translation['route']) || trim($translation['route']) === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ($translationService->getRouteKey((string) $translation['route']) === $routeKey) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
$query .= ' LIMIT 1';
|
|
||||||
|
|
||||||
return ! empty($this->db->select($query, $parameters));
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -21,27 +21,60 @@ class SettingRepository extends BaseRepository implements SettingRepositoryContr
|
|||||||
*/
|
*/
|
||||||
public function updateSettings(array $data)
|
public function updateSettings(array $data)
|
||||||
{
|
{
|
||||||
|
if (! $this->hasValidLanguageSettings($data)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
foreach ($data as $key => $value) {
|
return $this->db->transaction(function () use ($data) {
|
||||||
$isArray = is_array($value) ? 1 : 0;
|
foreach ($data as $key => $value) {
|
||||||
if ($isArray) {
|
$isArray = is_array($value) ? 1 : 0;
|
||||||
$value = implode(',', $value);
|
if ($isArray) {
|
||||||
}
|
$value = implode(',', $value);
|
||||||
$ins = $this->findWhere('setting', $key);
|
}
|
||||||
if (empty($ins)) {
|
$setting = [
|
||||||
$this->create([
|
|
||||||
'setting' => $key,
|
'setting' => $key,
|
||||||
'value' => $value,
|
'value' => $value,
|
||||||
'is_array' => $isArray,
|
'is_array' => $isArray,
|
||||||
]);
|
];
|
||||||
} else {
|
$ins = $this->findWhere('setting', $key);
|
||||||
$this->update($ins[0], [
|
if (empty($ins)) {
|
||||||
'setting' => $key,
|
if (! $this->create($setting)) {
|
||||||
'value' => $value,
|
return false;
|
||||||
'is_array' => $isArray,
|
}
|
||||||
]);
|
} elseif (! $this->update($ins[0], $setting)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function hasValidLanguageSettings(array $data): bool
|
||||||
|
{
|
||||||
|
if (! array_intersect(['languages', 'default_language', 'admin_language'], array_keys($data))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$languages = array_key_exists('languages', $data)
|
||||||
|
? $data['languages']
|
||||||
|
: array_keys(phpb_active_languages());
|
||||||
|
$defaultLanguage = $data['default_language']
|
||||||
|
?? phpb_instance('setting')::get('default_language')
|
||||||
|
?? $data['admin_language']
|
||||||
|
?? phpb_config('general.language');
|
||||||
|
$availableLanguages = phpb_trans('languages');
|
||||||
|
|
||||||
|
if (! is_array($languages) || $languages === [] || ! is_string($defaultLanguage)
|
||||||
|
|| ! is_array($availableLanguages) || ! isset($availableLanguages[$defaultLanguage])
|
||||||
|
|| ! in_array($defaultLanguage, $languages, true)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($languages as $language) {
|
||||||
|
if (! is_string($language) || ! isset($availableLanguages[$language])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -54,11 +54,14 @@ class PageCreationTestDatabase extends DB
|
|||||||
public int $pageTranslationAllCallCount = 0;
|
public int $pageTranslationAllCallCount = 0;
|
||||||
public int $pageTranslationBatchSelectCount = 0;
|
public int $pageTranslationBatchSelectCount = 0;
|
||||||
public ?int $failOnTranslationInsert = null;
|
public ?int $failOnTranslationInsert = null;
|
||||||
|
public bool $failOnTranslationUpdate = false;
|
||||||
public bool $throwOnTranslationFailure = false;
|
public bool $throwOnTranslationFailure = false;
|
||||||
public ?string $failOnDeleteTable = null;
|
public ?string $failOnDeleteTable = null;
|
||||||
public bool $throwOnDeleteFailure = false;
|
public bool $throwOnDeleteFailure = false;
|
||||||
public bool $failOnPageUpdate = false;
|
public bool $failOnPageUpdate = false;
|
||||||
public ?int $failOnPageUpdateId = null;
|
public ?int $failOnPageUpdateId = null;
|
||||||
|
public ?int $failOnSettingWrite = null;
|
||||||
|
public int $settingWriteCount = 0;
|
||||||
public array $schemaDiffs = [];
|
public array $schemaDiffs = [];
|
||||||
|
|
||||||
public function __construct()
|
public function __construct()
|
||||||
@@ -70,6 +73,12 @@ class PageCreationTestDatabase extends DB
|
|||||||
|
|
||||||
public function query(string $query, array $parameters = [])
|
public function query(string $query, array $parameters = [])
|
||||||
{
|
{
|
||||||
|
if (str_starts_with($query, 'INSERT INTO settings') || str_starts_with($query, 'UPDATE settings SET')) {
|
||||||
|
$this->settingWriteCount++;
|
||||||
|
if ($this->settingWriteCount === $this->failOnSettingWrite) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
if ($this->failOnDeleteTable !== null && str_starts_with($query, 'DELETE FROM ' . $this->failOnDeleteTable)) {
|
if ($this->failOnDeleteTable !== null && str_starts_with($query, 'DELETE FROM ' . $this->failOnDeleteTable)) {
|
||||||
if ($this->throwOnDeleteFailure) {
|
if ($this->throwOnDeleteFailure) {
|
||||||
throw new PDOException('Simulated page deletion failure.');
|
throw new PDOException('Simulated page deletion failure.');
|
||||||
@@ -92,6 +101,9 @@ class PageCreationTestDatabase extends DB
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if ($this->failOnTranslationUpdate && str_starts_with($query, 'UPDATE page_translations SET')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
return parent::query($query, $parameters);
|
return parent::query($query, $parameters);
|
||||||
}
|
}
|
||||||
@@ -128,6 +140,12 @@ class PageCreationTestDatabase extends DB
|
|||||||
|
|
||||||
public function createSchema(): void
|
public function createSchema(): void
|
||||||
{
|
{
|
||||||
|
$this->pdo->exec('CREATE TABLE settings (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
setting TEXT NOT NULL UNIQUE,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
is_array INTEGER NOT NULL
|
||||||
|
)');
|
||||||
$this->pdo->exec('CREATE TABLE pages (
|
$this->pdo->exec('CREATE TABLE pages (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
name TEXT,
|
name TEXT,
|
||||||
@@ -212,14 +230,24 @@ class PageCreationSchemaMigrationTestDatabase extends DB
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function transaction(callable $callback): mixed
|
||||||
|
{
|
||||||
|
return $callback();
|
||||||
|
}
|
||||||
|
|
||||||
public function select(string $query, array $parameters): array
|
public function select(string $query, array $parameters): array
|
||||||
{
|
{
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function findWithId(string $table, $id): array
|
||||||
|
{
|
||||||
|
return [['id' => $id]];
|
||||||
|
}
|
||||||
|
|
||||||
public function lastInsertId(): string
|
public function lastInsertId(): string
|
||||||
{
|
{
|
||||||
return '0';
|
return '1';
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getDBDefinitionHash(): string
|
public function getDBDefinitionHash(): string
|
||||||
@@ -268,11 +296,11 @@ class PageCreationTestCache
|
|||||||
|
|
||||||
class PageCreationTestPublicRouter
|
class PageCreationTestPublicRouter
|
||||||
{
|
{
|
||||||
public function __construct(private PageTranslationContract $translation)
|
public function __construct(private ?PageTranslationContract $translation)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public function resolve(string $url): PageTranslationContract
|
public function resolve(string $url): ?PageTranslationContract
|
||||||
{
|
{
|
||||||
return $this->translation;
|
return $this->translation;
|
||||||
}
|
}
|
||||||
@@ -281,10 +309,12 @@ class PageCreationTestPublicRouter
|
|||||||
class PageCreationTestPublicPageBuilder
|
class PageCreationTestPublicPageBuilder
|
||||||
{
|
{
|
||||||
public array $renderedData = [];
|
public array $renderedData = [];
|
||||||
|
public ?string $renderedLanguage = null;
|
||||||
|
|
||||||
public function renderPage(PageContract $page, ?string $language = null): string
|
public function renderPage(PageContract $page, ?string $language = null): string
|
||||||
{
|
{
|
||||||
$this->renderedData = $page->getBuilderData();
|
$this->renderedData = $page->getBuilderData();
|
||||||
|
$this->renderedLanguage = $language;
|
||||||
return '<!doctype html><html><head><title>Page</title></head><body><main>Theme layout</main>'
|
return '<!doctype html><html><head><title>Page</title></head><body><main>Theme layout</main>'
|
||||||
. '<a href="/about?locale=de#intro">Internal</a>'
|
. '<a href="/about?locale=de#intro">Internal</a>'
|
||||||
. '<a href="https://example.test/contact?next=1">Absolute internal</a>'
|
. '<a href="https://example.test/contact?next=1">Absolute internal</a>'
|
||||||
@@ -299,7 +329,7 @@ class PageCreationTestPublicPageBuilder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function runPageCreationPublicRequest(PageTranslationContract $translation, array $query, bool $authenticated, string $sessionToken): array
|
function runPageCreationPublicRequest(?PageTranslationContract $translation, array $query, bool $authenticated, string $sessionToken, ?string $cachedContent = null): array
|
||||||
{
|
{
|
||||||
global $pageCreationCurrentUrl;
|
global $pageCreationCurrentUrl;
|
||||||
|
|
||||||
@@ -312,7 +342,7 @@ function runPageCreationPublicRequest(PageTranslationContract $translation, arra
|
|||||||
$pageCreationCurrentUrl = '/new-page' . ($query === [] ? '' : '?' . http_build_query($query));
|
$pageCreationCurrentUrl = '/new-page' . ($query === [] ? '' : '?' . http_build_query($query));
|
||||||
PageCreationTestCache::$cacheReads = [];
|
PageCreationTestCache::$cacheReads = [];
|
||||||
PageCreationTestCache::$cacheWrites = [];
|
PageCreationTestCache::$cacheWrites = [];
|
||||||
PageCreationTestCache::$cachedContent = null;
|
PageCreationTestCache::$cachedContent = $cachedContent;
|
||||||
\Plugi\Modules\GrapesJS\PageRenderer::$canBeCached = true;
|
\Plugi\Modules\GrapesJS\PageRenderer::$canBeCached = true;
|
||||||
|
|
||||||
$pageBuilder = new PageCreationTestPublicPageBuilder();
|
$pageBuilder = new PageCreationTestPublicPageBuilder();
|
||||||
@@ -738,7 +768,7 @@ $cases = [
|
|||||||
assertPageCreation($page === true, 'The submitted homepage payload did not create a page.');
|
assertPageCreation($page === true, 'The submitted homepage payload did not create a page.');
|
||||||
assertPageCreation(count($translations) === 2, 'The homepage did not persist both localized translations.');
|
assertPageCreation(count($translations) === 2, 'The homepage did not persist both localized translations.');
|
||||||
assertPageCreation($translations[0]['route'] === '/', 'The English homepage route was not preserved.');
|
assertPageCreation($translations[0]['route'] === '/', 'The English homepage route was not preserved.');
|
||||||
assertPageCreation($translations[1]['route'] === '/de/', 'The German homepage route was not preserved.');
|
assertPageCreation($translations[1]['route'] === '/de', 'The German homepage route was not stored without a trailing slash.');
|
||||||
},
|
},
|
||||||
'generated routes persist for every active locale' => function (): void {
|
'generated routes persist for every active locale' => function (): void {
|
||||||
resetPageCreationDatabase();
|
resetPageCreationDatabase();
|
||||||
@@ -841,6 +871,107 @@ $cases = [
|
|||||||
);
|
);
|
||||||
assertPageCreation($phpb_db->pageTranslationAllCallCount === 0, 'Route validation loaded every translation instead of querying for a collision.');
|
assertPageCreation($phpb_db->pageTranslationAllCallCount === 0, 'Route validation loaded every translation instead of querying for a collision.');
|
||||||
},
|
},
|
||||||
|
'page route writes canonicalize slash and case variants' => function (): void {
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
$repository = new PageRepository();
|
||||||
|
assertPageCreation($repository->create(pageCreationPayload([
|
||||||
|
'route' => ['en' => '/About//Us/', 'de' => '/DE/Neue-Seite/'],
|
||||||
|
])) === true, 'A route with redundant slashes and uppercase characters was rejected.');
|
||||||
|
|
||||||
|
global $phpb_db;
|
||||||
|
$translations = $phpb_db->rows('page_translations');
|
||||||
|
assertPageCreation($translations[0]['route'] === '/about/us', 'The English route was not stored canonically.');
|
||||||
|
assertPageCreation($translations[1]['route'] === '/de/neue-seite', 'The German route was not stored canonically.');
|
||||||
|
},
|
||||||
|
'route collision checks reject canonical slash and case variants' => function (): void {
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
$repository = new PageRepository();
|
||||||
|
$repository->create(pageCreationPayload([
|
||||||
|
'route' => ['en' => '/About/Us/', 'de' => '/de/uns'],
|
||||||
|
]));
|
||||||
|
|
||||||
|
assertPageCreation($repository->create(pageCreationPayload([
|
||||||
|
'name' => 'Canonical collision',
|
||||||
|
'route' => ['en' => '/ABOUT//US', 'de' => '/de/another'],
|
||||||
|
])) === false, 'A case or slash variant of a stored route was not rejected.');
|
||||||
|
},
|
||||||
|
'unchanged legacy routes remain stored until edited' => function (): void {
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
$repository = new PageRepository();
|
||||||
|
$repository->create(pageCreationPayload());
|
||||||
|
global $phpb_db;
|
||||||
|
$pageId = $phpb_db->rows('pages')[0]['id'];
|
||||||
|
$phpb_db->query('UPDATE page_translations SET route = ? WHERE page_id = ? AND locale = ?', ['/Legacy-Path/', $pageId, 'en']);
|
||||||
|
$page = $repository->findWithId($pageId);
|
||||||
|
|
||||||
|
assertPageCreation($repository->update($page, pageCreationPayload([
|
||||||
|
'name' => 'Updated title only',
|
||||||
|
'route' => ['en' => '/Legacy-Path/'],
|
||||||
|
])) === true, 'An unrelated page edit failed for a legacy route.');
|
||||||
|
assertPageCreation($phpb_db->rows('page_translations')[0]['route'] === '/Legacy-Path/', 'An unchanged legacy route was rewritten during an unrelated edit.');
|
||||||
|
},
|
||||||
|
'ambiguous legacy routes do not resolve to an arbitrary translation' => function (): void {
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
$repository = new PageRepository();
|
||||||
|
$repository->create(pageCreationPayload(['route' => ['en' => '/legacy-path', 'de' => '/de/first']]));
|
||||||
|
$repository->create(pageCreationPayload(['name' => 'Second page', 'route' => ['en' => '/other-path', 'de' => '/de/second']]));
|
||||||
|
global $phpb_db;
|
||||||
|
$pageIds = array_column($phpb_db->rows('pages'), 'id');
|
||||||
|
$phpb_db->query('UPDATE page_translations SET route = ? WHERE page_id = ? AND locale = ?', ['/LEGACY-PATH/', $pageIds[1], 'en']);
|
||||||
|
|
||||||
|
assertPageCreation((new DatabasePageRouter())->resolve('/legacy-path') === null, 'A normalized legacy route collision resolved to an arbitrary page.');
|
||||||
|
},
|
||||||
|
'router normalizes request paths and keeps route parameters and wildcards' => function (): void {
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
$repository = new PageRepository();
|
||||||
|
assertPageCreation($repository->create(pageCreationPayload([
|
||||||
|
'route' => ['en' => '/Catalog/{ProductID}/', 'de' => '/DE/Files/*'],
|
||||||
|
])) === true, 'Routes for parameter and wildcard matching were not created.');
|
||||||
|
|
||||||
|
$router = new DatabasePageRouter();
|
||||||
|
$parameterRoute = $router->resolve('//CATALOG/AbC/?preview=1');
|
||||||
|
assertPageCreation($parameterRoute instanceof PageTranslationContract, 'Case/slash variants did not match a parameterized route.');
|
||||||
|
assertPageCreation($parameterRoute->route === '/catalog/{ProductID}', 'The resolved parameter route was not canonicalized.');
|
||||||
|
assertPageCreation(($GLOBALS['phpb_route_parameters']['ProductID'] ?? null) === 'AbC', 'The route parameter name or value was changed.');
|
||||||
|
|
||||||
|
$wildcardRoute = $router->resolve('/DE/FILES/a/b/');
|
||||||
|
assertPageCreation($wildcardRoute instanceof PageTranslationContract && $wildcardRoute->locale === 'de', 'A case/slash variant did not match the wildcard route.');
|
||||||
|
},
|
||||||
|
'disabled-language routes are hidden and translation rows survive edits' => function (): void {
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
$repository = new PageRepository();
|
||||||
|
assertPageCreation($repository->create(pageCreationPayload()) === true, 'The multilingual page was not created.');
|
||||||
|
global $phpb_db, $pageCreationLanguages;
|
||||||
|
$pageId = $phpb_db->rows('pages')[0]['id'];
|
||||||
|
$pageCreationLanguages = ['en' => []];
|
||||||
|
$page = $repository->findWithId($pageId);
|
||||||
|
assertPageCreation($repository->update($page, pageCreationPayload([
|
||||||
|
'name' => 'Edited with German disabled',
|
||||||
|
'title' => ['en' => 'Changed English', 'de' => 'Must remain untouched'],
|
||||||
|
'route' => ['en' => '/changed-english'],
|
||||||
|
])) === true, 'Editing with a language disabled failed.');
|
||||||
|
|
||||||
|
$translations = $phpb_db->rows('page_translations');
|
||||||
|
assertPageCreation(count($translations) === 2, 'Editing deleted an inactive translation.');
|
||||||
|
$germanTranslation = array_values(array_filter($translations, static fn(array $translation): bool => $translation['locale'] === 'de'))[0] ?? null;
|
||||||
|
assertPageCreation($germanTranslation !== null && $germanTranslation['title'] === 'Neue Seite' && $germanTranslation['route'] === '/de/new-page', 'Editing changed the inactive translation data.');
|
||||||
|
assertPageCreation((new DatabasePageRouter())->resolve('/de/new-page') === null, 'A disabled locale remained publicly routable.');
|
||||||
|
|
||||||
|
$pageCreationLanguages = ['en' => [], 'de' => []];
|
||||||
|
assertPageCreation((new DatabasePageRouter())->resolve('/DE/NEW-PAGE') instanceof PageTranslationContract, 'Re-enabling a locale did not restore its stored route.');
|
||||||
|
},
|
||||||
|
'active route edits cannot collide with a stored inactive translation' => function (): void {
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
$repository = new PageRepository();
|
||||||
|
$repository->create(pageCreationPayload());
|
||||||
|
global $phpb_db, $pageCreationLanguages;
|
||||||
|
$pageCreationLanguages = ['en' => []];
|
||||||
|
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
|
||||||
|
|
||||||
|
assertPageCreation($repository->update($page, pageCreationPayload([
|
||||||
|
'route' => ['en' => '/de/new-page'],
|
||||||
|
])) === false, 'An active route was allowed to collide with an inactive translation on the same page.');
|
||||||
|
},
|
||||||
'page locale coverage summarizes complete partial and absent translations in one batch' => function (): void {
|
'page locale coverage summarizes complete partial and absent translations in one batch' => function (): void {
|
||||||
resetPageCreationDatabase();
|
resetPageCreationDatabase();
|
||||||
$repository = new PageRepository();
|
$repository = new PageRepository();
|
||||||
@@ -1128,6 +1259,52 @@ $cases = [
|
|||||||
assertPageCreation($phpb_db->rows('pages')[0]['draft_data'] !== null, 'Rejected CSRF requests changed the saved draft.');
|
assertPageCreation($phpb_db->rows('pages')[0]['draft_data'] !== null, 'Rejected CSRF requests changed the saved draft.');
|
||||||
http_response_code(200);
|
http_response_code(200);
|
||||||
},
|
},
|
||||||
|
'settings writes roll back when a create or update fails' => function (): void {
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
global $phpb_db;
|
||||||
|
$settingRepository = new \Plugi\Repositories\SettingRepository();
|
||||||
|
$phpb_db->failOnSettingWrite = 2;
|
||||||
|
|
||||||
|
assertPageCreation(
|
||||||
|
! $settingRepository->updateSettings(['first' => 'one', 'second' => 'two'])
|
||||||
|
&& $phpb_db->rows('settings') === [],
|
||||||
|
'A failed settings create reported success or retained earlier writes.'
|
||||||
|
);
|
||||||
|
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
$phpb_db->query('INSERT INTO settings (setting, value, is_array) VALUES (?, ?, ?)', ['existing', 'old', 0]);
|
||||||
|
$phpb_db->settingWriteCount = 0;
|
||||||
|
$phpb_db->failOnSettingWrite = 2;
|
||||||
|
$settingRepository = new \Plugi\Repositories\SettingRepository();
|
||||||
|
$updateSucceeded = $settingRepository->updateSettings(['first' => 'one', 'existing' => 'new']);
|
||||||
|
$savedSettings = array_column($phpb_db->rows('settings'), 'value', 'setting');
|
||||||
|
assertPageCreation(
|
||||||
|
! $updateSucceeded && $savedSettings === ['existing' => 'old'],
|
||||||
|
'A failed settings update reported success or retained earlier writes.'
|
||||||
|
);
|
||||||
|
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
$settingRepository = new \Plugi\Repositories\SettingRepository();
|
||||||
|
assertPageCreation(
|
||||||
|
$settingRepository->updateSettings(['first' => 'one', 'second' => ['two', 'three']])
|
||||||
|
&& array_column($phpb_db->rows('settings'), 'value', 'setting') === ['first' => 'one', 'second' => 'two,three'],
|
||||||
|
'Successful settings writes were not committed.'
|
||||||
|
);
|
||||||
|
},
|
||||||
|
'cached public pages require a currently resolved route' => function (): void {
|
||||||
|
resetPageCreationDatabase();
|
||||||
|
$translation = new PageTranslation();
|
||||||
|
$translation->locale = 'en';
|
||||||
|
$translation->route = '/new-page';
|
||||||
|
|
||||||
|
[$handled, $html] = runPageCreationPublicRequest($translation, [], false, '', '<p>cached page</p>');
|
||||||
|
assertPageCreation($handled && $html === '<p>cached page</p>', 'An active route did not serve its cached response.');
|
||||||
|
assertPageCreation(count(PageCreationTestCache::$cacheReads) === 1, 'An active route did not check its cache.');
|
||||||
|
|
||||||
|
[$handled, $html] = runPageCreationPublicRequest(null, [], false, '', '<p>cached disabled route</p>');
|
||||||
|
assertPageCreation(! $handled && $html === '', 'A cached response was served after the router rejected the route.');
|
||||||
|
assertPageCreation(PageCreationTestCache::$cacheReads === [], 'A rejected route accessed the page cache.');
|
||||||
|
},
|
||||||
'public requests show drafts only for authenticated session-bound preview tokens' => function (): void {
|
'public requests show drafts only for authenticated session-bound preview tokens' => function (): void {
|
||||||
resetPageCreationDatabase();
|
resetPageCreationDatabase();
|
||||||
$repository = new PageRepository();
|
$repository = new PageRepository();
|
||||||
@@ -1143,13 +1320,14 @@ $cases = [
|
|||||||
$repository->updatePageDraftData($page, $draftData);
|
$repository->updatePageDraftData($page, $draftData);
|
||||||
$translation = new PageTranslation();
|
$translation = new PageTranslation();
|
||||||
$translation->page_id = $pageId;
|
$translation->page_id = $pageId;
|
||||||
$translation->locale = 'en';
|
$translation->locale = 'de';
|
||||||
$translation->route = '/new-page';
|
$translation->route = '/new-page';
|
||||||
$resolvedPreviewRoute = (new DatabasePageRouter())->resolve('/new-page?previewToken=valid-token');
|
$resolvedPreviewRoute = (new DatabasePageRouter())->resolve('/new-page?previewToken=valid-token');
|
||||||
assertPageCreation($resolvedPreviewRoute->route === '/new-page', 'The public router treated preview query parameters as part of the page route.');
|
assertPageCreation($resolvedPreviewRoute->route === '/new-page', 'The public router treated preview query parameters as part of the page route.');
|
||||||
|
|
||||||
[$handled, $html, $pageBuilder] = runPageCreationPublicRequest($translation, ['previewToken' => 'valid-token'], true, 'valid-token');
|
[$handled, $html, $pageBuilder] = runPageCreationPublicRequest($translation, ['previewToken' => 'valid-token'], true, 'valid-token');
|
||||||
assertPageCreation($handled === true, 'An authenticated preview request was not handled.');
|
assertPageCreation($handled === true, 'An authenticated preview request was not handled.');
|
||||||
|
assertPageCreation($pageBuilder->renderedLanguage === 'de' && $GLOBALS['phpb_request_language'] === 'de', 'A resolved translation locale did not control page rendering and request language state.');
|
||||||
assertPageCreation($pageBuilder->renderedData === $draftData, 'An authenticated session-bound preview did not render the saved draft.');
|
assertPageCreation($pageBuilder->renderedData === $draftData, 'An authenticated session-bound preview did not render the saved draft.');
|
||||||
assertPageCreation(str_contains(strtolower($html), '<!doctype html>'), 'Draft preview did not preserve the page doctype.');
|
assertPageCreation(str_contains(strtolower($html), '<!doctype html>'), 'Draft preview did not preserve the page doctype.');
|
||||||
assertPageCreation(str_contains($html, 'Theme layout'), 'Draft preview did not preserve the full themed page.');
|
assertPageCreation(str_contains($html, 'Theme layout'), 'Draft preview did not preserve the full themed page.');
|
||||||
@@ -1256,7 +1434,7 @@ $cases = [
|
|||||||
$repository->create(pageCreationPayload());
|
$repository->create(pageCreationPayload());
|
||||||
global $phpb_db;
|
global $phpb_db;
|
||||||
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
|
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
|
||||||
$phpb_db->failOnTranslationInsert = 4;
|
$phpb_db->failOnTranslationUpdate = true;
|
||||||
|
|
||||||
$result = $repository->update($page, pageCreationPayload([
|
$result = $repository->update($page, pageCreationPayload([
|
||||||
'name' => 'Changed page',
|
'name' => 'Changed page',
|
||||||
|
|||||||
@@ -7,6 +7,17 @@ $pageTranslationServiceConfig = [
|
|||||||
'language' => 'en',
|
'language' => 'en',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
$pageTranslationServiceSettings = ['languages' => ['en', 'fr']];
|
||||||
|
$pageTranslationServiceUrl = '/page';
|
||||||
|
|
||||||
|
class PageTranslationTestSettings
|
||||||
|
{
|
||||||
|
public static function get(string $key): mixed
|
||||||
|
{
|
||||||
|
global $pageTranslationServiceSettings;
|
||||||
|
return $pageTranslationServiceSettings[$key] ?? null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function phpb_config(?string $key = null): mixed
|
function phpb_config(?string $key = null): mixed
|
||||||
{
|
{
|
||||||
@@ -22,10 +33,66 @@ function phpb_config(?string $key = null): mixed
|
|||||||
}
|
}
|
||||||
$value = $value[$segment];
|
$value = $value[$segment];
|
||||||
}
|
}
|
||||||
|
|
||||||
return $value;
|
return $value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function phpb_trans(string $key): mixed
|
||||||
|
{
|
||||||
|
$languages = ['en' => 'English', 'fr' => 'French'];
|
||||||
|
return $key === 'languages' ? $languages : ($languages[substr($key, 10)] ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function phpb_instance(string $name, array $params = []): mixed
|
||||||
|
{
|
||||||
|
return PageTranslationTestSettings::class;
|
||||||
|
}
|
||||||
|
|
||||||
|
function phpb_current_relative_url(bool $removeParameters = false): string
|
||||||
|
{
|
||||||
|
global $pageTranslationServiceUrl;
|
||||||
|
return $pageTranslationServiceUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../src/Core/helpers.php';
|
||||||
|
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
|
||||||
|
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
|
||||||
|
require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
|
||||||
|
require_once __DIR__ . '/../src/Contracts/SettingContract.php';
|
||||||
|
require_once __DIR__ . '/../src/Setting.php';
|
||||||
|
require_once __DIR__ . '/../src/Plugi.php';
|
||||||
|
|
||||||
|
class PageTranslationTestSettingRepository extends Plugi\Repositories\SettingRepository
|
||||||
|
{
|
||||||
|
public array $saved = [];
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->db = new class {
|
||||||
|
public function transaction(callable $callback): mixed
|
||||||
|
{
|
||||||
|
return $callback();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public function findWhere($column, $value): array
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function create(array $data): object
|
||||||
|
{
|
||||||
|
$this->saved[$data['setting']] = $data;
|
||||||
|
return new stdClass();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function update($instance, array $data): bool
|
||||||
|
{
|
||||||
|
$this->saved[$data['setting']] = $data;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function assertPageTranslationService(bool $condition, string $message): void
|
function assertPageTranslationService(bool $condition, string $message): void
|
||||||
{
|
{
|
||||||
if (! $condition) {
|
if (! $condition) {
|
||||||
@@ -81,6 +148,108 @@ $cases = [
|
|||||||
'Locale validation should accept active languages only and must not apply fallback.'
|
'Locale validation should accept active languages only and must not apply fallback.'
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
'routes normalize slash variants and static-segment case' => function () use ($service): void {
|
||||||
|
assertPageTranslationService(
|
||||||
|
$service->normalizeRoute('/About//US/') === '/about/us'
|
||||||
|
&& $service->normalizeRoute('/About/{ProductID}/') === '/about/{ProductID}'
|
||||||
|
&& $service->getRouteKey('/ABOUT/{productid}') === $service->getRouteKey('/about/{ProductID}'),
|
||||||
|
'Route normalization should canonicalize slashes and case without changing parameter names.'
|
||||||
|
);
|
||||||
|
},
|
||||||
|
'generated route prefix follows the default-language convention' => function () use ($service): void {
|
||||||
|
assertPageTranslationService(
|
||||||
|
$service->getGeneratedRoutePrefix('en', true) === ''
|
||||||
|
&& $service->getGeneratedRoutePrefix('de', false) === '/de',
|
||||||
|
'Generated routes should leave the default locale unprefixed and prefix later locales.'
|
||||||
|
);
|
||||||
|
},
|
||||||
|
'matched page locale takes precedence over URL inference' => function (): void {
|
||||||
|
global $pageTranslationServiceUrl, $phpb_request_language;
|
||||||
|
$pageTranslationServiceUrl = '/page';
|
||||||
|
$phpb_request_language = 'fr';
|
||||||
|
|
||||||
|
assertPageTranslationService(
|
||||||
|
phpb_current_language() === 'fr',
|
||||||
|
'The matched translation locale should be authoritative on resolved page requests.'
|
||||||
|
);
|
||||||
|
unset($GLOBALS['phpb_request_language']);
|
||||||
|
},
|
||||||
|
'unresolved requests retain URL and configured-default fallback' => function (): void {
|
||||||
|
global $pageTranslationServiceUrl, $pageTranslationServiceConfig, $phpb_request_language;
|
||||||
|
unset($GLOBALS['phpb_request_language']);
|
||||||
|
$pageTranslationServiceConfig['general']['language'] = 'en';
|
||||||
|
$pageTranslationServiceUrl = '/fr/page';
|
||||||
|
assertPageTranslationService(
|
||||||
|
phpb_current_language() === 'fr',
|
||||||
|
'An unresolved locale-prefixed URL should retain URL-based language detection.'
|
||||||
|
);
|
||||||
|
|
||||||
|
$pageTranslationServiceUrl = '/page';
|
||||||
|
assertPageTranslationService(
|
||||||
|
phpb_current_language() === 'en',
|
||||||
|
'An unresolved URL without a locale prefix should fall back to the configured default.'
|
||||||
|
);
|
||||||
|
},
|
||||||
|
'default-language settings reject a disabled locale' => function (): void {
|
||||||
|
$settingRepository = new PageTranslationTestSettingRepository();
|
||||||
|
|
||||||
|
assertPageTranslationService(
|
||||||
|
! $settingRepository->updateSettings([
|
||||||
|
'languages' => ['en'],
|
||||||
|
'default_language' => 'fr',
|
||||||
|
]) && $settingRepository->saved === [],
|
||||||
|
'A default locale must be among enabled languages and invalid settings must not be persisted.'
|
||||||
|
);
|
||||||
|
},
|
||||||
|
'default-language settings accept an enabled locale' => function (): void {
|
||||||
|
$settingRepository = new PageTranslationTestSettingRepository();
|
||||||
|
|
||||||
|
assertPageTranslationService(
|
||||||
|
$settingRepository->updateSettings([
|
||||||
|
'languages' => ['en', 'fr'],
|
||||||
|
'default_language' => 'fr',
|
||||||
|
]) && ($settingRepository->saved['default_language']['value'] ?? null) === 'fr',
|
||||||
|
'A selected default locale should be saved when it is enabled.'
|
||||||
|
);
|
||||||
|
},
|
||||||
|
'legacy language input cannot disable an existing default' => function (): void {
|
||||||
|
global $pageTranslationServiceSettings;
|
||||||
|
$pageTranslationServiceSettings['default_language'] = 'en';
|
||||||
|
$settingRepository = new PageTranslationTestSettingRepository();
|
||||||
|
|
||||||
|
assertPageTranslationService(
|
||||||
|
! $settingRepository->updateSettings([
|
||||||
|
'languages' => ['fr'],
|
||||||
|
'admin_language' => 'fr',
|
||||||
|
]) && $settingRepository->saved === [],
|
||||||
|
'Legacy language input must not allow disabling the saved site default without replacement.'
|
||||||
|
);
|
||||||
|
unset($pageTranslationServiceSettings['default_language']);
|
||||||
|
},
|
||||||
|
'new default language takes precedence over the legacy setting' => function (): void {
|
||||||
|
$settings = new ReflectionProperty(Plugi\Setting::class, 'settings');
|
||||||
|
$settings->setValue(null, ['default_language' => 'fr', 'admin_language' => 'en']);
|
||||||
|
$GLOBALS['phpb_config'] = ['general' => ['language' => 'en'], 'theme' => []];
|
||||||
|
|
||||||
|
(new Plugi\Plugi([]))->hydrateConfig();
|
||||||
|
|
||||||
|
assertPageTranslationService(
|
||||||
|
$GLOBALS['phpb_config']['general']['language'] === 'fr',
|
||||||
|
'The distinct default-language setting should take precedence over the legacy setting.'
|
||||||
|
);
|
||||||
|
},
|
||||||
|
'legacy admin language remains a compatibility fallback' => function (): void {
|
||||||
|
$settings = new ReflectionProperty(Plugi\Setting::class, 'settings');
|
||||||
|
$settings->setValue(null, ['admin_language' => 'fr']);
|
||||||
|
$GLOBALS['phpb_config'] = ['general' => ['language' => 'en'], 'theme' => []];
|
||||||
|
|
||||||
|
(new Plugi\Plugi([]))->hydrateConfig();
|
||||||
|
|
||||||
|
assertPageTranslationService(
|
||||||
|
$GLOBALS['phpb_config']['general']['language'] === 'fr',
|
||||||
|
'Installations without a saved default-language setting should continue using admin_language.'
|
||||||
|
);
|
||||||
|
},
|
||||||
'translation values follow the same fallback order and preserve empty strings' => function () use ($service): void {
|
'translation values follow the same fallback order and preserve empty strings' => function () use ($service): void {
|
||||||
global $pageTranslationServiceConfig;
|
global $pageTranslationServiceConfig;
|
||||||
$pageTranslationServiceConfig['general']['language'] = 'fr';
|
$pageTranslationServiceConfig['general']['language'] = 'fr';
|
||||||
|
|||||||
Reference in New Issue
Block a user