Files
plugi/plugi-core/src/Modules/WebsiteManager/WebsiteManager.php
T
deepDiverPaul 6a4f7cac5f feat(multi-language): Add multi-language support and routing updates
Add configuration for multiple languages in the Website Manager
2026-11-30 19:47:55 +01:00

504 lines
16 KiB
PHP

<?php
namespace Plugi\Modules\WebsiteManager;
use Plugi\Contracts\PageContract;
use Plugi\Contracts\WebsiteManagerContract;
use Plugi\Extensions;
use Plugi\PageTranslationService;
use Plugi\Repositories\MenuRepository;
use Plugi\Repositories\PageDraftPublishedCacheInvalidationException;
use Plugi\Repositories\PageRepository;
use Plugi\Repositories\SettingRepository;
use Plugi\Repositories\UploadRepository;
class WebsiteManager implements WebsiteManagerContract
{
/**
* Process the current GET or POST request and redirect or render the requested page.
*
* @param $route
* @param $action
*/
public function handleRequest($route, $action)
{
if (is_null($route)) {
$this->renderOverview();
exit();
}
if ($route === "media" && $action === "update_metadata") {
if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
http_response_code(405);
exit();
}
$this->handleUpdateMediaMetadata();
exit();
}
if ($route === "drafts" && $action === "publish_all") {
$result = $this->handlePublishAllDrafts();
if ($result === null) {
exit();
}
if ($result["total"] === 0) {
$flashData = [
"message-type" => "info",
"message" => "No unpublished page changes were found.",
];
} elseif (
empty($result["failed"]) &&
empty($result["cache_warnings"])
) {
$pageCount = count($result["published"]);
$flashData = [
"message-type" => "success",
"message" => sprintf(
"Published changes for %d page%s.",
$pageCount,
$pageCount === 1 ? "" : "s",
),
];
} else {
$message = sprintf(
"Published changes for %d of %d pages.",
count($result["published"]),
$result["total"],
);
if (!empty($result["failed"])) {
$message .= sprintf(
" Failed pages: %s. Their drafts remain available to retry.",
implode(", ", $result["failed"]),
);
}
if (!empty($result["cache_warnings"])) {
$message .= sprintf(
" Route cache invalidation failed for: %s.",
implode(", ", $result["cache_warnings"]),
);
}
$flashData = [
"message-type" => empty($result["published"])
? "error"
: "warning",
"message" => $message,
];
}
phpb_redirect(phpb_url("website_manager"), $flashData);
}
if (
$route === "quality" &&
$action === "scan" &&
($_SERVER["REQUEST_METHOD"] ?? "") === "POST"
) {
if (
!function_exists("phpb_validate_csrf") ||
!phpb_validate_csrf()
) {
http_response_code(403);
die(
"Invalid CSRF token. Please refresh the page and try again."
);
}
$_GET["tab"] = "quality";
$this->renderQualityChecks(new SiteQualityCheckService()->run());
exit();
}
if ($route === "settings") {
if ($action === "renderBlockThumbs") {
$this->renderBlockThumbs();
exit();
}
if ($action === "update") {
$this->handleUpdateSettings();
exit();
}
}
if ($route === "menus") {
if ($action === "update") {
$this->handleUpdateMenus();
exit();
}
}
if ($route === "database") {
if ($action === "update") {
$this->handleUpdateDB();
exit();
}
}
if ($route === "page_settings") {
if ($action === "create") {
$this->handleCreate();
exit();
}
$pageId = $_GET["page"] ?? null;
$pageRepository = new PageRepository();
$page = $pageRepository->findWithId($pageId);
if (!($page instanceof PageContract)) {
phpb_redirect(phpb_url("website_manager"));
}
if ($action === "edit") {
$this->handleEdit($page);
exit();
} elseif ($action === "destroy") {
$this->handleDestroy($page);
}
}
}
/**
* Publish every page with a valid saved draft and return per-page outcomes.
*/
public function handlePublishAllDrafts(): ?array
{
if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
http_response_code(405);
return null;
}
if (!function_exists("phpb_validate_csrf") || !phpb_validate_csrf()) {
http_response_code(403);
return null;
}
$pageRepository = new PageRepository();
$result = [
"total" => 0,
"published" => [],
"failed" => [],
"cache_warnings" => [],
];
foreach ($pageRepository->getAll() as $page) {
if ($pageRepository->getPageDraftData($page) === null) {
continue;
}
$result["total"]++;
try {
$published = $pageRepository->publishPageDraft($page);
} catch (PageDraftPublishedCacheInvalidationException) {
$result["published"][] = (string) $page->getName();
$result["cache_warnings"][] = (string) $page->getName();
continue;
} catch (\Throwable) {
$published = false;
}
$result[
$published ? "published" : "failed"
][] = (string) $page->getName();
}
return $result;
}
/**
* Handle a CSRF-protected update to upload metadata.
*/
public function handleUpdateMediaMetadata(): bool
{
if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
http_response_code(405);
return false;
}
if (!function_exists("phpb_validate_csrf") || !phpb_validate_csrf()) {
http_response_code(403);
return false;
}
$allowedFields = ["_csrf_token", "public_id", "folder", "alt_text"];
if (array_diff(array_keys($_POST), $allowedFields)) {
return $this->redirectMediaMetadataResult(false);
}
$publicId = $_POST["public_id"] ?? null;
$metadata = array_intersect_key(
$_POST,
array_flip(["folder", "alt_text"]),
);
if (!is_string($publicId) || $publicId === "" || empty($metadata)) {
return $this->redirectMediaMetadataResult(false);
}
$success = new UploadRepository()->updateMetadata($publicId, $metadata);
return $this->redirectMediaMetadataResult($success);
}
private function redirectMediaMetadataResult(bool $success): bool
{
phpb_redirect(phpb_url("website_manager", ["tab" => "files"]), [
"message-type" => $success ? "success" : "error",
"message" => $success
? "Media metadata updated."
: "Media metadata could not be updated.",
]);
return $success;
}
/**
* Handle requests for creating a new page.
*/
public function handleCreate()
{
$errorMessage = null;
if ($_SERVER["REQUEST_METHOD"] === "POST") {
try {
$pageRepository = new PageRepository();
$page = $pageRepository->create($_POST);
} catch (\Throwable) {
$page = false;
}
if ($page) {
phpb_redirect(phpb_url("website_manager"), [
"message-type" => "success",
"message" => phpb_trans("website-manager.page-created"),
]);
}
$errorMessage = phpb_trans("website-manager.page-create-failed");
}
$this->renderPageSettings(null, $errorMessage);
}
/**
* Handle requests for editing the given page.
*
* @param PageContract $page
*/
public function handleEdit(PageContract $page)
{
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$pageRepository = new PageRepository();
$success = $pageRepository->update($page, $_POST);
if ($success) {
phpb_redirect(phpb_url("website_manager"), [
"message-type" => "success",
"message" => phpb_trans("website-manager.page-updated"),
]);
}
}
$this->renderPageSettings($page);
}
/**
* Handle requests to destroy the given page.
*
* @param PageContract $page
*/
public function handleDestroy(PageContract $page)
{
$pageRepository = new PageRepository();
if (!$pageRepository->destroy($page->getId())) {
phpb_redirect(phpb_url("website_manager"), [
"message-type" => "error",
"message" => phpb_trans("website-manager.page-delete-failed"),
]);
}
phpb_redirect(phpb_url("website_manager"), [
"message-type" => "success",
"message" => phpb_trans("website-manager.page-deleted"),
]);
}
/**
* Handle requests for updating the website settings.
*/
public function handleUpdateSettings()
{
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$settingRepository = new SettingRepository();
$success = $settingRepository->updateSettings($_POST);
if ($success) {
phpb_redirect(
phpb_url("website_manager", ["tab" => "settings"]),
[
"message-type" => "success",
"message" => phpb_trans(
"website-manager.settings-updated",
),
],
);
}
phpb_redirect(
phpb_url("website_manager", ["tab" => "settings"]),
[
"message-type" => "error",
"message" => phpb_trans(
"website-manager.invalid-default-language",
),
],
);
}
}
/**
* Handle requests for updating the website menuss.
*/
public function handleUpdateMenus()
{
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$settingRepository = new MenuRepository();
$success = $settingRepository->updateMenus($_POST);
if ($success) {
phpb_redirect(phpb_url("website_manager", ["tab" => "menus"]), [
"message-type" => "success",
"message" => phpb_trans("website-manager.menus-updated"),
]);
}
}
}
/**
* Handle requests for updating the website DB.
*/
public function handleUpdateDB()
{
global $phpb_db;
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$phpb_db->resolveDiffDB();
phpb_redirect(phpb_url("website_manager", ["tab" => "info"]), [
"message-type" => "success",
"message" => phpb_trans("website-manager.db-updated"),
]);
}
}
/**
* Render the website manager overview page.
*/
public function renderOverview()
{
$pageRepository = new PageRepository();
$pages = $pageRepository->getAll();
uasort($pages, function ($a, $b) {
return $a->getRoute() < $b->getRoute() ? -1 : 1;
});
$draftPages = [];
foreach ($pages as $page) {
if ($pageRepository->getPageDraftData($page) === null) {
continue;
}
$route = $page->getRoute();
$draftPages[] = [
"name" => $page->getName(),
"route" => $route,
"previewUrl" => phpb_full_url($page->getPreviewRoute()),
];
}
$activeLanguages = phpb_active_languages();
$pageTranslationCoverage = new PageTranslationService()->getPageCoverage(
$pages,
$activeLanguages,
);
$filesRepository = new UploadRepository();
$files = $filesRepository->getAll();
$menuRepository = new MenuRepository();
$menus = $menuRepository->getHydratedMenus();
$menusJson = json_encode($menus);
$completedTranslations = 0;
foreach ($pageTranslationCoverage as $coverage) {
$completedTranslations += $coverage["completeCount"];
}
$expectedTranslations = count($pages) * count($activeLanguages);
$dashboardSummary = [
"pageCount" => count($pages),
"uploadCount" => count($files),
"menuCount" => count($menus),
"completedTranslations" => $completedTranslations,
"expectedTranslations" => $expectedTranslations,
"translationCoveragePercent" =>
$expectedTranslations > 0
? (int) round(
($completedTranslations / $expectedTranslations) * 100,
)
: null,
"activeLanguageCount" => count($activeLanguages),
];
$menuPages = [];
foreach ($pages as $page) {
$menuPages[] = [
"id" => $page->getId(),
"title" => $page->getName(),
"route" => $page->getRoute(),
];
}
$menuPagesJson = json_encode($menuPages);
$viewFile = "overview";
require __DIR__ . "/resources/layouts/master.php";
}
/**
* Render the quality-check tab with an optional transient report.
*/
public function renderQualityChecks(?array $qualityReport = null)
{
$viewFile = "overview";
require __DIR__ . "/resources/layouts/master.php";
}
/**
* Render the website manager page settings (add/edit page form).
*
* @param PageContract $page
*/
public function renderPageSettings(
?PageContract $page = null,
?string $errorMessage = null,
) {
$action = isset($page) ? "edit" : "create";
$theme = phpb_instance("theme", [
phpb_config("theme"),
phpb_config("theme.active_theme"),
]);
$viewFile = "page-settings";
require __DIR__ . "/resources/layouts/master.php";
}
/**
* Render the website manager menu settings (add/edit menu form).
*/
public function renderMenuSettings()
{
$viewFile = "menu-settings";
require __DIR__ . "/resources/layouts/master.php";
}
/**
* Render a thumbnail for each theme block.
*/
public function renderBlockThumbs()
{
$viewFile = "block-thumbs";
require __DIR__ . "/resources/layouts/master.php";
}
/**
* Render the website manager welcome page for installations without a homepage.
*/
public function renderWelcomePage()
{
$viewFile = "welcome";
require __DIR__ . "/resources/layouts/empty.php";
}
}