recht: Meldeverfahren v2 Phasen 1-4 — Re-Sync-Sperre, Anonymisierung, Magic-Link-Intake, Self-Service-Korrektur
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>
This commit is contained in:
parent
021ee2d23c
commit
04b49c567d
42 changed files with 3868 additions and 1 deletions
230
app/Services/PressRelease/AnonymizationService.php
Normal file
230
app/Services/PressRelease/AnonymizationService.php
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\PressRelease;
|
||||
|
||||
use App\Enums\ActivityType;
|
||||
use App\Models\LegalRequest;
|
||||
use App\Models\PressRelease;
|
||||
use App\Models\PressReleaseRedactionSnapshot;
|
||||
use App\Services\ActivityLog;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Schwärzung personenbezogener Daten in einer Pressemitteilung
|
||||
* (Meldeverfahren v2, Spur B — Phase 2).
|
||||
*
|
||||
* Ersetzt Freitext-Schwärzwerte inkl. Varianten über Wortgrenzen in den
|
||||
* Textfeldern, löst Kontakt-Zuordnungen, entfernt markierte Bilder/Anhänge
|
||||
* und sichert die Vorher-Werte verschlüsselt (Reversibilität, nie Klartext
|
||||
* in Logs). Bewusst OHNE KI-Gate und OHNE Credit-Bezug — der DSGVO-Pfad
|
||||
* ist Compliance-Pflicht (Art. 12 Abs. 5) und darf an keinem Freigabelauf
|
||||
* oder Bezahlschritt hängen.
|
||||
*/
|
||||
class AnonymizationService
|
||||
{
|
||||
/** @var list<string> */
|
||||
public const REDACTABLE_FIELDS = ['title', 'subtitle', 'text', 'boilerplate_override', 'keywords'];
|
||||
|
||||
public const DEFAULT_REPLACEMENT = '[entfernt]';
|
||||
|
||||
public function __construct(private readonly ActivityLog $activityLog) {}
|
||||
|
||||
/**
|
||||
* Pflicht-Vorschau: Was würde ersetzt? Verändert die PM nicht.
|
||||
*
|
||||
* @param list<string> $terms
|
||||
* @return array{fields: array<string, array{hits: int, after: string}>, total_hits: int}
|
||||
*/
|
||||
public function preview(PressRelease $pressRelease, array $terms, string $replacement = self::DEFAULT_REPLACEMENT): array
|
||||
{
|
||||
$fields = [];
|
||||
$totalHits = 0;
|
||||
|
||||
foreach (self::REDACTABLE_FIELDS as $field) {
|
||||
$value = (string) ($pressRelease->getAttribute($field) ?? '');
|
||||
|
||||
if ($value === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$after, $hits] = $this->redact($value, $terms, $replacement);
|
||||
|
||||
if ($hits > 0) {
|
||||
$fields[$field] = ['hits' => $hits, 'after' => $after];
|
||||
$totalHits += $hits;
|
||||
}
|
||||
}
|
||||
|
||||
return ['fields' => $fields, 'total_hits' => $totalHits];
|
||||
}
|
||||
|
||||
/**
|
||||
* Führt die Schwärzung aus: Snapshot → Text-Replace → Kontakte lösen →
|
||||
* Bilder/Anhänge entfernen → Re-Sync-Sperre → Cache-Invalidierung →
|
||||
* Verlaufs-Eintrag ohne Klartext-Altwerte.
|
||||
*
|
||||
* @param list<string> $terms
|
||||
* @param list<int> $removeImageIds
|
||||
* @param list<int> $removeAttachmentIds
|
||||
*/
|
||||
public function execute(
|
||||
PressRelease $pressRelease,
|
||||
array $terms,
|
||||
string $replacement = self::DEFAULT_REPLACEMENT,
|
||||
bool $detachContacts = true,
|
||||
array $removeImageIds = [],
|
||||
array $removeAttachmentIds = [],
|
||||
?LegalRequest $legalRequest = null,
|
||||
): PressReleaseRedactionSnapshot {
|
||||
$totalHits = 0;
|
||||
|
||||
$snapshot = DB::transaction(function () use (
|
||||
$pressRelease, $terms, $replacement, $detachContacts,
|
||||
$removeImageIds, $removeAttachmentIds, $legalRequest, &$totalHits,
|
||||
): PressReleaseRedactionSnapshot {
|
||||
$contactIds = $detachContacts
|
||||
? $pressRelease->contacts()->pluck('contacts.id')->all()
|
||||
: [];
|
||||
|
||||
$images = $pressRelease->images()->whereIn('id', $removeImageIds)->get();
|
||||
$attachments = $pressRelease->attachments()->whereIn('id', $removeAttachmentIds)->get();
|
||||
|
||||
$snapshot = PressReleaseRedactionSnapshot::capture($pressRelease, [
|
||||
'fields' => $pressRelease->only(self::REDACTABLE_FIELDS),
|
||||
'contact_ids' => $contactIds,
|
||||
'images' => $images->map(fn ($image) => $image->only(['id', 'disk', 'path', 'title']))->all(),
|
||||
'attachments' => $attachments->map(fn ($attachment) => $attachment->only(['id', 'disk', 'path']))->all(),
|
||||
'terms' => $terms,
|
||||
'replacement' => $replacement,
|
||||
], $legalRequest);
|
||||
|
||||
$changedFields = [];
|
||||
|
||||
foreach (self::REDACTABLE_FIELDS as $field) {
|
||||
$value = (string) ($pressRelease->getAttribute($field) ?? '');
|
||||
|
||||
if ($value === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$after, $hits] = $this->redact($value, $terms, $replacement);
|
||||
|
||||
if ($hits > 0) {
|
||||
$pressRelease->setAttribute($field, $after);
|
||||
$changedFields[] = $field;
|
||||
$totalHits += $hits;
|
||||
}
|
||||
}
|
||||
|
||||
if ($changedFields !== []) {
|
||||
$pressRelease->save();
|
||||
}
|
||||
|
||||
if ($contactIds !== []) {
|
||||
$pressRelease->contacts()->detach($contactIds);
|
||||
}
|
||||
|
||||
// Klarname in Pressebild/PDF: Zeile soft-löschen (raus aus der
|
||||
// Auslieferung); auf der public-Disk zusätzlich die Dateien
|
||||
// entfernen, weil sie sonst per Direkt-URL erreichbar blieben.
|
||||
foreach ($images as $image) {
|
||||
$this->deletePublicFiles($image->disk, array_filter([
|
||||
$image->path,
|
||||
...array_values((array) ($image->variants ?? [])),
|
||||
]));
|
||||
$image->delete();
|
||||
}
|
||||
|
||||
foreach ($attachments as $attachment) {
|
||||
$this->deletePublicFiles($attachment->disk, array_filter([$attachment->path]));
|
||||
$attachment->delete();
|
||||
}
|
||||
|
||||
$pressRelease->lockSync(
|
||||
'Anonymisierung im Meldeverfahren'.($legalRequest ? ' '.$legalRequest->reference() : '')
|
||||
);
|
||||
|
||||
return $snapshot;
|
||||
});
|
||||
|
||||
$this->forgetSitemapCaches();
|
||||
|
||||
// Bewusst ohne Alt-Werte und ohne Schwärzbegriffe — sonst leben die
|
||||
// personenbezogenen Daten im Verlauf weiter.
|
||||
$this->activityLog->record(
|
||||
ActivityType::Anonymization,
|
||||
sprintf(
|
||||
'PM anonymisiert%s: %d Ersetzung(en), %d Kontakt(e) gelöst, %d Bild(er), %d Anhang/Anhänge entfernt.',
|
||||
$legalRequest ? ' ('.$legalRequest->reference().')' : '',
|
||||
$totalHits,
|
||||
count($snapshot->encrypted_before['contact_ids'] ?? []),
|
||||
count($snapshot->encrypted_before['images'] ?? []),
|
||||
count($snapshot->encrypted_before['attachments'] ?? []),
|
||||
),
|
||||
user: Auth::user(),
|
||||
subject: $pressRelease,
|
||||
meta: ['legal_request_id' => $legalRequest?->getKey(), 'snapshot_id' => $snapshot->getKey()],
|
||||
);
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ersetzung über Wortgrenzen: Lookarounds auf Unicode-Buchstaben/Ziffern
|
||||
* statt \b, damit Umlaute korrekt begrenzen und weder Teiltreffer
|
||||
* stehenbleiben noch Wörter wie „maximal" bei Begriff „Max" zerlegt
|
||||
* werden. Längste Begriffe zuerst („Matvey Teplitsky" vor „Teplitsky").
|
||||
*
|
||||
* @param list<string> $terms
|
||||
* @return array{0: string, 1: int}
|
||||
*/
|
||||
private function redact(string $value, array $terms, string $replacement): array
|
||||
{
|
||||
$totalHits = 0;
|
||||
|
||||
$normalized = collect($terms)
|
||||
->map(fn (string $term): string => trim($term))
|
||||
->filter()
|
||||
->unique()
|
||||
->sortByDesc(fn (string $term): int => mb_strlen($term))
|
||||
->values();
|
||||
|
||||
foreach ($normalized as $term) {
|
||||
$pattern = '/(?<![\pL\pN])'.preg_quote($term, '/').'(?![\pL\pN])/iu';
|
||||
$value = (string) preg_replace($pattern, $replacement, $value, -1, $hits);
|
||||
$totalHits += (int) $hits;
|
||||
}
|
||||
|
||||
return [$value, $totalHits];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $paths
|
||||
*/
|
||||
private function deletePublicFiles(?string $disk, array $paths): void
|
||||
{
|
||||
if ($disk !== 'public' || $paths === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
Storage::disk('public')->delete($paths);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sitemap-Caches aller Hosts verwerfen (SitemapController cached 1h je
|
||||
* Host) — nach einer Schwärzung darf kein Cache den alten Stand halten.
|
||||
*/
|
||||
private function forgetSitemapCaches(): void
|
||||
{
|
||||
foreach ((array) config('domains.domains', []) as $domain) {
|
||||
$host = parse_url((string) ($domain['url'] ?? ''), PHP_URL_HOST);
|
||||
|
||||
if ($host) {
|
||||
Cache::forget('web.sitemap.'.$host);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
18
app/Services/PressRelease/CorrectionRateLimitException.php
Normal file
18
app/Services/PressRelease/CorrectionRateLimitException.php
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\PressRelease;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Spur-A-Bremse: zu viele Selbstbedienungs-Korrekturen für diese PM im
|
||||
* Zeitfenster (legal.corrections_per_week) — verhindert, dass die kostenlose
|
||||
* Korrektur per Salami-Taktik zum Voll-Editor wird.
|
||||
*/
|
||||
class CorrectionRateLimitException extends Exception
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('Für diese Pressemitteilung wurden zuletzt bereits mehrere Korrekturen gespeichert. Bitte versuchen Sie es später erneut.');
|
||||
}
|
||||
}
|
||||
329
app/Services/PressRelease/CorrectionService.php
Normal file
329
app/Services/PressRelease/CorrectionService.php
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
<?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];
|
||||
}
|
||||
}
|
||||
17
app/Services/PressRelease/CorrectionTooLargeException.php
Normal file
17
app/Services/PressRelease/CorrectionTooLargeException.php
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\PressRelease;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Die Änderung überschreitet die Spur-A-Grenze (legal.correction_max_distance_percent)
|
||||
* — sie ist keine kleine Korrektur mehr, sondern eine kostenpflichtige Änderung (Spur D).
|
||||
*/
|
||||
class CorrectionTooLargeException extends Exception
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('Die Änderung überschreitet den Rahmen einer kleinen Korrektur.');
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue