add site quality audits and pagebuilder viewport selection
Add published-page accessibility and link checks with localized reports, and add responsive viewport controls to the page builder. Detect schema drift beyond matching hashes and apply lowercase definitions when creating or updating tables. Refresh generated admin, page-builder, and website-manager assets, and add coverage for quality checks, viewport selection, and schema migrations.
This commit is contained in:
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+2
-2
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -41,6 +41,27 @@ return [
|
||||
],
|
||||
'target-redirect' => 'Ziel der Weiterleitung',
|
||||
'files' => 'Dateien',
|
||||
'quality' => 'Qualitätsprüfungen',
|
||||
'quality-heading' => 'Qualitätsprüfung der veröffentlichten Website',
|
||||
'quality-description' => 'Prüft veröffentlichte Seiten auf häufige Barrierefreiheitsprobleme und defekte interne Links oder Uploads.',
|
||||
'quality-synchronous-note' => 'Die Prüfung läuft in dieser Anfrage. Ergebnisse werden nicht gespeichert.',
|
||||
'quality-run-scan' => 'Website prüfen',
|
||||
'quality-running' => 'Veröffentlichte Seiten werden geprüft…',
|
||||
'quality-awaiting-scan' => 'Starten Sie die Prüfung, um veröffentlichte Seitenrouten und aktive Sprachen zu überprüfen.',
|
||||
'quality-pages-checked' => 'Seiten-Sprachen geprüft',
|
||||
'quality-findings-count' => 'Befunde',
|
||||
'quality-errors-count' => 'Seitenfehler',
|
||||
'quality-no-findings' => 'In den geprüften Seiten wurden keine Barrierefreiheits- oder internen Linkprobleme gefunden.',
|
||||
'quality-report' => 'Bericht zur Qualitätsprüfung',
|
||||
'quality-target' => 'Betroffenes Element oder Ziel',
|
||||
'quality-severity-warning' => 'Hinweis',
|
||||
'quality-severity-error' => 'Seitenfehler',
|
||||
'quality-rule-image-alt' => 'Alternativtext für Bilder',
|
||||
'quality-rule-form-control-name' => 'Zugänglicher Name des Formularfelds',
|
||||
'quality-rule-heading-level' => 'Reihenfolge der Überschriftenebenen',
|
||||
'quality-rule-missing-internal-route' => 'Interne Seitenroute nicht gefunden',
|
||||
'quality-rule-missing-local-asset' => 'Lokaler Upload nicht gefunden',
|
||||
'quality-rule-coverage-error' => 'Seite konnte nicht geprüft werden',
|
||||
'settings' => 'Einstellungen',
|
||||
'info' => 'Info',
|
||||
'required' => 'Pflichtfeld',
|
||||
@@ -72,6 +93,10 @@ return [
|
||||
'save-page' => 'Speichern',
|
||||
'view-page' => 'Ansehen',
|
||||
'go-back' => 'Zurück',
|
||||
'viewport-selector' => 'Vorschauansicht',
|
||||
'viewport-desktop' => 'Desktop',
|
||||
'viewport-tablet' => 'Tablet',
|
||||
'viewport-mobile' => 'Mobil',
|
||||
'page' => 'Seite',
|
||||
'page-content' => 'Seiteninhalte',
|
||||
'toastr-changes-saved' => 'Änderungen gespeichert',
|
||||
|
||||
@@ -41,6 +41,27 @@ return [
|
||||
],
|
||||
'target-redirect' => 'Target of redirect',
|
||||
'files' => 'Files',
|
||||
'quality' => 'Quality checks',
|
||||
'quality-heading' => 'Published-site quality audit',
|
||||
'quality-description' => 'Check rendered published pages for common accessibility issues and broken internal links or uploads.',
|
||||
'quality-synchronous-note' => 'This scan runs in the current request. Results are temporary and are not saved.',
|
||||
'quality-run-scan' => 'Run site audit',
|
||||
'quality-running' => 'Checking published pages…',
|
||||
'quality-awaiting-scan' => 'Run the audit to review published page routes and their active languages.',
|
||||
'quality-pages-checked' => 'page locales checked',
|
||||
'quality-findings-count' => 'findings',
|
||||
'quality-errors-count' => 'page errors',
|
||||
'quality-no-findings' => 'No accessibility or internal-link findings were detected in the scanned pages.',
|
||||
'quality-report' => 'Quality audit report',
|
||||
'quality-target' => 'Affected target',
|
||||
'quality-severity-warning' => 'Warning',
|
||||
'quality-severity-error' => 'Page error',
|
||||
'quality-rule-image-alt' => 'Image alternative text',
|
||||
'quality-rule-form-control-name' => 'Form control accessible name',
|
||||
'quality-rule-heading-level' => 'Heading level order',
|
||||
'quality-rule-missing-internal-route' => 'Missing internal page route',
|
||||
'quality-rule-missing-local-asset' => 'Missing local upload',
|
||||
'quality-rule-coverage-error' => 'Page could not be checked',
|
||||
'settings' => 'Settings',
|
||||
'info' => 'Info',
|
||||
'required' => 'Required',
|
||||
@@ -72,6 +93,10 @@ return [
|
||||
'save-page' => 'Save',
|
||||
'view-page' => 'View',
|
||||
'go-back' => 'Back',
|
||||
'viewport-selector' => 'Preview viewport',
|
||||
'viewport-desktop' => 'Desktop',
|
||||
'viewport-tablet' => 'Tablet',
|
||||
'viewport-mobile' => 'Mobile',
|
||||
'page' => 'Page',
|
||||
'page-content' => 'Page contents',
|
||||
'toastr-changes-saved' => 'Changes saved',
|
||||
|
||||
@@ -40,6 +40,27 @@ return [
|
||||
],
|
||||
'target-redirect' => 'Mål för omdirigering',
|
||||
'files' => 'Filer',
|
||||
'quality' => 'Kvalitetskontroller',
|
||||
'quality-heading' => 'Kvalitetsgranskning av publicerade sidor',
|
||||
'quality-description' => 'Kontrollera publicerade sidor efter vanliga tillgänglighetsproblem och trasiga interna länkar eller uppladdningar.',
|
||||
'quality-synchronous-note' => 'Granskningen körs i den aktuella förfrågan. Resultaten sparas inte.',
|
||||
'quality-run-scan' => 'Granska webbplatsen',
|
||||
'quality-running' => 'Kontrollerar publicerade sidor…',
|
||||
'quality-awaiting-scan' => 'Kör granskningen för att kontrollera publicerade sidrutter och aktiva språk.',
|
||||
'quality-pages-checked' => 'sidornas språk kontrollerade',
|
||||
'quality-findings-count' => 'resultat',
|
||||
'quality-errors-count' => 'sidfel',
|
||||
'quality-no-findings' => 'Inga tillgänglighetsproblem eller interna länkproblem hittades på de granskade sidorna.',
|
||||
'quality-report' => 'Kvalitetsrapport',
|
||||
'quality-target' => 'Berört element eller mål',
|
||||
'quality-severity-warning' => 'Varning',
|
||||
'quality-severity-error' => 'Sidfel',
|
||||
'quality-rule-image-alt' => 'Alternativtext för bild',
|
||||
'quality-rule-form-control-name' => 'Tillgängligt namn på formulärkontroll',
|
||||
'quality-rule-heading-level' => 'Rubriknivåernas ordning',
|
||||
'quality-rule-missing-internal-route' => 'Intern sidrutt saknas',
|
||||
'quality-rule-missing-local-asset' => 'Lokal uppladdning saknas',
|
||||
'quality-rule-coverage-error' => 'Sidan kunde inte kontrolleras',
|
||||
'settings' => 'Inställningar',
|
||||
'info' => 'Info',
|
||||
'required' => 'Obligatoriskt',
|
||||
@@ -71,6 +92,10 @@ return [
|
||||
'save-page' => 'Spara',
|
||||
'view-page' => 'Visa',
|
||||
'go-back' => 'Tillbaka',
|
||||
'viewport-selector' => 'Förhandsgranskningens vy',
|
||||
'viewport-desktop' => 'Dator',
|
||||
'viewport-tablet' => 'Surfplatta',
|
||||
'viewport-mobile' => 'Mobil',
|
||||
'page' => 'Sida',
|
||||
'page-content' => 'Sidinnehåll',
|
||||
'toastr-changes-saved' => 'Ändringarna har sparats',
|
||||
|
||||
@@ -241,6 +241,7 @@ class DB
|
||||
}
|
||||
|
||||
public function resolveDiffDB() {
|
||||
$definitions = $this->getDBDefinition();
|
||||
$diff = $this->diffDB();
|
||||
foreach ($diff as $table => $tableDiff) {
|
||||
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
|
||||
@@ -248,20 +249,29 @@ class DB
|
||||
$this->query("CREATE TABLE {$tableName} (`id` int NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
|
||||
$this->query("ALTER TABLE {$tableName} ADD PRIMARY KEY (`id`)");
|
||||
$this->query("ALTER TABLE {$tableName} MODIFY `id` int NOT NULL AUTO_INCREMENT");
|
||||
} elseif (is_array($tableDiff)) {
|
||||
$tableDefinition = $definitions[$table] ?? ['columns' => [], 'uniqueKeys' => []];
|
||||
$tableDiff = [
|
||||
'columns' => $tableDefinition['columns'] ?? [],
|
||||
'uniqueKeys' => [],
|
||||
];
|
||||
foreach ($tableDefinition['uniqueKeys'] ?? [] as $key => $columns) {
|
||||
$tableDiff['uniqueKeys'][$key] = '`' . implode('`,`', $columns) . '`';
|
||||
}
|
||||
}
|
||||
if (is_array($tableDiff)) {
|
||||
foreach ($tableDiff['columns'] as $column => $columnDefinition) {
|
||||
// Validate column name to prevent SQL injection
|
||||
$sanitizedColumn = phpb_remove_non_alpha_numeric($column);
|
||||
if (empty($sanitizedColumn)) continue;
|
||||
// Validate column definition against a safe pattern
|
||||
if (!preg_match('/^[A-Z\s(),0-9_`]+$/', $columnDefinition)) continue;
|
||||
if (!is_string($columnDefinition) || !preg_match('/^[A-Z\s(),0-9_`]+$/i', $columnDefinition)) continue;
|
||||
$this->query("ALTER TABLE {$tableName} ADD {$sanitizedColumn} {$columnDefinition}");
|
||||
}
|
||||
foreach ($tableDiff['uniqueKeys'] as $key => $keyDefinition) {
|
||||
// Validate key name and definition
|
||||
$sanitizedKey = phpb_remove_non_alpha_numeric($key);
|
||||
if (empty($sanitizedKey)) continue;
|
||||
if (!preg_match('/^[A-Z,`\s_]+$/', $keyDefinition)) continue;
|
||||
if (!preg_match('/^[A-Z,`\s_]+$/i', $keyDefinition)) continue;
|
||||
$this->query("ALTER TABLE {$tableName} ADD UNIQUE KEY {$sanitizedKey} ($keyDefinition)");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { bindViewportSelector } from './viewport-selection.js';
|
||||
|
||||
|
||||
const editorEl = document.querySelector('.gjs-editor');
|
||||
const editorEl = document.querySelector('.gjs-editor');
|
||||
const toggleSidebarBtn = document.getElementById('toggle-sidebar');
|
||||
const sidebarHeader = document.getElementById('sidebar-header');
|
||||
const sidebarBottomButtons = document.getElementById('sidebar-bottom-buttons');
|
||||
const panelsEl = document.querySelector('.gjs-pn-panels');
|
||||
const gjsEl = document.getElementById('gjs');
|
||||
const viewportSelector = document.getElementById('viewport-select');
|
||||
|
||||
if (window.editor) {
|
||||
bindViewportSelector(window.editor, viewportSelector);
|
||||
}
|
||||
|
||||
if (editorEl && toggleSidebarBtn) {
|
||||
editorEl.appendChild(toggleSidebarBtn);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
export function bindViewportSelector(editor, selector) {
|
||||
if (!editor || typeof editor.setDevice !== 'function' || !selector || typeof selector.addEventListener !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
selector.addEventListener('change', function() {
|
||||
if (selector.value) {
|
||||
editor.setDevice(selector.value);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,13 @@ return [
|
||||
'autoload' => false,
|
||||
'autosave' => false
|
||||
],
|
||||
'deviceManager' => [
|
||||
'devices' => [
|
||||
['name' => 'Desktop', 'width' => ''],
|
||||
['name' => 'Tablet', 'width' => '768px', 'widthMedia' => '992px'],
|
||||
['name' => 'Mobile', 'width' => '375px', 'widthMedia' => '480px'],
|
||||
],
|
||||
],
|
||||
'canvasCss' => 'body {height: auto;}', // prevent scrollbar jump on pasting in CKEditor
|
||||
'assetManager' => [
|
||||
'upload' => phpb_url('pagebuilder', ['action' => 'upload', 'page' => $page->getId()]),
|
||||
|
||||
@@ -103,12 +103,12 @@ require __DIR__ . '/grapesjs/trait-manager.php';
|
||||
<button id="toggle-sidebar" class="btn btn-sm btn-ghost">
|
||||
<i class="fa fa-bars"></i>
|
||||
</button>
|
||||
<div id="sidebar-header" class="flex items-center justify-between px-2">
|
||||
<div id="sidebar-header" class="flex flex-wrap items-center justify-between gap-1 px-2">
|
||||
<?php
|
||||
if (sizeof(phpb_active_languages()) > 1):
|
||||
?>
|
||||
<div id="language-selector" class="ml-auto">
|
||||
<select class="select select-bordered select-xs text-xs">
|
||||
<div id="language-selector">
|
||||
<select class="select select-xs w-24 text-xs">
|
||||
<?php
|
||||
foreach (phpb_active_languages() as $languageCode => $languageTranslation):
|
||||
?>
|
||||
@@ -123,6 +123,14 @@ require __DIR__ . '/grapesjs/trait-manager.php';
|
||||
<?php
|
||||
endif;
|
||||
?>
|
||||
<div id="viewport-selector" class="ml-auto">
|
||||
<label class="sr-only" for="viewport-select"><?= phpb_trans('pagebuilder.viewport-selector') ?></label>
|
||||
<select id="viewport-select" class="select select-xs w-28 text-xs" aria-label="<?= phpb_e(phpb_trans('pagebuilder.viewport-selector')) ?>">
|
||||
<option value="Desktop"><?= phpb_trans('pagebuilder.viewport-desktop') ?></option>
|
||||
<option value="Tablet"><?= phpb_trans('pagebuilder.viewport-tablet') ?></option>
|
||||
<option value="Mobile"><?= phpb_trans('pagebuilder.viewport-mobile') ?></option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="sidebar-bottom-buttons" class="flex items-center justify-between">
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
<?php
|
||||
|
||||
namespace Plugi\Modules\WebsiteManager;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
use RuntimeException;
|
||||
|
||||
class SiteQualityAnalyzer
|
||||
{
|
||||
protected $routes;
|
||||
protected $assets;
|
||||
protected $baseUrl;
|
||||
protected $basePath;
|
||||
protected $uploadsPath;
|
||||
|
||||
public function __construct(array $routes, array $assets, ?string $baseUrl = null, ?string $uploadsUrl = null)
|
||||
{
|
||||
$this->baseUrl = $baseUrl ?? ($_ENV['BASE_URL'] ?? '');
|
||||
$this->basePath = $this->normalizePath(rawurldecode(parse_url($this->baseUrl, PHP_URL_PATH) ?: ''));
|
||||
$uploadsUrl = $uploadsUrl ?? (function_exists('phpb_config') ? phpb_config('general.uploads_url') : '/uploads');
|
||||
$uploadsPath = $this->normalizePath(rawurldecode((string) $uploadsUrl));
|
||||
$this->uploadsPath = $this->stripBasePath($uploadsPath) ?? $uploadsPath;
|
||||
|
||||
$this->routes = [];
|
||||
foreach ($routes as $route) {
|
||||
if (is_string($route) && trim($route) !== '') {
|
||||
$this->routes[$this->normalizePath(rawurldecode($route))] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$this->assets = [];
|
||||
foreach ($assets as $asset) {
|
||||
if (is_string($asset) && trim($asset) !== '') {
|
||||
$assetPath = $this->normalizeInventoryPath($asset);
|
||||
if ($assetPath !== null) {
|
||||
$this->assets[$assetPath] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspect rendered page markup and return actionable findings.
|
||||
*/
|
||||
public function analyze(string $html, string $pageRoute = '/'): array
|
||||
{
|
||||
if (! class_exists(DOMDocument::class)) {
|
||||
throw new RuntimeException('The PHP DOM extension is required to inspect rendered markup.');
|
||||
}
|
||||
|
||||
$document = new DOMDocument();
|
||||
$previousErrorMode = libxml_use_internal_errors(true);
|
||||
libxml_clear_errors();
|
||||
$loaded = $document->loadHTML('<?xml encoding="UTF-8">' . $html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_HTML_NODEFDTD);
|
||||
$parseErrors = libxml_get_errors();
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previousErrorMode);
|
||||
|
||||
if (! $loaded) {
|
||||
throw new RuntimeException('The rendered page markup could not be parsed.');
|
||||
}
|
||||
foreach ($parseErrors as $parseError) {
|
||||
if ($parseError->level === LIBXML_ERR_FATAL) {
|
||||
throw new RuntimeException('The rendered page markup could not be parsed.');
|
||||
}
|
||||
}
|
||||
|
||||
$xpath = new DOMXPath($document);
|
||||
$findings = array_merge(
|
||||
$this->findMissingImageAlternatives($xpath),
|
||||
$this->findUnnamedFormControls($xpath),
|
||||
$this->findSkippedHeadingLevels($xpath),
|
||||
$this->findBrokenLinks($xpath, $pageRoute)
|
||||
);
|
||||
|
||||
return $findings;
|
||||
}
|
||||
|
||||
private function findMissingImageAlternatives(DOMXPath $xpath): array
|
||||
{
|
||||
$findings = [];
|
||||
foreach ($xpath->query('//img[not(@alt)]') as $image) {
|
||||
if (! ($image instanceof DOMElement)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$target = 'img';
|
||||
if ($image->hasAttribute('src') && trim($image->getAttribute('src')) !== '') {
|
||||
$target .= '[src="' . trim($image->getAttribute('src')) . '"]';
|
||||
}
|
||||
$findings[] = [
|
||||
'rule' => 'image-alt',
|
||||
'severity' => 'warning',
|
||||
'explanation' => 'Add an alt attribute that describes the image, or use an empty alt attribute when the image is decorative.',
|
||||
'target' => $target,
|
||||
];
|
||||
}
|
||||
|
||||
return $findings;
|
||||
}
|
||||
|
||||
private function findUnnamedFormControls(DOMXPath $xpath): array
|
||||
{
|
||||
$idText = [];
|
||||
foreach ($xpath->query('//*[@id]') as $element) {
|
||||
if ($element instanceof DOMElement) {
|
||||
$idText[$element->getAttribute('id')] = $this->hasText($element->textContent);
|
||||
}
|
||||
}
|
||||
|
||||
$findings = [];
|
||||
foreach ($xpath->query('//input[not(translate(@type,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")="hidden")] | //select | //textarea | //button') as $control) {
|
||||
if (! ($control instanceof DOMElement) || $this->hasAccessibleName($control, $xpath, $idText)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tag = strtolower($control->tagName);
|
||||
$target = $tag;
|
||||
if ($control->hasAttribute('id') && trim($control->getAttribute('id')) !== '') {
|
||||
$target .= '#' . trim($control->getAttribute('id'));
|
||||
} elseif ($control->hasAttribute('name') && trim($control->getAttribute('name')) !== '') {
|
||||
$target .= '[name="' . trim($control->getAttribute('name')) . '"]';
|
||||
}
|
||||
|
||||
$findings[] = [
|
||||
'rule' => 'form-control-name',
|
||||
'severity' => 'warning',
|
||||
'explanation' => 'Give this form control an accessible name using a visible label, aria-label, or aria-labelledby.',
|
||||
'target' => $target,
|
||||
];
|
||||
}
|
||||
|
||||
return $findings;
|
||||
}
|
||||
|
||||
private function hasAccessibleName(DOMElement $control, DOMXPath $xpath, array $idText): bool
|
||||
{
|
||||
foreach (['aria-label', 'title'] as $attribute) {
|
||||
if ($control->hasAttribute($attribute) && $this->hasText($control->getAttribute($attribute))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($control->hasAttribute('aria-labelledby')) {
|
||||
foreach (preg_split('/\s+/', trim($control->getAttribute('aria-labelledby'))) as $labelId) {
|
||||
if ($labelId !== '' && ! empty($idText[$labelId])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($control->tagName === 'button' && $this->hasText($control->textContent)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($control->tagName === 'input') {
|
||||
$type = strtolower($control->getAttribute('type'));
|
||||
if ($type === 'image' && $this->hasText($control->getAttribute('alt'))) {
|
||||
return true;
|
||||
}
|
||||
if (in_array($type, ['submit', 'reset'], true)) {
|
||||
return true;
|
||||
}
|
||||
if (in_array($type, ['button', 'submit', 'reset'], true) && $this->hasText($control->getAttribute('value'))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($control->hasAttribute('id')) {
|
||||
$controlId = $control->getAttribute('id');
|
||||
foreach ($xpath->query('//label[@for]') as $label) {
|
||||
if ($label instanceof DOMElement
|
||||
&& $label->getAttribute('for') === $controlId
|
||||
&& $this->hasText($label->textContent)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for ($parent = $control->parentNode; $parent !== null; $parent = $parent->parentNode) {
|
||||
if ($parent instanceof DOMElement && strtolower($parent->tagName) === 'label' && $this->hasText($parent->textContent)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function findSkippedHeadingLevels(DOMXPath $xpath): array
|
||||
{
|
||||
$findings = [];
|
||||
$previousLevel = null;
|
||||
foreach ($xpath->query('//h1 | //h2 | //h3 | //h4 | //h5 | //h6') as $heading) {
|
||||
if (! ($heading instanceof DOMElement)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$level = (int) substr(strtolower($heading->tagName), 1);
|
||||
if ($previousLevel !== null && $level > $previousLevel + 1) {
|
||||
$findings[] = [
|
||||
'rule' => 'heading-level',
|
||||
'severity' => 'warning',
|
||||
'explanation' => sprintf('The heading level jumps from h%d to h%d; use the intervening heading level.', $previousLevel, $level),
|
||||
'target' => 'h' . $level,
|
||||
];
|
||||
}
|
||||
$previousLevel = $level;
|
||||
}
|
||||
|
||||
return $findings;
|
||||
}
|
||||
|
||||
private function findBrokenLinks(DOMXPath $xpath, string $pageRoute): array
|
||||
{
|
||||
$findings = [];
|
||||
foreach ($xpath->query('//a[@href] | //area[@href]') as $link) {
|
||||
if (! ($link instanceof DOMElement)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$url = trim($link->getAttribute('href'));
|
||||
$path = $this->resolveInternalPath($url, $pageRoute);
|
||||
if ($path === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->isUploadsPath($path)) {
|
||||
if (! isset($this->assets[$path])) {
|
||||
$findings[] = [
|
||||
'rule' => 'missing-local-asset',
|
||||
'severity' => 'warning',
|
||||
'explanation' => 'This link points to a site upload that is not present in the configured public uploads inventory.',
|
||||
'target' => $url,
|
||||
];
|
||||
}
|
||||
} elseif (! $this->routeExists($path)) {
|
||||
$findings[] = [
|
||||
'rule' => 'missing-internal-route',
|
||||
'severity' => 'warning',
|
||||
'explanation' => 'This same-site link does not match a published page route.',
|
||||
'target' => $url,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($xpath->query('//img[@src] | //script[@src] | //iframe[@src] | //source[@src] | //audio[@src] | //video[@src] | //track[@src] | //input[@src] | //link[@href] | //video[@poster]') as $assetElement) {
|
||||
if (! ($assetElement instanceof DOMElement)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$attribute = $assetElement->hasAttribute('src') ? 'src' : ($assetElement->hasAttribute('poster') ? 'poster' : 'href');
|
||||
$url = trim($assetElement->getAttribute($attribute));
|
||||
$path = $this->resolveInternalPath($url, $pageRoute);
|
||||
if ($path !== null && $this->isUploadsPath($path) && ! isset($this->assets[$path])) {
|
||||
$findings[] = [
|
||||
'rule' => 'missing-local-asset',
|
||||
'severity' => 'warning',
|
||||
'explanation' => 'This element references a site upload that is not present in the configured public uploads inventory.',
|
||||
'target' => $url,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $findings;
|
||||
}
|
||||
|
||||
private function resolveInternalPath(string $url, string $pageRoute): ?string
|
||||
{
|
||||
if ($url === '' || str_starts_with($url, '#')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parts = parse_url($url);
|
||||
if ($parts === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$scheme = strtolower($parts['scheme'] ?? '');
|
||||
if ($scheme !== '' && ! in_array($scheme, ['http', 'https'], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isset($parts['host']) && ! $this->isSameSiteHost($parts['host'], $parts['port'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = $parts['path'] ?? '';
|
||||
if ($path === '') {
|
||||
return $this->normalizePath(rawurldecode($pageRoute));
|
||||
}
|
||||
|
||||
$path = rawurldecode($path);
|
||||
if (! str_starts_with($path, '/')) {
|
||||
$currentPath = $this->normalizePath(rtrim($this->basePath, '/') . '/' . ltrim(rawurldecode($pageRoute), '/'));
|
||||
$currentDirectory = substr($currentPath, 0, (int) strrpos($currentPath, '/'));
|
||||
$path = $this->normalizePath($currentDirectory . '/' . $path);
|
||||
return $this->toAppPath($path);
|
||||
}
|
||||
|
||||
$path = $this->normalizePath($path);
|
||||
return $this->toAppPath($path);
|
||||
}
|
||||
|
||||
private function normalizeInventoryPath(string $asset): ?string
|
||||
{
|
||||
$parts = parse_url($asset);
|
||||
if ($parts === false) {
|
||||
return null;
|
||||
}
|
||||
if (isset($parts['host']) && ! $this->isSameSiteHost($parts['host'], $parts['port'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = rawurldecode($parts['path'] ?? '');
|
||||
if ($path === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = $this->normalizePath($path);
|
||||
$appRelativePath = $this->stripBasePath($path);
|
||||
return $appRelativePath ?? $path;
|
||||
}
|
||||
|
||||
private function isSameSiteHost(string $host, ?int $port): bool
|
||||
{
|
||||
$base = parse_url($this->baseUrl);
|
||||
if (! isset($base['host']) || strtolower($host) !== strtolower($base['host'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($port === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$basePort = $base['port'] ?? (($base['scheme'] ?? '') === 'https' ? 443 : 80);
|
||||
return $port === $basePort;
|
||||
}
|
||||
|
||||
private function stripBasePath(string $path): ?string
|
||||
{
|
||||
if ($this->basePath === '/' || $this->basePath === '') {
|
||||
return $path;
|
||||
}
|
||||
|
||||
if ($path === $this->basePath) {
|
||||
return '/';
|
||||
}
|
||||
if (str_starts_with($path, rtrim($this->basePath, '/') . '/')) {
|
||||
return $this->normalizePath(substr($path, strlen(rtrim($this->basePath, '/'))));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function toAppPath(string $path): string
|
||||
{
|
||||
$appPath = $this->stripBasePath($path);
|
||||
if ($appPath !== null) {
|
||||
return $appPath;
|
||||
}
|
||||
|
||||
return $this->basePath === '' || $this->basePath === '/'
|
||||
? $path
|
||||
: '/__outside_app_base__' . $path;
|
||||
}
|
||||
|
||||
private function normalizePath(string $path): string
|
||||
{
|
||||
$segments = [];
|
||||
foreach (explode('/', str_replace('\\', '/', $path)) as $segment) {
|
||||
if ($segment === '' || $segment === '.') {
|
||||
continue;
|
||||
}
|
||||
if ($segment === '..') {
|
||||
if (! empty($segments)) {
|
||||
array_pop($segments);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$segments[] = $segment;
|
||||
}
|
||||
|
||||
return '/' . implode('/', $segments);
|
||||
}
|
||||
|
||||
private function isUploadsPath(string $path): bool
|
||||
{
|
||||
return $path === $this->uploadsPath
|
||||
|| str_starts_with($path, rtrim($this->uploadsPath, '/') . '/');
|
||||
}
|
||||
|
||||
private function routeExists(string $path): bool
|
||||
{
|
||||
if (isset($this->routes[$path])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$pathSegments = $this->pathSegments($path);
|
||||
foreach (array_keys($this->routes) as $route) {
|
||||
$routeSegments = $this->pathSegments($route);
|
||||
$hasWildcard = end($routeSegments) === '*';
|
||||
if ((! $hasWildcard && count($routeSegments) !== count($pathSegments))
|
||||
|| ($hasWildcard && count($pathSegments) < count($routeSegments) - 1)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($routeSegments as $index => $routeSegment) {
|
||||
if ($routeSegment === '*') {
|
||||
return true;
|
||||
}
|
||||
if (preg_match('/^\{[^{}]+\}$/', $routeSegment) === 1) {
|
||||
continue;
|
||||
}
|
||||
if (! isset($pathSegments[$index]) || $pathSegments[$index] !== $routeSegment) {
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function pathSegments(string $path): array
|
||||
{
|
||||
$trimmedPath = trim($path, '/');
|
||||
return $trimmedPath === '' ? [] : explode('/', $trimmedPath);
|
||||
}
|
||||
|
||||
private function hasText(?string $text): bool
|
||||
{
|
||||
return trim(preg_replace('/\s+/u', ' ', (string) $text)) !== '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
<?php
|
||||
|
||||
namespace Plugi\Modules\WebsiteManager;
|
||||
|
||||
use Throwable;
|
||||
|
||||
class SiteQualityCheckService
|
||||
{
|
||||
protected $pageRepository;
|
||||
protected $translationRepository;
|
||||
protected $uploadRepository;
|
||||
protected $renderPage;
|
||||
protected $pageBuilder;
|
||||
|
||||
public function __construct($pageRepository = null, $translationRepository = null, $uploadRepository = null, ?callable $renderPage = null)
|
||||
{
|
||||
$this->pageRepository = $pageRepository;
|
||||
$this->translationRepository = $translationRepository;
|
||||
$this->uploadRepository = $uploadRepository;
|
||||
$this->renderPage = $renderPage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Audit canonical pages in every active language and return a transient report.
|
||||
*/
|
||||
public function run(): array
|
||||
{
|
||||
$pageRepository = $this->pageRepository ?? new \Plugi\Repositories\PageRepository();
|
||||
$translationRepository = $this->translationRepository ?? new \Plugi\Repositories\PageTranslationRepository();
|
||||
$pages = $pageRepository->getAll();
|
||||
$pagesById = [];
|
||||
foreach ($pages as $page) {
|
||||
$pageId = $this->getPageId($page);
|
||||
if ($pageId !== null) {
|
||||
$pagesById[(string) $pageId] = $page;
|
||||
}
|
||||
}
|
||||
|
||||
$activeLanguages = function_exists('phpb_active_languages') ? array_keys(phpb_active_languages()) : [];
|
||||
$translationForeignKey = function_exists('phpb_config')
|
||||
? (phpb_config('page.translation.foreign_key') ?: 'page_id')
|
||||
: 'page_id';
|
||||
$translationsByPage = [];
|
||||
$routes = [];
|
||||
if (! empty($pagesById)) {
|
||||
foreach ($translationRepository->getForPages(array_keys($pagesById)) as $translation) {
|
||||
$pageId = $this->readValue($translation, $translationForeignKey);
|
||||
$locale = $this->readValue($translation, 'locale');
|
||||
$route = $this->readValue($translation, 'route');
|
||||
if ($pageId === null || ! isset($pagesById[(string) $pageId])
|
||||
|| ! is_string($locale) || ! in_array($locale, $activeLanguages, true)
|
||||
|| ! is_string($route) || trim($route) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$translationsByPage[(string) $pageId][$locale] = $route;
|
||||
$routes[] = $route;
|
||||
}
|
||||
}
|
||||
|
||||
$uploadsUrl = function_exists('phpb_config') ? (phpb_config('general.uploads_url') ?: '/uploads') : '/uploads';
|
||||
$analyzer = new SiteQualityAnalyzer(
|
||||
$routes,
|
||||
$this->getVerifiedAssetUrls($uploadsUrl),
|
||||
$_ENV['BASE_URL'] ?? '',
|
||||
$uploadsUrl
|
||||
);
|
||||
|
||||
$report = [
|
||||
'pages_checked' => 0,
|
||||
'findings' => [],
|
||||
'errors' => [],
|
||||
];
|
||||
|
||||
foreach ($translationsByPage as $pageId => $localizedRoutes) {
|
||||
$pageId = (string) $pageId;
|
||||
$page = $pagesById[$pageId];
|
||||
foreach ($localizedRoutes as $locale => $route) {
|
||||
$report['pages_checked']++;
|
||||
try {
|
||||
$html = $this->render($page, $locale);
|
||||
foreach ($analyzer->analyze($html, $route) as $finding) {
|
||||
$report['findings'][] = $this->addPageContext($finding, $page, $pageId, $locale, $route);
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
$report['errors'][] = [
|
||||
'page_id' => $pageId,
|
||||
'page_name' => $this->getPageName($page),
|
||||
'route' => $route,
|
||||
'locale' => $locale,
|
||||
'rule' => 'coverage-error',
|
||||
'severity' => 'error',
|
||||
'explanation' => 'This page could not be inspected: ' . $exception->getMessage(),
|
||||
'target' => $route,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
private function render($page, string $locale): string
|
||||
{
|
||||
if ($this->renderPage !== null) {
|
||||
$html = call_user_func($this->renderPage, $page, $locale);
|
||||
} else {
|
||||
if ($this->pageBuilder === null) {
|
||||
$this->pageBuilder = function_exists('phpb_instance') ? phpb_instance('pagebuilder') : null;
|
||||
}
|
||||
if (! is_object($this->pageBuilder) || ! method_exists($this->pageBuilder, 'renderPage')) {
|
||||
throw new \RuntimeException('The configured page renderer is unavailable.');
|
||||
}
|
||||
$html = $this->pageBuilder->renderPage($page, $locale);
|
||||
}
|
||||
|
||||
if (! is_string($html)) {
|
||||
throw new \RuntimeException('The page renderer did not return HTML.');
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
private function getVerifiedAssetUrls(string $uploadsUrl): array
|
||||
{
|
||||
$uploadRepository = $this->uploadRepository ?? new \Plugi\Repositories\UploadRepository();
|
||||
$configuredUploadFolder = function_exists('phpb_config') ? phpb_config('storage.uploads_folder') : null;
|
||||
$uploadRoot = is_string($configuredUploadFolder) ? realpath($configuredUploadFolder) : false;
|
||||
if ($uploadRoot === false || ! is_dir($uploadRoot)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$assets = [];
|
||||
foreach ($uploadRepository->getAll() as $upload) {
|
||||
$serverFile = $this->readValue($upload, 'server_file');
|
||||
$publicId = $this->readValue($upload, 'public_id');
|
||||
$originalFile = $this->readValue($upload, 'original_file');
|
||||
if (! is_string($serverFile) || ! is_string($publicId) || ! is_string($originalFile)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$resolvedFile = realpath($uploadRoot . DIRECTORY_SEPARATOR . ltrim($serverFile, '/\\'));
|
||||
if ($resolvedFile === false || ! is_file($resolvedFile)
|
||||
|| ! str_starts_with($resolvedFile, rtrim($uploadRoot, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$encodedPublicId = implode('/', array_map('rawurlencode', explode('/', $publicId)));
|
||||
$encodedOriginalFile = implode('/', array_map('rawurlencode', explode('/', $originalFile)));
|
||||
$assets[] = rtrim($uploadsUrl, '/') . '/' . $encodedPublicId . '/' . $encodedOriginalFile;
|
||||
}
|
||||
|
||||
return $assets;
|
||||
}
|
||||
|
||||
private function addPageContext(array $finding, $page, string $pageId, string $locale, string $route): array
|
||||
{
|
||||
return array_merge([
|
||||
'page_id' => $pageId,
|
||||
'page_name' => $this->getPageName($page),
|
||||
'route' => $route,
|
||||
'locale' => $locale,
|
||||
], $finding);
|
||||
}
|
||||
|
||||
private function getPageId($page)
|
||||
{
|
||||
if (is_object($page) && method_exists($page, 'getId')) {
|
||||
return $page->getId();
|
||||
}
|
||||
return $this->readValue($page, 'id');
|
||||
}
|
||||
|
||||
private function getPageName($page): string
|
||||
{
|
||||
if (is_object($page) && method_exists($page, 'getName')) {
|
||||
return (string) $page->getName();
|
||||
}
|
||||
return (string) ($this->readValue($page, 'name') ?? '');
|
||||
}
|
||||
|
||||
private function readValue($record, string $key)
|
||||
{
|
||||
if (is_array($record)) {
|
||||
return $record[$key] ?? null;
|
||||
}
|
||||
if (is_object($record) && method_exists($record, 'get')) {
|
||||
return $record->get($key);
|
||||
}
|
||||
if (is_object($record) && isset($record->{$key})) {
|
||||
return $record->{$key};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,16 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
exit();
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -223,6 +233,15 @@ class WebsiteManager implements WebsiteManagerContract
|
||||
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).
|
||||
*
|
||||
|
||||
@@ -16,6 +16,11 @@ return [
|
||||
'include' => __DIR__ . '/files.php',
|
||||
'icon' => '<i class="ph ph-folder-notch-open"></i>',
|
||||
],
|
||||
'quality' => [
|
||||
'title' => phpb_trans('website-manager.quality'),
|
||||
'include' => __DIR__ . '/quality.php',
|
||||
'icon' => '<i class="ph ph-check-circle"></i>',
|
||||
],
|
||||
'settings' => [
|
||||
'title' => phpb_trans('website-manager.settings'),
|
||||
'include' => __DIR__ . '/settings.php',
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
$qualityReport = isset($qualityReport) && is_array($qualityReport) ? $qualityReport : null;
|
||||
$qualityFindings = $qualityReport['findings'] ?? [];
|
||||
$qualityErrors = $qualityReport['errors'] ?? [];
|
||||
$qualityItems = array_merge($qualityFindings, $qualityErrors);
|
||||
$qualityGroups = [];
|
||||
$qualityRuleLabels = [
|
||||
'image-alt' => phpb_trans('website-manager.quality-rule-image-alt'),
|
||||
'form-control-name' => phpb_trans('website-manager.quality-rule-form-control-name'),
|
||||
'heading-level' => phpb_trans('website-manager.quality-rule-heading-level'),
|
||||
'missing-internal-route' => phpb_trans('website-manager.quality-rule-missing-internal-route'),
|
||||
'missing-local-asset' => phpb_trans('website-manager.quality-rule-missing-local-asset'),
|
||||
'coverage-error' => phpb_trans('website-manager.quality-rule-coverage-error'),
|
||||
];
|
||||
|
||||
foreach ($qualityItems as $qualityItem) {
|
||||
$pageId = (string) ($qualityItem['page_id'] ?? '');
|
||||
$locale = (string) ($qualityItem['locale'] ?? '');
|
||||
$groupKey = $pageId . '|' . $locale;
|
||||
if (! isset($qualityGroups[$groupKey])) {
|
||||
$qualityGroups[$groupKey] = [
|
||||
'page_id' => $pageId,
|
||||
'page_name' => (string) ($qualityItem['page_name'] ?? ''),
|
||||
'route' => (string) ($qualityItem['route'] ?? ''),
|
||||
'locale' => $locale,
|
||||
'rules' => [],
|
||||
];
|
||||
}
|
||||
$rule = (string) ($qualityItem['rule'] ?? '');
|
||||
$qualityGroups[$groupKey]['rules'][$rule][] = $qualityItem;
|
||||
}
|
||||
?>
|
||||
<section class="space-y-5">
|
||||
<header class="space-y-1">
|
||||
<h2 class="text-xl font-bold tracking-tight text-base-content"><?= phpb_trans('website-manager.quality-heading') ?></h2>
|
||||
<p class="max-w-3xl text-sm leading-relaxed text-base-content/60"><?= phpb_trans('website-manager.quality-description') ?></p>
|
||||
</header>
|
||||
|
||||
<div class="card card-border bg-base-100 shadow-sm">
|
||||
<div class="card-body gap-4 p-4 sm:p-6">
|
||||
<p class="text-sm leading-relaxed text-base-content/70"><?= phpb_trans('website-manager.quality-synchronous-note') ?></p>
|
||||
<form method="post" action="<?= phpb_e(phpb_url('website_manager', ['route' => 'quality', 'action' => 'scan', 'tab' => 'quality'])) ?>" x-data="{scanning: false}" @submit="scanning = true">
|
||||
<?php phpb_csrf_field(); ?>
|
||||
<div class="mb-4" role="status" x-cloak x-show="scanning">
|
||||
<div class="alert alert-info alert-soft">
|
||||
<i class="ph ph-spinner-gap animate-spin" aria-hidden="true"></i>
|
||||
<span><?= phpb_trans('website-manager.quality-running') ?></span>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn" type="submit" :disabled="scanning">
|
||||
<i class="ph ph-magnifying-glass" aria-hidden="true"></i>
|
||||
<span x-show="!scanning"><?= phpb_trans('website-manager.quality-run-scan') ?></span>
|
||||
<span x-cloak x-show="scanning"><?= phpb_trans('website-manager.quality-running') ?></span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($qualityReport === null): ?>
|
||||
<div class="alert alert-info alert-soft" role="status">
|
||||
<i class="ph ph-info" aria-hidden="true"></i>
|
||||
<span><?= phpb_trans('website-manager.quality-awaiting-scan') ?></span>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="flex flex-wrap items-center gap-3 rounded-box border border-base-300 bg-base-100 px-4 py-3">
|
||||
<span class="badge badge-outline"><?= (int) ($qualityReport['pages_checked'] ?? 0) ?> <?= phpb_trans('website-manager.quality-pages-checked') ?></span>
|
||||
<span class="badge badge-outline"><?= count($qualityFindings) ?> <?= phpb_trans('website-manager.quality-findings-count') ?></span>
|
||||
<span class="badge badge-outline"><?= count($qualityErrors) ?> <?= phpb_trans('website-manager.quality-errors-count') ?></span>
|
||||
</div>
|
||||
|
||||
<?php if (empty($qualityItems)): ?>
|
||||
<div class="alert alert-success alert-soft" role="status">
|
||||
<i class="ph ph-check-circle" aria-hidden="true"></i>
|
||||
<span><?= phpb_trans('website-manager.quality-no-findings') ?></span>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<section class="space-y-4" aria-label="<?= phpb_e(phpb_trans('website-manager.quality-report')) ?>">
|
||||
<?php foreach ($qualityGroups as $qualityGroup): ?>
|
||||
<article class="card card-border bg-base-100 shadow-sm">
|
||||
<div class="card-body gap-4 p-4 sm:p-6">
|
||||
<header class="flex flex-col gap-2 border-b border-base-300 pb-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div class="min-w-0 space-y-1">
|
||||
<h3 class="text-lg font-semibold text-base-content">
|
||||
<?= phpb_e($qualityGroup['page_name'] !== '' ? $qualityGroup['page_name'] : $qualityGroup['page_id']) ?>
|
||||
</h3>
|
||||
<p class="break-all text-sm text-base-content/60"><?= phpb_e($qualityGroup['route']) ?></p>
|
||||
</div>
|
||||
<span class="badge badge-ghost"><?= phpb_e($qualityGroup['locale']) ?></span>
|
||||
</header>
|
||||
|
||||
<?php foreach ($qualityGroup['rules'] as $rule => $ruleFindings): ?>
|
||||
<section class="space-y-2">
|
||||
<h4 class="font-semibold text-base-content"><?= phpb_e($qualityRuleLabels[$rule] ?? $rule) ?></h4>
|
||||
<ul class="space-y-2">
|
||||
<?php foreach ($ruleFindings as $qualityItem): ?>
|
||||
<?php $severity = ($qualityItem['severity'] ?? '') === 'error' ? 'error' : 'warning'; ?>
|
||||
<?php $severityClass = $severity === 'error' ? 'badge-error' : 'badge-warning'; ?>
|
||||
<li class="rounded-box border border-base-300 bg-base-200/40 p-3">
|
||||
<div class="mb-2 flex flex-wrap items-center gap-2">
|
||||
<span class="badge <?= $severityClass ?> badge-soft">
|
||||
<?= phpb_trans('website-manager.quality-severity-' . $severity) ?>
|
||||
</span>
|
||||
</div>
|
||||
<p class="text-sm leading-relaxed text-base-content/80"><?= phpb_e($qualityItem['explanation'] ?? '') ?></p>
|
||||
<?php if (! empty($qualityItem['target'])): ?>
|
||||
<p class="mt-2 break-all text-xs text-base-content/60">
|
||||
<?= phpb_trans('website-manager.quality-target') ?>:
|
||||
<code class="rounded bg-base-300/70 px-1.5 py-0.5 text-base-content"><?= phpb_e($qualityItem['target']) ?></code>
|
||||
</p>
|
||||
<?php endif; ?>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
</section>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</article>
|
||||
<?php endforeach; ?>
|
||||
</section>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
@@ -234,7 +234,19 @@ class Plugi
|
||||
public function checkDatabaseDefinition()
|
||||
{
|
||||
global $phpb_db;
|
||||
if (Setting::get('db-definition') !== $phpb_db->getDBDefinitionHash()) {
|
||||
$schemaNeedsUpdate = Setting::get('db-definition') !== $phpb_db->getDBDefinitionHash();
|
||||
if (! $schemaNeedsUpdate) {
|
||||
foreach ($phpb_db->diffDB() as $tableDiff) {
|
||||
if ($tableDiff === false
|
||||
|| ! empty($tableDiff['columns'])
|
||||
|| ! empty($tableDiff['uniqueKeys'])) {
|
||||
$schemaNeedsUpdate = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($schemaNeedsUpdate) {
|
||||
$module = 'website_manager';
|
||||
$parameters = [
|
||||
['tab' => 'info'],
|
||||
|
||||
@@ -7,6 +7,7 @@ use Plugi\Modules\GrapesJS\PageBuilder;
|
||||
use Plugi\Modules\Router\DatabasePageRouter;
|
||||
use Plugi\Page;
|
||||
use Plugi\PageTranslation;
|
||||
use Plugi\Setting;
|
||||
use Plugi\Modules\WebsiteManager\WebsiteManager;
|
||||
use Plugi\Repositories\PageRepository;
|
||||
|
||||
@@ -18,16 +19,29 @@ require_once __DIR__ . '/../src/Contracts/WebsiteManagerContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/RouterContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/PageBuilderContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/ThemeContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/SettingContract.php';
|
||||
require_once __DIR__ . '/../src/Core/DB.php';
|
||||
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
|
||||
require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
|
||||
require_once __DIR__ . '/../src/Repositories/PageTranslationRepository.php';
|
||||
require_once __DIR__ . '/../src/PageTranslationService.php';
|
||||
require_once __DIR__ . '/../src/Page.php';
|
||||
require_once __DIR__ . '/../src/PageTranslation.php';
|
||||
require_once __DIR__ . '/../src/Setting.php';
|
||||
require_once __DIR__ . '/../src/Repositories/PageRepository.php';
|
||||
require_once __DIR__ . '/../src/Modules/WebsiteManager/WebsiteManager.php';
|
||||
require_once __DIR__ . '/../src/Modules/Router/DatabasePageRouter.php';
|
||||
require_once __DIR__ . '/../src/Modules/GrapesJS/PageBuilder.php';
|
||||
require_once __DIR__ . '/../src/Plugi.php';
|
||||
|
||||
class PageCreationRedirectException extends RuntimeException
|
||||
{
|
||||
public function __construct(public string $redirectUrl)
|
||||
{
|
||||
parent::__construct('Redirect requested.');
|
||||
}
|
||||
}
|
||||
|
||||
class PageCreationTestDatabase extends DB
|
||||
{
|
||||
@@ -39,6 +53,7 @@ class PageCreationTestDatabase extends DB
|
||||
public ?string $failOnDeleteTable = null;
|
||||
public bool $throwOnDeleteFailure = false;
|
||||
public bool $failOnPageUpdate = false;
|
||||
public array $schemaDiffs = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
@@ -118,12 +133,79 @@ class PageCreationTestDatabase extends DB
|
||||
)');
|
||||
}
|
||||
|
||||
public function diffDB(): array
|
||||
{
|
||||
return $this->schemaDiffs;
|
||||
}
|
||||
|
||||
public function getDBDefinitionHash(): string
|
||||
{
|
||||
return 'test-schema-hash';
|
||||
}
|
||||
|
||||
public function rows(string $table): array
|
||||
{
|
||||
return $this->select("SELECT * FROM {$table}", []);
|
||||
}
|
||||
}
|
||||
|
||||
class PageCreationSchemaMigrationTestDatabase extends DB
|
||||
{
|
||||
public array $queries = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public function diffDB(): array
|
||||
{
|
||||
return [
|
||||
'pages' => [
|
||||
'columns' => ['type' => 'varchar(63)'],
|
||||
'uniqueKeys' => [],
|
||||
],
|
||||
'page_translations' => [
|
||||
'columns' => ['target' => 'varchar(255)'],
|
||||
'uniqueKeys' => [],
|
||||
],
|
||||
'missing_table' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function getDBDefinition(): array
|
||||
{
|
||||
return [
|
||||
'pages' => ['columns' => ['type' => 'varchar(63)'], 'uniqueKeys' => []],
|
||||
'page_translations' => ['columns' => ['target' => 'varchar(255)'], 'uniqueKeys' => []],
|
||||
'missing_table' => [
|
||||
'columns' => ['label' => 'varchar(255)'],
|
||||
'uniqueKeys' => ['label' => ['label']],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function query(string $query, array $parameters = [])
|
||||
{
|
||||
$this->queries[] = $query;
|
||||
return true;
|
||||
}
|
||||
|
||||
public function select(string $query, array $parameters): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function lastInsertId(): string
|
||||
{
|
||||
return '0';
|
||||
}
|
||||
|
||||
public function getDBDefinitionHash(): string
|
||||
{
|
||||
return 'test-schema-hash';
|
||||
}
|
||||
}
|
||||
|
||||
class PageCreationTestWebsiteManager extends WebsiteManager
|
||||
{
|
||||
public ?string $renderedErrorMessage = null;
|
||||
@@ -202,6 +284,21 @@ function phpb_url(string $module, array $parameters = []): string
|
||||
return '/' . $module;
|
||||
}
|
||||
|
||||
function phpb_on_url(string $module, array $parameters = []): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
function phpb_current_relative_url(): string
|
||||
{
|
||||
return '/admin/page_settings';
|
||||
}
|
||||
|
||||
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
|
||||
{
|
||||
throw new PageCreationRedirectException($url);
|
||||
}
|
||||
|
||||
function phpb_full_url(string $route): string
|
||||
{
|
||||
return 'https://example.test' . $route;
|
||||
@@ -268,6 +365,56 @@ function runPageCreationCase(string $name, callable $case): bool
|
||||
}
|
||||
|
||||
$cases = [
|
||||
'startup prompts for database updates when schema drifts despite a matching hash' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
global $phpb_db, $pageCreationConfig;
|
||||
$pageCreationConfig['auth'] = ['url' => '/auth'];
|
||||
$phpb_db->schemaDiffs = [
|
||||
'pages' => [
|
||||
'columns' => ['type' => 'varchar(63)'],
|
||||
'uniqueKeys' => [],
|
||||
],
|
||||
];
|
||||
$settings = new ReflectionProperty(Setting::class, 'settings');
|
||||
$settings->setValue(null, ['db-definition' => $phpb_db->getDBDefinitionHash()]);
|
||||
|
||||
try {
|
||||
(new \Plugi\Plugi())->checkDatabaseDefinition();
|
||||
} catch (PageCreationRedirectException $exception) {
|
||||
assertPageCreation(
|
||||
$exception->redirectUrl === '/website_manager',
|
||||
'Schema drift redirected to an unexpected page.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new RuntimeException('Schema drift with a matching hash did not prompt for a database update.');
|
||||
},
|
||||
'database updates apply lowercase schema definitions needed to create pages' => function (): void {
|
||||
$_ENV['DATABASE_PREFIX'] = '';
|
||||
$database = new PageCreationSchemaMigrationTestDatabase();
|
||||
global $phpb_db;
|
||||
$phpb_db = $database;
|
||||
|
||||
$database->resolveDiffDB();
|
||||
|
||||
assertPageCreation(
|
||||
in_array('ALTER TABLE pages ADD type varchar(63)', $database->queries, true),
|
||||
'Database update skipped the lowercase pages.type definition.'
|
||||
);
|
||||
assertPageCreation(
|
||||
in_array('ALTER TABLE page_translations ADD target varchar(255)', $database->queries, true),
|
||||
'Database update skipped the lowercase page_translations.target definition.'
|
||||
);
|
||||
assertPageCreation(
|
||||
in_array('ALTER TABLE missing_table ADD label varchar(255)', $database->queries, true),
|
||||
'Database update did not add configured columns to a newly created table.'
|
||||
);
|
||||
assertPageCreation(
|
||||
in_array('ALTER TABLE missing_table ADD UNIQUE KEY label (`label`)', $database->queries, true),
|
||||
'Database update skipped a lowercase unique-key definition.'
|
||||
);
|
||||
},
|
||||
'configured locale is preferred over the first available translation' => function (): void {
|
||||
resetPageCreationDatabase(['de' => [], 'fr' => []]);
|
||||
global $pageCreationConfig;
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { bindViewportSelector } from '../src/Modules/GrapesJS/resources/assets/js/viewport-selection.js';
|
||||
|
||||
test('viewport changes select a device without changing project data or invoking save', () => {
|
||||
const projectData = { pages: [{ id: 'page-1' }] };
|
||||
const originalProjectData = structuredClone(projectData);
|
||||
const selectedDevices = [];
|
||||
let saveCalls = 0;
|
||||
let changeHandler;
|
||||
const editor = {
|
||||
setDevice(device) {
|
||||
selectedDevices.push(device);
|
||||
},
|
||||
getProjectData() {
|
||||
return projectData;
|
||||
},
|
||||
store() {
|
||||
saveCalls++;
|
||||
},
|
||||
};
|
||||
const selector = {
|
||||
value: 'Desktop',
|
||||
addEventListener(eventName, handler) {
|
||||
assert.equal(eventName, 'change');
|
||||
changeHandler = handler;
|
||||
},
|
||||
};
|
||||
|
||||
bindViewportSelector(editor, selector);
|
||||
for (const device of ['Desktop', 'Tablet', 'Mobile']) {
|
||||
selector.value = device;
|
||||
changeHandler();
|
||||
}
|
||||
|
||||
assert.deepEqual(selectedDevices, ['Desktop', 'Tablet', 'Mobile']);
|
||||
assert.deepEqual(editor.getProjectData(), originalProjectData);
|
||||
assert.equal(saveCalls, 0);
|
||||
});
|
||||
@@ -0,0 +1,298 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/../src/Modules/WebsiteManager/SiteQualityAnalyzer.php';
|
||||
require_once __DIR__ . '/../src/Modules/WebsiteManager/SiteQualityCheckService.php';
|
||||
|
||||
$siteQualityConfig = [
|
||||
'page' => ['translation' => ['foreign_key' => 'page_id']],
|
||||
'general' => ['uploads_url' => '/uploads'],
|
||||
'storage' => ['uploads_folder' => sys_get_temp_dir()],
|
||||
];
|
||||
$siteQualityLanguages = ['en' => 'English', 'de' => 'German'];
|
||||
|
||||
function phpb_config(?string $key = null)
|
||||
{
|
||||
global $siteQualityConfig;
|
||||
if ($key === null) {
|
||||
return $siteQualityConfig;
|
||||
}
|
||||
$value = $siteQualityConfig;
|
||||
foreach (explode('.', $key) as $segment) {
|
||||
if (! is_array($value) || ! array_key_exists($segment, $value)) {
|
||||
return '';
|
||||
}
|
||||
$value = $value[$segment];
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
function phpb_active_languages(): array
|
||||
{
|
||||
global $siteQualityLanguages;
|
||||
return $siteQualityLanguages;
|
||||
}
|
||||
|
||||
function phpb_trans(string $key): string
|
||||
{
|
||||
return $key;
|
||||
}
|
||||
|
||||
function phpb_e($value): string
|
||||
{
|
||||
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
function phpb_url(string $module, array $parameters = []): string
|
||||
{
|
||||
return '/' . $module . '?' . http_build_query($parameters);
|
||||
}
|
||||
|
||||
function phpb_csrf_field(): void
|
||||
{
|
||||
echo '<input type="hidden" name="_csrf_token" value="test-token">';
|
||||
}
|
||||
|
||||
function assertSiteQuality(bool $condition, string $message): void
|
||||
{
|
||||
if (! $condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
}
|
||||
|
||||
function runSiteQualityCase(string $name, callable $case): bool
|
||||
{
|
||||
try {
|
||||
$case();
|
||||
fwrite(STDOUT, "PASS: {$name}\n");
|
||||
return true;
|
||||
} catch (Throwable $exception) {
|
||||
fwrite(STDERR, "FAIL: {$name}: {$exception->getMessage()}\n");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class SiteQualityTestPage
|
||||
{
|
||||
public function __construct(public string $id, public string $name)
|
||||
{
|
||||
}
|
||||
|
||||
public function getId(): string
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
}
|
||||
|
||||
class SiteQualityTestPageRepository
|
||||
{
|
||||
public function __construct(private array $pages)
|
||||
{
|
||||
}
|
||||
|
||||
public function getAll(): array
|
||||
{
|
||||
return $this->pages;
|
||||
}
|
||||
}
|
||||
|
||||
class SiteQualityTestTranslationRepository
|
||||
{
|
||||
public function __construct(private array $translations)
|
||||
{
|
||||
}
|
||||
|
||||
public function getForPages(array $pageIds): array
|
||||
{
|
||||
return $this->translations;
|
||||
}
|
||||
}
|
||||
|
||||
class SiteQualityTestUploadRepository
|
||||
{
|
||||
public function __construct(private array $uploads)
|
||||
{
|
||||
}
|
||||
|
||||
public function getAll(): array
|
||||
{
|
||||
return $this->uploads;
|
||||
}
|
||||
}
|
||||
|
||||
function siteQualityTranslation(string $pageId, string $locale, string $route): object
|
||||
{
|
||||
return (object) ['page_id' => $pageId, 'locale' => $locale, 'route' => $route];
|
||||
}
|
||||
|
||||
function siteQualityRules(array $findings): array
|
||||
{
|
||||
return array_column($findings, 'rule');
|
||||
}
|
||||
|
||||
$cases = [
|
||||
'compliant markup, active routes, and known assets produce no findings' => function (): void {
|
||||
$analyzer = new Plugi\Modules\WebsiteManager\SiteQualityAnalyzer(
|
||||
['/home', '/contact', '/de/about'],
|
||||
['/uploads/file-1/logo.png'],
|
||||
'https://example.test/plugi',
|
||||
'/uploads'
|
||||
);
|
||||
$html = '<h1>Home</h1><h2>Section</h2><label for="email">Email</label><input id="email" type="email">'
|
||||
. '<img alt="Logo" src="https://example.test/plugi/uploads/file-1/logo.png">'
|
||||
. '<a href="https://example.test/plugi/contact?source=home#form">Contact</a>';
|
||||
|
||||
assertSiteQuality($analyzer->analyze($html, '/home') === [], 'Compliant markup or known links produced unexpected findings.');
|
||||
},
|
||||
'missing image alt, unnamed controls, and skipped heading levels are reported' => function (): void {
|
||||
$analyzer = new Plugi\Modules\WebsiteManager\SiteQualityAnalyzer(['/home'], [], 'https://example.test/plugi', '/uploads');
|
||||
$findings = $analyzer->analyze('<img src="/plugi/photo.png"><input type="text"><h1>Title</h1><h3>Subheading</h3>', '/home');
|
||||
|
||||
assertSiteQuality(in_array('image-alt', siteQualityRules($findings), true), 'An image without an alt attribute was not reported.');
|
||||
assertSiteQuality(in_array('form-control-name', siteQualityRules($findings), true), 'An unnamed form control was not reported.');
|
||||
assertSiteQuality(in_array('heading-level', siteQualityRules($findings), true), 'A skipped heading level was not reported.');
|
||||
},
|
||||
'localized internal routes and ignored external or non-navigation links are handled offline' => function (): void {
|
||||
$analyzer = new Plugi\Modules\WebsiteManager\SiteQualityAnalyzer(
|
||||
['/home', '/de/ueber-uns'],
|
||||
['/uploads/image-1/photo.jpg'],
|
||||
'https://example.test/plugi',
|
||||
'/uploads'
|
||||
);
|
||||
$html = '<a href="/plugi/de/ueber-uns">German route</a>'
|
||||
. '<a href="https://outside.test/anything">External</a>'
|
||||
. '<a href="mailto:team@example.test">Email</a><a href="tel:+123">Phone</a>'
|
||||
. '<a href="#details">Fragment</a>'
|
||||
. '<img alt="Photo" src="/plugi/uploads/image-1/photo.jpg">';
|
||||
|
||||
assertSiteQuality($analyzer->analyze($html, '/home') === [], 'A valid localized route, local asset, or ignored external link was incorrectly reported.');
|
||||
},
|
||||
'same-site links outside the configured application base are not treated as local uploads' => function (): void {
|
||||
$analyzer = new Plugi\Modules\WebsiteManager\SiteQualityAnalyzer(
|
||||
['/home'],
|
||||
['/uploads/image-1/photo.jpg'],
|
||||
'https://example.test/plugi',
|
||||
'/uploads'
|
||||
);
|
||||
|
||||
$findings = $analyzer->analyze('<a href="/uploads/image-1/photo.jpg">Photo</a>', '/home');
|
||||
assertSiteQuality(
|
||||
in_array('missing-internal-route', siteQualityRules($findings), true),
|
||||
'A root-level path outside the application base was incorrectly resolved to an application upload.'
|
||||
);
|
||||
},
|
||||
'missing same-site routes and uploads are reported with actionable targets' => function (): void {
|
||||
$analyzer = new Plugi\Modules\WebsiteManager\SiteQualityAnalyzer(
|
||||
['/home'],
|
||||
[],
|
||||
'https://example.test/plugi',
|
||||
'/uploads'
|
||||
);
|
||||
$findings = $analyzer->analyze('<a href="/plugi/not-found">Missing page</a><img alt="Missing" src="/plugi/uploads/no-file.png">', '/home');
|
||||
|
||||
assertSiteQuality(in_array('missing-internal-route', siteQualityRules($findings), true), 'A missing same-site route was not reported.');
|
||||
assertSiteQuality(in_array('missing-local-asset', siteQualityRules($findings), true), 'A missing local upload was not reported.');
|
||||
assertSiteQuality(count(array_filter($findings, static fn(array $finding): bool => $finding['target'] !== '')) === 2, 'Findings did not identify affected targets.');
|
||||
},
|
||||
'only active language routes are scanned' => function (): void {
|
||||
global $siteQualityLanguages;
|
||||
$siteQualityLanguages = ['en' => 'English'];
|
||||
$renderedLocales = [];
|
||||
$service = new Plugi\Modules\WebsiteManager\SiteQualityCheckService(
|
||||
new SiteQualityTestPageRepository([new SiteQualityTestPage('1', 'Localized page')]),
|
||||
new SiteQualityTestTranslationRepository([
|
||||
siteQualityTranslation('1', 'en', '/localized'),
|
||||
siteQualityTranslation('1', 'fr', '/fr/localized'),
|
||||
]),
|
||||
new SiteQualityTestUploadRepository([]),
|
||||
static function (SiteQualityTestPage $page, string $locale) use (&$renderedLocales): string {
|
||||
$renderedLocales[] = $locale;
|
||||
return '<h1>Page</h1>';
|
||||
}
|
||||
);
|
||||
|
||||
$report = $service->run();
|
||||
assertSiteQuality($report['pages_checked'] === 1 && $renderedLocales === ['en'], 'An inactive translation was included in the live-site scan.');
|
||||
},
|
||||
'renderer failure is page-scoped and does not stop later page locales' => function (): void {
|
||||
global $siteQualityLanguages;
|
||||
$siteQualityLanguages = ['en' => 'English'];
|
||||
$pages = [new SiteQualityTestPage('1', 'Broken render'), new SiteQualityTestPage('2', 'Available page')];
|
||||
$translations = [siteQualityTranslation('1', 'en', '/broken'), siteQualityTranslation('2', 'en', '/available')];
|
||||
$service = new Plugi\Modules\WebsiteManager\SiteQualityCheckService(
|
||||
new SiteQualityTestPageRepository($pages),
|
||||
new SiteQualityTestTranslationRepository($translations),
|
||||
new SiteQualityTestUploadRepository([]),
|
||||
static function (SiteQualityTestPage $page): string {
|
||||
if ($page->id === '1') {
|
||||
throw new RuntimeException('template failure');
|
||||
}
|
||||
return '<h1>Available</h1>';
|
||||
}
|
||||
);
|
||||
|
||||
$report = $service->run();
|
||||
assertSiteQuality($report['pages_checked'] === 2, 'The audit did not continue after a renderer failure.');
|
||||
assertSiteQuality(count($report['errors']) === 1, 'The renderer failure was not captured as one page-scoped error.');
|
||||
assertSiteQuality($report['errors'][0]['page_id'] === '1' && $report['errors'][0]['locale'] === 'en', 'The coverage error omitted its page or locale.');
|
||||
},
|
||||
'upload inventory rejects file paths resolved outside the configured uploads directory' => function (): void {
|
||||
global $siteQualityConfig, $siteQualityLanguages;
|
||||
$siteQualityLanguages = ['en' => 'English'];
|
||||
$siteQualityConfig['storage']['uploads_folder'] = sys_get_temp_dir();
|
||||
$page = new SiteQualityTestPage('1', 'Path safety');
|
||||
$outsidePath = str_repeat('../', 64) . ltrim(__FILE__, DIRECTORY_SEPARATOR);
|
||||
$upload = (object) ['public_id' => 'outside', 'original_file' => 'test.php', 'server_file' => $outsidePath];
|
||||
$service = new Plugi\Modules\WebsiteManager\SiteQualityCheckService(
|
||||
new SiteQualityTestPageRepository([$page]),
|
||||
new SiteQualityTestTranslationRepository([siteQualityTranslation('1', 'en', '/safety')]),
|
||||
new SiteQualityTestUploadRepository([$upload]),
|
||||
static fn(): string => '<img alt="Outside" src="/uploads/outside/test.php">'
|
||||
);
|
||||
|
||||
$report = $service->run();
|
||||
assertSiteQuality(
|
||||
in_array('missing-local-asset', siteQualityRules($report['findings']), true),
|
||||
'An upload path outside the configured public area was trusted as a valid asset.'
|
||||
);
|
||||
},
|
||||
'quality tab groups findings and escapes actionable context' => function (): void {
|
||||
$qualityReport = [
|
||||
'pages_checked' => 1,
|
||||
'findings' => [[
|
||||
'page_id' => '1',
|
||||
'page_name' => '<script>alert(1)</script>',
|
||||
'route' => '/home',
|
||||
'locale' => 'en',
|
||||
'rule' => 'missing-internal-route',
|
||||
'severity' => 'warning',
|
||||
'explanation' => 'The linked page was not found.',
|
||||
'target' => '/missing"><script>alert(2)</script>',
|
||||
]],
|
||||
'errors' => [],
|
||||
];
|
||||
ob_start();
|
||||
require __DIR__ . '/../src/Modules/WebsiteManager/resources/views/tabs/quality.php';
|
||||
$html = ob_get_clean();
|
||||
|
||||
assertSiteQuality(str_contains($html, 'route=quality&action=scan&tab=quality'), 'The quality scan form does not target its authenticated action.');
|
||||
assertSiteQuality(str_contains($html, 'name="_csrf_token"'), 'The quality scan form is missing its CSRF token field.');
|
||||
assertSiteQuality(str_contains($html, 'website-manager.quality-rule-missing-internal-route'), 'Findings were not grouped under their rule label.');
|
||||
assertSiteQuality(str_contains($html, '<script>alert(1)</script>'), 'The affected page name was not escaped.');
|
||||
assertSiteQuality(str_contains($html, '<script>alert(2)</script>'), 'The affected target was not escaped.');
|
||||
},
|
||||
];
|
||||
|
||||
$passed = 0;
|
||||
foreach ($cases as $name => $case) {
|
||||
if (runSiteQualityCase($name, $case)) {
|
||||
$passed++;
|
||||
}
|
||||
}
|
||||
|
||||
fwrite(STDOUT, sprintf("%d/%d site quality check cases passed.\n", $passed, count($cases)));
|
||||
exit($passed === count($cases) ? 0 : 1);
|
||||
Reference in New Issue
Block a user