Phase 1: sync_locked_at auf press_releases (Importer überspringt gesperrte PMs auch bei --force), LegalRequest um Verifikation/Ausführung erweitert, verschlüsselte Vorher-Snapshots mit Löschfrist (snapshots:purge, täglich). Phase 2: AnonymizationService (Unicode-Wortgrenzen-Schwärzung, Pflicht-Diff, transaktionale Ausführung mit Snapshot, Kontakt-Detach, Bild-Löschung, Sitemap-Invalidierung, Verlauf ohne Klartext-Altwerte); Admin-Queue kann DSGVO-Anfragen anonymisieren oder depublizieren, inkl. Snapshot-Restore. Phase 3: Deflektions-Trichter „PM melden/ändern" (melden/pm) mit Kosten- Tabelle vorab; Magic-Link geht nur an die hinterlegte Pressekontaktadresse (neuer purpose press_release_report), atomare Verifikation, Anliegen-Auswahl erzeugt verifizierte Queue-Anfragen; toter-Kanal-Fallback; Owner-Einstieg. Phase 4: Panel-Abschnitt „Änderung & Korrektur" — Levenshtein-Gate (5 %, Mini-Edit-Ausnahme ≤ 2 Zeichen) stuft klein/groß ein; kleine Korrektur kostenlos sofort live (Snapshot, Sperre, Verlauf, Re-Score), größere als Change-Anfrage (Interim bis 10-€-Checkout, Phase 7). Entwicklungsplan mit Entscheidungen E1-E8 und offenen Punkten in docs/Decision-Update; 41 Pest-Tests (tests/Feature/Legal) grün. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
329 lines
12 KiB
PHP
329 lines
12 KiB
PHP
<?php
|
|
|
|
namespace App\Services\PressRelease;
|
|
|
|
use App\Enums\ActivityType;
|
|
use App\Enums\LegalRequestStatus;
|
|
use App\Enums\LegalRequestType;
|
|
use App\Enums\LegalRequestVerificationMethod;
|
|
use App\Models\LegalRequest;
|
|
use App\Models\PressRelease;
|
|
use App\Models\PressReleaseRedactionSnapshot;
|
|
use App\Models\User;
|
|
use App\Services\ActivityLog;
|
|
use App\Support\WebCaches;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
/**
|
|
* Kleine Korrektur (Meldeverfahren v2, Spur A — Phase 4): Selbstbedienungs-
|
|
* Korrektur ohne neuen Inhalt, sofort live. Die Free/Paid-Einstufung trifft
|
|
* NICHT der Antragsteller, sondern das Levenshtein-Gate: bleibt die relative
|
|
* Änderungsdistanz jedes Felds unter legal.correction_max_distance_percent,
|
|
* ist es Spur A (kostenlos) — darüber Spur D (kostenpflichtige Änderung).
|
|
*/
|
|
class CorrectionService
|
|
{
|
|
/** @var list<string> */
|
|
public const CORRECTABLE_FIELDS = ['title', 'subtitle', 'text', 'keywords'];
|
|
|
|
public function __construct(
|
|
private readonly ActivityLog $activityLog,
|
|
private readonly PressReleaseService $pressReleaseService,
|
|
private readonly PressReleaseHtmlSanitizer $sanitizer,
|
|
) {}
|
|
|
|
/**
|
|
* Einstufung klein/groß je Feld — verändert nichts.
|
|
*
|
|
* @param array<string, string|null> $newValues
|
|
* @return array{fields: array<string, array{distance_percent: float, changed: bool}>, max_distance_percent: float, has_changes: bool, is_minor: bool}
|
|
*/
|
|
public function classify(PressRelease $pressRelease, array $newValues): array
|
|
{
|
|
$threshold = (int) config('legal.correction_max_distance_percent');
|
|
$fields = [];
|
|
$maxPercent = 0.0;
|
|
$hasChanges = false;
|
|
|
|
$allMinor = true;
|
|
|
|
foreach (self::CORRECTABLE_FIELDS as $field) {
|
|
if (! array_key_exists($field, $newValues)) {
|
|
continue;
|
|
}
|
|
|
|
$old = $this->comparableText((string) ($pressRelease->getAttribute($field) ?? ''));
|
|
$new = $this->comparableText((string) ($newValues[$field] ?? ''));
|
|
|
|
if ($old === $new) {
|
|
$fields[$field] = ['distance_percent' => 0.0, 'changed' => false];
|
|
|
|
continue;
|
|
}
|
|
|
|
$percent = $this->distancePercent($old, $new);
|
|
|
|
// Mini-Edit-Ausnahme: bis 2 Zeichen ist es immer ein Tippfehler-Fix
|
|
// — sonst würde bei kurzen Titeln schon ein einzelner Buchstabe
|
|
// die Prozent-Grenze reißen und Spur A ins Leere laufen.
|
|
$isMinorField = $percent <= $threshold || $this->isTinyEdit($old, $new);
|
|
|
|
$fields[$field] = ['distance_percent' => $percent, 'changed' => true];
|
|
$maxPercent = max($maxPercent, $percent);
|
|
$hasChanges = true;
|
|
$allMinor = $allMinor && $isMinorField;
|
|
}
|
|
|
|
return [
|
|
'fields' => $fields,
|
|
'max_distance_percent' => $maxPercent,
|
|
'has_changes' => $hasChanges,
|
|
'is_minor' => $hasChanges && $allMinor,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Führt eine kleine Korrektur aus: Snapshot (Rückgängig-Option) →
|
|
* Felder schreiben → Re-Sync-Sperre → Verlauf → Re-Score ohne
|
|
* Status-Wirkung. Wirft, wenn das Gate reißt oder die Bremse greift.
|
|
*
|
|
* @param array<string, string|null> $newValues
|
|
*
|
|
* @throws CorrectionTooLargeException
|
|
* @throws CorrectionRateLimitException
|
|
*/
|
|
public function apply(
|
|
PressRelease $pressRelease,
|
|
array $newValues,
|
|
string $requesterEmail,
|
|
LegalRequestVerificationMethod $method,
|
|
?User $actor = null,
|
|
): LegalRequest {
|
|
$classification = $this->classify($pressRelease, $newValues);
|
|
|
|
if (! $classification['is_minor']) {
|
|
throw new CorrectionTooLargeException;
|
|
}
|
|
|
|
$this->assertNotRateLimited($pressRelease);
|
|
|
|
$legalRequest = DB::transaction(function () use ($pressRelease, $newValues, $requesterEmail, $method, $classification): LegalRequest {
|
|
$legalRequest = LegalRequest::query()->create([
|
|
'press_release_id' => $pressRelease->id,
|
|
'portal' => $pressRelease->portal?->value,
|
|
'type' => LegalRequestType::Correction->value,
|
|
'status' => LegalRequestStatus::Resolved->value,
|
|
'requester_email' => $requesterEmail,
|
|
'message' => null,
|
|
'payload' => [
|
|
'source' => 'self_service',
|
|
'fields' => $classification['fields'],
|
|
],
|
|
'verified_at' => now(),
|
|
'verification_method' => $method->value,
|
|
'resolved_at' => now(),
|
|
'executed_at' => now(),
|
|
]);
|
|
|
|
PressReleaseRedactionSnapshot::capture($pressRelease, [
|
|
'fields' => $pressRelease->only(self::CORRECTABLE_FIELDS),
|
|
], $legalRequest);
|
|
|
|
foreach ($classification['fields'] as $field => $meta) {
|
|
if (! $meta['changed']) {
|
|
continue;
|
|
}
|
|
|
|
$value = (string) ($newValues[$field] ?? '');
|
|
|
|
if ($field === 'text' && $this->sanitizer->isHtml($value)) {
|
|
$value = $this->sanitizer->clean($value);
|
|
}
|
|
|
|
$pressRelease->setAttribute($field, $value !== '' ? $value : null);
|
|
}
|
|
|
|
$pressRelease->save();
|
|
$pressRelease->lockSync('Kleine Korrektur '.$legalRequest->reference());
|
|
|
|
return $legalRequest;
|
|
});
|
|
|
|
WebCaches::forgetSitemaps();
|
|
|
|
$changedFields = collect($classification['fields'])
|
|
->filter(fn (array $meta): bool => $meta['changed'])
|
|
->keys()
|
|
->implode(', ');
|
|
|
|
$this->activityLog->record(
|
|
ActivityType::Correction,
|
|
sprintf(
|
|
'Kleine Korrektur (%s) gespeichert: Feld(er) %s, max. Distanz %.1f %%.',
|
|
$legalRequest->reference(),
|
|
$changedFields,
|
|
$classification['max_distance_percent'],
|
|
),
|
|
user: $actor,
|
|
subject: $pressRelease,
|
|
meta: ['legal_request_id' => $legalRequest->id],
|
|
);
|
|
|
|
// Re-Check ohne Status-Wirkung — konsistent mit dem bestehenden
|
|
// Edit-Verhalten; Spur A hat bewusst kein Freigabelauf-Gate.
|
|
$this->pressReleaseService->reprocessAfterContentChange($pressRelease);
|
|
|
|
return $legalRequest;
|
|
}
|
|
|
|
/**
|
|
* Rückgängig machen (Admin): stellt die Feld-Werte aus dem verschlüsselten
|
|
* Snapshot wieder her und hängt gelöste Kontakte wieder an. Bilder werden
|
|
* nur wiederhergestellt, wenn ihre Dateien noch existieren (nicht public
|
|
* gelöscht). Die Re-Sync-Sperre bleibt bestehen.
|
|
*/
|
|
public function restoreSnapshot(PressReleaseRedactionSnapshot $snapshot, ?User $actor = null): void
|
|
{
|
|
$pressRelease = $snapshot->pressRelease()->withoutGlobalScopes()->firstOrFail();
|
|
$before = $snapshot->encrypted_before;
|
|
|
|
DB::transaction(function () use ($pressRelease, $before): void {
|
|
foreach ((array) ($before['fields'] ?? []) as $field => $value) {
|
|
$pressRelease->setAttribute($field, $value);
|
|
}
|
|
|
|
$pressRelease->save();
|
|
|
|
$contactIds = (array) ($before['contact_ids'] ?? []);
|
|
|
|
if ($contactIds !== []) {
|
|
$pressRelease->contacts()->syncWithoutDetaching($contactIds);
|
|
}
|
|
|
|
foreach ((array) ($before['images'] ?? []) as $imageMeta) {
|
|
if (($imageMeta['disk'] ?? null) === 'public') {
|
|
continue; // Datei wurde physisch gelöscht — Zeile bliebe kaputt.
|
|
}
|
|
|
|
$pressRelease->images()->withTrashed()->whereKey($imageMeta['id'] ?? 0)->restore();
|
|
}
|
|
});
|
|
|
|
WebCaches::forgetSitemaps();
|
|
|
|
$this->activityLog->record(
|
|
ActivityType::Correction,
|
|
sprintf('Snapshot #%d wiederhergestellt — Vorher-Stand der PM zurückgespielt.', $snapshot->id),
|
|
user: $actor,
|
|
subject: $pressRelease,
|
|
meta: ['snapshot_id' => $snapshot->id, 'legal_request_id' => $snapshot->legal_request_id],
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @throws CorrectionRateLimitException
|
|
*/
|
|
private function assertNotRateLimited(PressRelease $pressRelease): void
|
|
{
|
|
$recent = LegalRequest::query()
|
|
->where('press_release_id', $pressRelease->id)
|
|
->where('type', LegalRequestType::Correction->value)
|
|
->whereNotNull('executed_at')
|
|
->where('executed_at', '>=', now()->subWeek())
|
|
->count();
|
|
|
|
if ($recent >= (int) config('legal.corrections_per_week')) {
|
|
throw new CorrectionRateLimitException;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Bis 2 Zeichen Distanz ist jede Änderung ein Tippfehler-Fix (nur für
|
|
* Werte im levenshtein()-Limit von 255 Bytes bestimmbar).
|
|
*/
|
|
private function isTinyEdit(string $old, string $new): bool
|
|
{
|
|
return strlen($old) <= 255
|
|
&& strlen($new) <= 255
|
|
&& levenshtein($old, $new) <= 2;
|
|
}
|
|
|
|
/**
|
|
* Vergleichsbasis: HTML raus, Whitespace normalisiert — reine
|
|
* Markup-Änderungen zählen nicht als inhaltliche Distanz.
|
|
*/
|
|
private function comparableText(string $value): string
|
|
{
|
|
$plain = strip_tags($value);
|
|
$collapsed = preg_replace('/\s+/u', ' ', $plain) ?? $plain;
|
|
|
|
return trim($collapsed);
|
|
}
|
|
|
|
/**
|
|
* Relative Änderungsdistanz in Prozent. Kurze Felder zeichenbasiert
|
|
* (ein Tippfehler im Titel bleibt „klein"), lange Texte wortbasiert —
|
|
* PHPs levenshtein() ist auf 255 Bytes begrenzt und zeichenweises DP
|
|
* wäre bei langen Texten zu teuer.
|
|
*/
|
|
private function distancePercent(string $old, string $new): float
|
|
{
|
|
if (strlen($old) <= 255 && strlen($new) <= 255) {
|
|
$max = max(mb_strlen($old), mb_strlen($new), 1);
|
|
|
|
return round(levenshtein($old, $new) / $max * 100, 1);
|
|
}
|
|
|
|
$oldWords = preg_split('/\s+/u', $old, -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
|
$newWords = preg_split('/\s+/u', $new, -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
|
$max = max(count($oldWords), count($newWords), 1);
|
|
$lengthDiffPercent = abs(count($oldWords) - count($newWords)) / $max * 100;
|
|
|
|
// Die Längendifferenz ist eine untere Schranke der Distanz — ab 50 %
|
|
// ist das sicher „groß", das teure DP kann entfallen. Ebenso bei
|
|
// extrem langen Texten (DP-Kostengrenze).
|
|
if ($lengthDiffPercent >= 50.0 || $max > 20000) {
|
|
return max(round($lengthDiffPercent, 1), 50.0);
|
|
}
|
|
|
|
return round($this->wordLevenshtein($oldWords, $newWords) / $max * 100, 1);
|
|
}
|
|
|
|
/**
|
|
* Klassisches Levenshtein-DP auf Wort-Ebene (zwei Zeilen Speicher).
|
|
*
|
|
* @param list<string> $a
|
|
* @param list<string> $b
|
|
*/
|
|
private function wordLevenshtein(array $a, array $b): int
|
|
{
|
|
$countA = count($a);
|
|
$countB = count($b);
|
|
|
|
if ($countA === 0) {
|
|
return $countB;
|
|
}
|
|
|
|
if ($countB === 0) {
|
|
return $countA;
|
|
}
|
|
|
|
$previous = range(0, $countB);
|
|
|
|
for ($i = 1; $i <= $countA; $i++) {
|
|
$current = [$i];
|
|
|
|
for ($j = 1; $j <= $countB; $j++) {
|
|
$current[$j] = min(
|
|
$previous[$j] + 1,
|
|
$current[$j - 1] + 1,
|
|
$previous[$j - 1] + ($a[$i - 1] === $b[$j - 1] ? 0 : 1),
|
|
);
|
|
}
|
|
|
|
$previous = $current;
|
|
}
|
|
|
|
return $previous[$countB];
|
|
}
|
|
}
|