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:
@@ -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'],
|
||||
|
||||
Reference in New Issue
Block a user