fix: media usage check fails closed on database errors; refused deletes checked for partial state

MediaUsageFinder treats a failed query (null result or last_error) as a possible
usage and an incomplete scan, so media-delete refuses without force. A refused
wp_delete_attachment() is write_failed only when the attachment is intact,
otherwise partial_write. media-update: re-read hint on write_failed, normalized
ids in failures, documented lock resolution and kses on restore.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01At3V6SjwbMe6eMzVGW3Hs7
This commit is contained in:
2026-09-26 02:54:37 +02:00
co-authored by Claude Opus 5.5
parent 931ddeb137
commit 7f136f6f4c
10 changed files with 238 additions and 20 deletions
@@ -23,6 +23,7 @@ final class MediaDeleteAbilityTest extends TestCase
parent::setUp();
Functions\when('get_post')->justReturn(new WP_Post(['ID' => 33, 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_title' => 'Foto']));
Functions\when('current_user_can')->justReturn(true);
Functions\when('get_post_meta')->justReturn('2026/09/foto.jpg');
}
private function ability(array $usages, ChangeLog $log, bool $trash = false): MediaDeleteAbility
@@ -96,8 +97,9 @@ final class MediaDeleteAbilityTest extends TestCase
self::assertSame('trashed', $result['changed'][0]['action']);
}
public function testRefusedDeleteIsAWriteFailure(): void
public function testRefusedDeleteWithTheAttachmentIntactIsAWriteFailure(): void
{
Functions\when('get_post_meta')->justReturn('2026/09/foto.jpg');
Functions\expect('wp_delete_attachment')->once()->andReturn(false);
$result = $this->ability([], Mockery::mock(ChangeLog::class))->execute(['id' => 33, 'confirm' => true]);
@@ -105,6 +107,54 @@ final class MediaDeleteAbilityTest extends TestCase
self::assertSame('lit_write_failed', $result->get_error_code());
}
public function testRefusedDeleteThatRemovedDataIsAPartialWrite(): void
{
$meta = '2026/09/foto.jpg';
Functions\when('get_post_meta')->alias(static function () use (&$meta): string {
return $meta;
});
Functions\expect('wp_delete_attachment')->once()->andReturnUsing(static function () use (&$meta) {
$meta = '';
return null;
});
$log = Mockery::mock(ChangeLog::class);
$log->expects('recordPartial')->once()->with('lit/media-delete', 'attachment', '33', Mockery::type('string'));
$result = $this->ability([], $log)->execute(['id' => 33, 'confirm' => true]);
self::assertSame('lit_partial_write', $result->get_error_code());
self::assertSame(33, $result->get_error_data()['attachment_id']);
}
public function testADatabaseErrorInTheUsageCheckRefusesWithoutForce(): void
{
Functions\when('get_post_meta')->justReturn('2026/09/foto.jpg');
Functions\when('get_option')->justReturn(false);
Functions\when('get_theme_mod')->justReturn(false);
Functions\expect('wp_delete_attachment')->never();
/** @var \Mockery\MockInterface&\wpdb $db */
$db = Mockery::mock(\wpdb::class)->makePartial();
$db->allows('get_results')->andReturn(null);
$ability = new MediaDeleteAbility(
new MediaUsageFinder(static fn (): array => [], $db),
Mockery::mock(ChangeLog::class),
static fn (): bool => false
);
$file = (string) tempnam(sys_get_temp_dir(), 'lit-mcp-log');
$previous = ini_set('error_log', $file);
try {
$result = $ability->execute(['id' => 33, 'confirm' => true]);
} finally {
ini_set('error_log', (string) $previous);
unlink($file);
}
self::assertSame('lit_in_use', $result->get_error_code());
self::assertSame(MediaUsageFinder::FAILED_TITLE, $result->get_error_data()['usages'][0]['title']);
}
public function testChangeLogFailureIsOnlyAWarning(): void
{
Functions\expect('wp_delete_attachment')->once()->andReturn(new WP_Post(['ID' => 33]));
@@ -102,17 +102,19 @@ final class MediaUpdateAbilityTest extends TestCase
$failures = $result->get_error_data()['failures'];
self::assertSame([1, 2, 3], array_column($failures, 'index'));
self::assertSame(['not_found', 'not_found', 'validation_failed'], array_column($failures, 'code'));
self::assertSame([99, 5, 35], array_column($failures, 'id'));
self::assertStringContainsString('nicht gefunden', $failures[0]['error']);
self::assertStringContainsString('Papierkorb', $failures[2]['error']);
self::assertSame([], $this->postUpdates);
self::assertSame([], $this->altUpdates);
}
public function testFailuresOfOneKindKeepTheirCode(): void
public function testFailuresOfOneKindKeepTheirCodeAndReportTheNormalizedId(): void
{
$result = (new MediaUpdateAbility($this->log()))->execute(['items' => [['id' => 99, 'alt' => 'x']]]);
$result = (new MediaUpdateAbility($this->log()))->execute(['items' => [['id' => '99', 'alt' => 'x']]]);
self::assertSame('lit_not_found', $result->get_error_code());
self::assertSame(99, $result->get_error_data()['failures'][0]['id']);
}
public function testRejectsEmptyDuplicateAndOverlongItems(): void
@@ -165,6 +167,7 @@ final class MediaUpdateAbilityTest extends TestCase
} catch (WriteFailed $e) {
self::assertTrue($e->rolledBack);
self::assertSame('lit_write_failed', $e->toError()->get_error_code());
self::assertStringContainsString('neu lesen', $e->toError()->get_error_data()['hint']);
self::assertStringContainsString('Datenbankfehler', $e->getMessage());
}
@@ -316,4 +316,63 @@ final class MediaUsageFinderTest extends TestCase
self::assertStringNotContainsString('foto', $this->queries[1]);
self::assertStringNotContainsString("'%/%'", $this->queries[1]);
}
/**
* A finder whose query $failing (SQL fragment) fails – returns null or sets last_error.
*/
private function failingFinder(string $failing, bool $viaLastError): MediaUsageFinder
{
Functions\when('get_post_meta')->justReturn('2026/09/foto.jpg');
Functions\when('get_option')->justReturn(false);
Functions\when('get_theme_mod')->justReturn(false);
/** @var MockInterface&\wpdb $db */
$db = Mockery::mock(\wpdb::class)->makePartial();
$db->allows('get_results')->andReturnUsing(static function (string $sql) use ($db, $failing, $viaLastError) {
if (! str_contains($sql, $failing)) {
return [];
}
if ($viaLastError) {
$db->last_error = 'Lost connection to MySQL server';
return [];
}
return null;
});
return new MediaUsageFinder(static fn (): array => ['photo'], $db);
}
/** @return mixed Result of $run with error_log() redirected (a PHP internal, not stubbable). */
private static function quietly(callable $run): mixed
{
$file = (string) tempnam(sys_get_temp_dir(), 'lit-mcp-log');
$previous = ini_set('error_log', $file);
try {
return $run();
} finally {
ini_set('error_log', (string) $previous);
unlink($file);
}
}
public function testAFailedQueryNeverReportsUnused(): void
{
foreach (['_thumbnail_id', 'pm.meta_key IN', 'post_content LIKE'] as $failing) {
foreach ([true, false] as $viaLastError) {
$label = $failing . ($viaLastError ? ' (last_error)' : ' (null)');
self::assertTrue(self::quietly(fn () => $this->failingFinder($failing, $viaLastError)->isUsed(33)), $label);
$scan = self::quietly(fn () => $this->failingFinder($failing, $viaLastError)->scan(33));
self::assertFalse($scan['complete'], $label);
self::assertSame(
[['post_id' => 0, 'title' => MediaUsageFinder::FAILED_TITLE, 'post_type' => 'check', 'where' => 'unknown', 'certainty' => 'möglicherweise']],
$scan['usages'],
$label
);
}
}
}
}