394 lines
18 KiB
PHP
394 lines
18 KiB
PHP
<?php
|
|
|
|
use Plugi\Core\DB;
|
|
use Plugi\Modules\WebsiteManager\WebsiteManager;
|
|
use Plugi\Repositories\UploadRepository;
|
|
|
|
require_once __DIR__ . '/../src/Contracts/WebsiteManagerContract.php';
|
|
require_once __DIR__ . '/../src/Core/DB.php';
|
|
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
|
|
require_once __DIR__ . '/../src/UploadedFile.php';
|
|
require_once __DIR__ . '/../src/Repositories/UploadRepository.php';
|
|
require_once __DIR__ . '/../src/Modules/WebsiteManager/WebsiteManager.php';
|
|
|
|
class MediaLibrarySettingRepositoryStub
|
|
{
|
|
public function updateSettings(array $settings): bool
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
class_alias(MediaLibrarySettingRepositoryStub::class, 'Plugi\\Repositories\\SettingRepository');
|
|
|
|
class MediaLibraryRedirectException extends RuntimeException
|
|
{
|
|
public function __construct(public string $url, public array $flashData)
|
|
{
|
|
parent::__construct('Redirect requested.');
|
|
}
|
|
}
|
|
|
|
class MediaLibraryTestDatabase extends DB
|
|
{
|
|
public function __construct()
|
|
{
|
|
$this->pdo = new PDO('sqlite::memory:');
|
|
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
$this->databaseName = 'media_library_test';
|
|
}
|
|
|
|
public function createSchema(): void
|
|
{
|
|
$this->pdo->exec("CREATE TABLE testuploads (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
public_id VARCHAR(50),
|
|
original_file VARCHAR(512),
|
|
mime_type VARCHAR(50),
|
|
server_file VARCHAR(512),
|
|
alt_text VARCHAR(1000) NOT NULL DEFAULT '',
|
|
folder VARCHAR(255) NOT NULL DEFAULT ''
|
|
)");
|
|
}
|
|
}
|
|
|
|
class MediaLibrarySchemaUpdateTestDatabase extends MediaLibraryTestDatabase
|
|
{
|
|
public function createLegacySchema(): void
|
|
{
|
|
$this->pdo->exec('CREATE TABLE testuploads (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
public_id VARCHAR(50),
|
|
original_file VARCHAR(512),
|
|
mime_type VARCHAR(50),
|
|
server_file VARCHAR(512)
|
|
)');
|
|
}
|
|
|
|
public function getDBDefinition(): array
|
|
{
|
|
$tables = require __DIR__ . '/../config/tables.php';
|
|
return [
|
|
'uploads' => [
|
|
'columns' => $tables['uploads']['columns'],
|
|
'uniqueKeys' => [],
|
|
],
|
|
];
|
|
}
|
|
|
|
public function diffDB(): array
|
|
{
|
|
$definition = $this->getDBDefinition()['uploads'];
|
|
$existingColumns = $this->select('PRAGMA table_info(testuploads)', []);
|
|
$existingColumnNames = array_column($existingColumns, 'name');
|
|
$missingColumns = array_diff_key($definition['columns'], array_fill_keys($existingColumnNames, true));
|
|
|
|
return [
|
|
'uploads' => [
|
|
'columns' => $missingColumns,
|
|
'uniqueKeys' => [],
|
|
],
|
|
];
|
|
}
|
|
}
|
|
|
|
function phpb_remove_non_alpha_numeric(string $value): string
|
|
{
|
|
return preg_replace('/\W*/', '', $value);
|
|
}
|
|
|
|
function phpb_url(string $module, array $parameters = []): string
|
|
{
|
|
return '/' . $module . '?' . http_build_query($parameters);
|
|
}
|
|
|
|
function phpb_trans(string $key): string
|
|
{
|
|
return $key;
|
|
}
|
|
|
|
function phpb_e($value): string
|
|
{
|
|
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
|
}
|
|
|
|
function phpb_csrf_field(): void
|
|
{
|
|
echo '<input type="hidden" name="_csrf_token" value="test-token">';
|
|
}
|
|
|
|
function phpb_validate_csrf(): bool
|
|
{
|
|
return $GLOBALS['mediaLibraryCsrfValid'] ?? false;
|
|
}
|
|
|
|
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
|
|
{
|
|
throw new MediaLibraryRedirectException($url, $flashData);
|
|
}
|
|
|
|
function assertMediaLibrary(bool $condition, string $message): void
|
|
{
|
|
if (! $condition) {
|
|
throw new RuntimeException($message);
|
|
}
|
|
}
|
|
|
|
function runMediaLibraryCase(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 MediaLibraryViewUpload
|
|
{
|
|
public function __construct(
|
|
public string $public_id,
|
|
public string $original_file,
|
|
public string $mime_type,
|
|
public string $folder = '',
|
|
public string $alt_text = ''
|
|
) {
|
|
}
|
|
|
|
public function getUrl(): string
|
|
{
|
|
return '/uploads/' . $this->public_id . '/' . $this->original_file;
|
|
}
|
|
}
|
|
|
|
function renderMediaLibraryView(array $files): string
|
|
{
|
|
ob_start();
|
|
require __DIR__ . '/../src/Modules/WebsiteManager/resources/views/tabs/files.php';
|
|
return ob_get_clean();
|
|
}
|
|
|
|
$_ENV['DATABASE_PREFIX'] = 'test';
|
|
$phpb_db = new MediaLibraryTestDatabase;
|
|
$phpb_db->createSchema();
|
|
$repository = new UploadRepository;
|
|
$websiteManager = new WebsiteManager;
|
|
$cases = [
|
|
'schema defines defaulted metadata columns' => function (): void {
|
|
$tables = require __DIR__ . '/../config/tables.php';
|
|
assertMediaLibrary(
|
|
($tables['uploads']['columns']['alt_text'] ?? null) === "varchar(1000) NOT NULL DEFAULT ''",
|
|
'Alt text should be a bounded, empty-default upload column.'
|
|
);
|
|
assertMediaLibrary(
|
|
($tables['uploads']['columns']['folder'] ?? null) === "varchar(255) NOT NULL DEFAULT ''",
|
|
'Folder should be an empty-default upload column.'
|
|
);
|
|
},
|
|
'new uploads initialize metadata as empty strings' => function () use ($repository): void {
|
|
$upload = $repository->create([
|
|
'public_id' => 'new-upload',
|
|
'original_file' => 'new.png',
|
|
'mime_type' => 'image/png',
|
|
'server_file' => 'new-upload/new.png',
|
|
]);
|
|
|
|
assertMediaLibrary($upload !== null, 'A valid upload should be created.');
|
|
assertMediaLibrary($upload->alt_text === '', 'New uploads should start with blank alt text.');
|
|
assertMediaLibrary($upload->folder === '', 'New uploads should start without a folder.');
|
|
},
|
|
'legacy upload rows receive blank metadata defaults' => function () use ($phpb_db, $repository): void {
|
|
$phpb_db->query(
|
|
'INSERT INTO testuploads (public_id, original_file, mime_type, server_file) VALUES (?, ?, ?, ?)',
|
|
['legacy-upload', 'legacy.jpg', 'image/jpeg', 'legacy-upload/legacy.jpg']
|
|
);
|
|
$upload = $repository->findWhere('public_id', 'legacy-upload')[0] ?? null;
|
|
|
|
assertMediaLibrary($upload !== null, 'A legacy upload should remain available.');
|
|
assertMediaLibrary($upload->alt_text === '', 'Legacy uploads should have blank alt text.');
|
|
assertMediaLibrary($upload->folder === '', 'Legacy uploads should be unsorted.');
|
|
},
|
|
'schema update adds metadata defaults without losing existing uploads' => function (): void {
|
|
$database = new MediaLibrarySchemaUpdateTestDatabase;
|
|
$database->createLegacySchema();
|
|
$database->query(
|
|
'INSERT INTO testuploads (public_id, original_file, mime_type, server_file) VALUES (?, ?, ?, ?)',
|
|
['migrated-upload', 'existing.jpg', 'image/jpeg', 'migrated-upload/existing.jpg']
|
|
);
|
|
|
|
$database->resolveDiffDB();
|
|
$upload = $database->select('SELECT * FROM testuploads WHERE public_id = ?', ['migrated-upload'])[0] ?? null;
|
|
|
|
assertMediaLibrary($upload !== null, 'The schema update should retain existing upload rows.');
|
|
assertMediaLibrary(array_key_exists('alt_text', $upload) && $upload['alt_text'] === '', 'The schema update should add blank alt text.');
|
|
assertMediaLibrary(array_key_exists('folder', $upload) && $upload['folder'] === '', 'The schema update should add blank folders.');
|
|
},
|
|
'metadata updates by public ID and can clear fields' => function () use ($repository): void {
|
|
$upload = $repository->create([
|
|
'public_id' => 'editable-upload',
|
|
'original_file' => 'photo.jpg',
|
|
'mime_type' => 'image/jpeg',
|
|
'server_file' => 'editable-upload/photo.jpg',
|
|
]);
|
|
|
|
assertMediaLibrary(
|
|
$repository->updateMetadata('editable-upload', ['folder' => ' Campaigns ', 'alt_text' => 'Campaign photo']),
|
|
'Valid metadata should update.'
|
|
);
|
|
$updated = $repository->findWhere('public_id', 'editable-upload')[0];
|
|
assertMediaLibrary($updated->folder === 'Campaigns', 'The folder should persist.');
|
|
assertMediaLibrary($updated->alt_text === 'Campaign photo', 'Alt text should persist.');
|
|
|
|
assertMediaLibrary(
|
|
$repository->updateMetadata('editable-upload', ['folder' => '']),
|
|
'A folder should be clearable.'
|
|
);
|
|
assertMediaLibrary(
|
|
$repository->findWhere('public_id', 'editable-upload')[0]->folder === '',
|
|
'Clearing a folder should restore the unsorted state.'
|
|
);
|
|
},
|
|
'metadata updates reject missing records and unsupported values' => function () use ($repository): void {
|
|
assertMediaLibrary(! $repository->updateMetadata('missing-upload', ['folder' => 'News']), 'Unknown uploads must not update.');
|
|
assertMediaLibrary(! $repository->updateMetadata('legacy-upload', []), 'Empty metadata updates must be rejected.');
|
|
assertMediaLibrary(! $repository->updateMetadata('legacy-upload', ['path' => 'elsewhere']), 'Unsupported fields must be rejected.');
|
|
assertMediaLibrary(! $repository->updateMetadata('legacy-upload', ['folder' => ['News']]), 'Non-string values must be rejected.');
|
|
assertMediaLibrary(! $repository->updateMetadata('legacy-upload', ['folder' => str_repeat('x', 256)]), 'Overlong folder labels must be rejected.');
|
|
assertMediaLibrary(! $repository->updateMetadata('legacy-upload', ['alt_text' => str_repeat('x', 1001)]), 'Overlong alt text must be rejected.');
|
|
},
|
|
'metadata action validates CSRF and persists allowed request fields' => function () use ($repository, $websiteManager): void {
|
|
$repository->create([
|
|
'public_id' => 'request-upload',
|
|
'original_file' => 'request.png',
|
|
'mime_type' => 'image/png',
|
|
'server_file' => 'request-upload/request.png',
|
|
]);
|
|
$_SERVER['REQUEST_METHOD'] = 'POST';
|
|
$_GET = [];
|
|
$_POST = [
|
|
'_csrf_token' => 'valid-token',
|
|
'public_id' => 'request-upload',
|
|
'folder' => 'News',
|
|
];
|
|
$GLOBALS['mediaLibraryCsrfValid'] = true;
|
|
|
|
try {
|
|
$websiteManager->handleRequest('media', 'update_metadata');
|
|
throw new RuntimeException('A successful metadata update should redirect.');
|
|
} catch (MediaLibraryRedirectException $redirect) {
|
|
assertMediaLibrary(str_contains($redirect->url, 'tab=files'), 'Successful updates should return to the media tab.');
|
|
assertMediaLibrary(($redirect->flashData['message-type'] ?? null) === 'success', 'Successful updates should show a success message.');
|
|
}
|
|
|
|
assertMediaLibrary(
|
|
$repository->findWhere('public_id', 'request-upload')[0]->folder === 'News',
|
|
'The manager action should persist the requested folder.'
|
|
);
|
|
},
|
|
'alt text saves through manager action and appears on image previews' => function () use ($repository, $websiteManager): void {
|
|
$_SERVER['REQUEST_METHOD'] = 'POST';
|
|
$_POST = [
|
|
'_csrf_token' => 'valid-token',
|
|
'public_id' => 'request-upload',
|
|
'alt_text' => 'Camera "test" & results',
|
|
];
|
|
$GLOBALS['mediaLibraryCsrfValid'] = true;
|
|
|
|
try {
|
|
$websiteManager->handleRequest('media', 'update_metadata');
|
|
throw new RuntimeException('An alt-text update should redirect.');
|
|
} catch (MediaLibraryRedirectException $redirect) {
|
|
assertMediaLibrary(($redirect->flashData['message-type'] ?? null) === 'success', 'Saved alt text should show a success message.');
|
|
}
|
|
|
|
$upload = $repository->findWhere('public_id', 'request-upload')[0];
|
|
assertMediaLibrary($upload->alt_text === 'Camera "test" & results', 'Alt text should persist exactly as entered.');
|
|
$html = renderMediaLibraryView([
|
|
new MediaLibraryViewUpload($upload->public_id, $upload->original_file, $upload->mime_type, $upload->folder, $upload->alt_text),
|
|
]);
|
|
assertMediaLibrary(str_contains($html, 'alt="Camera "test" & results"'), 'The saved alt text should render as an escaped image alt attribute.');
|
|
assertMediaLibrary(str_contains($html, 'value="Camera "test" & results"'), 'The editor should show the saved alt text.');
|
|
},
|
|
'metadata action rejects requests without a valid CSRF token' => function () use ($repository, $websiteManager): void {
|
|
$_SERVER['REQUEST_METHOD'] = 'POST';
|
|
$_POST = ['public_id' => 'request-upload', 'folder' => 'Private'];
|
|
$GLOBALS['mediaLibraryCsrfValid'] = false;
|
|
|
|
assertMediaLibrary(! $websiteManager->handleUpdateMediaMetadata(), 'The metadata action should reject invalid CSRF.');
|
|
assertMediaLibrary(http_response_code() === 403, 'Invalid CSRF should set a forbidden status.');
|
|
assertMediaLibrary(
|
|
$repository->findWhere('public_id', 'request-upload')[0]->folder === 'News',
|
|
'A rejected request must not change metadata.'
|
|
);
|
|
},
|
|
'metadata action rejects unrecognized request fields' => function () use ($repository, $websiteManager): void {
|
|
$_SERVER['REQUEST_METHOD'] = 'POST';
|
|
$_POST = [
|
|
'_csrf_token' => 'valid-token',
|
|
'public_id' => 'request-upload',
|
|
'folder' => 'Private',
|
|
'server_file' => 'attacker-controlled/path',
|
|
];
|
|
$GLOBALS['mediaLibraryCsrfValid'] = true;
|
|
|
|
try {
|
|
$websiteManager->handleUpdateMediaMetadata();
|
|
throw new RuntimeException('An unsupported request field should be rejected.');
|
|
} catch (MediaLibraryRedirectException $redirect) {
|
|
assertMediaLibrary(($redirect->flashData['message-type'] ?? null) === 'error', 'Invalid fields should produce an error message.');
|
|
}
|
|
|
|
assertMediaLibrary(
|
|
$repository->findWhere('public_id', 'request-upload')[0]->folder === 'News',
|
|
'A request with unsupported fields must not change metadata.'
|
|
);
|
|
},
|
|
'media view exposes combined search and filter controls for mixed uploads' => function (): void {
|
|
$files = [
|
|
new MediaLibraryViewUpload('image-id', 'Campaign Photo.png', 'image/png', '', 'A campaign "photo" & more'),
|
|
new MediaLibraryViewUpload('empty-alt-id', 'Empty Alt.png', 'image/png'),
|
|
new MediaLibraryViewUpload('document-id', 'Press Kit.pdf', 'application/pdf', 'Press'),
|
|
new MediaLibraryViewUpload('audio-id', 'Interview.mp3', 'audio/mpeg'),
|
|
];
|
|
$html = renderMediaLibraryView($files);
|
|
|
|
assertMediaLibrary(str_contains($html, 'id="media-search"'), 'The view should render a search field.');
|
|
assertMediaLibrary(str_contains($html, 'id="media-type-filter"'), 'The view should render a MIME-derived type filter.');
|
|
assertMediaLibrary(str_contains($html, 'id="media-folder-filter"'), 'The view should render a folder filter.');
|
|
assertMediaLibrary(str_contains($html, 'id="media-filter-reset"'), 'The view should provide a clear-filters action.');
|
|
assertMediaLibrary(str_contains($html, 'value="__unsorted__">Unsorted</option>'), 'Unassigned files should have an Unsorted filter option.');
|
|
assertMediaLibrary(str_contains($html, 'data-file-name="Campaign Photo.png"'), 'Search data should include original filenames.');
|
|
assertMediaLibrary(str_contains($html, 'data-public-id="image-id"'), 'Search data should include public IDs.');
|
|
assertMediaLibrary(str_contains($html, 'data-mime-family="application"'), 'Type filters should derive from MIME types.');
|
|
assertMediaLibrary(str_contains($html, 'value="folder:Press">Press</option>'), 'Existing folder labels should be filter options.');
|
|
assertMediaLibrary(str_contains($html, 'name="folder"'), 'Each upload should have a virtual folder assignment field.');
|
|
assertMediaLibrary(str_contains($html, 'name="alt_text"'), 'Each upload should have an alt-text editor.');
|
|
assertMediaLibrary(str_contains($html, 'Alt text'), 'Alt text inputs should have a visible label.');
|
|
assertMediaLibrary(str_contains($html, 'alt="A campaign "photo" & more"'), 'Saved text should be used as the image preview alt.');
|
|
assertMediaLibrary(str_contains($html, 'alt=""'), 'Blank alt text should remain blank rather than using the filename.');
|
|
assertMediaLibrary(! str_contains($html, 'alt="Empty Alt.png"'), 'Image filenames must not be substituted for blank authored alt text.');
|
|
assertMediaLibrary(str_contains($html, 'id="media-no-results"'), 'The view should render an explicit no-results state.');
|
|
assertMediaLibrary(substr_count($html, '<img ') === 2, 'Only image MIME types should render image previews.');
|
|
assertMediaLibrary(str_contains($html, 'application/pdf'), 'Non-image uploads should show a file-type treatment.');
|
|
assertMediaLibrary(str_contains($html, 'action=upload_delete'), 'Existing delete behavior should remain routed through PageBuilder.');
|
|
assertMediaLibrary(str_contains($html, 'action=upload&page=1'), 'Existing upload behavior should remain routed through PageBuilder.');
|
|
},
|
|
'empty media view does not render active filters or require client controls' => function (): void {
|
|
$html = renderMediaLibraryView([]);
|
|
|
|
assertMediaLibrary(str_contains($html, 'No files yet'), 'An empty library should retain its empty state.');
|
|
assertMediaLibrary(! str_contains($html, 'id="media-search"'), 'An empty library should not render unnecessary filters.');
|
|
},
|
|
];
|
|
|
|
$passed = 0;
|
|
foreach ($cases as $name => $case) {
|
|
if (runMediaLibraryCase($name, $case)) {
|
|
$passed++;
|
|
}
|
|
}
|
|
|
|
fwrite(STDOUT, sprintf("%d/%d media library cases passed.\n", $passed, count($cases)));
|
|
exit($passed === count($cases) ? 0 : 1); |