- A-01/A-02/A-04: archive_pending_jobs je Vorgang (ArchivePendingQueue), Depublikationsstand am Auftrag festgehalten, Nachholer ohne Schlüssel FAILURE; archive_pending_at nur noch Sammelmarker - O07: Direktweg und Nachholer beanspruchen den Auftrag unter Zeilensperre - O08: fehlende Snapshot-Datei → Verweis auf den image_removed-Eintrag oder offener Auftrag, nie ein still unvollständiger Nachweis - A-03/A-06: Sweep verschiebt in die Quarantäne, Pause beim Restore, archive:reregister; Restore-Abgleich löscht Anwendungskopien erneut - O04/O05: Restore ordnet über den Payload-Pfad zu; unsignierte Exporte nur mit --accept-unsigned, reregister bricht bei ungültigem/fehlendem Export ab - A-05, A-07 bis A-15: Altbestand als möglicherweise veröffentlicht, Hold- Historie, Zweck per POST, Nachweise gelöschter Bilder nur mit compliance:manage, Anhänge auf ihrer Disk, Schlüssel-ID und ARCHIVE_PREVIOUS_KEYS, HMAC per HKDF, archive:verify-export - 5.1 d: Depublikation im Meldeverfahren trägt legal_request_id PressReleaseService.php enthält zusätzlich K-01 (Prüfung im Publish-Lock), N19 (archive() gibt Kopien frei) und N09 (markImagesPublished nur für auslieferbare Bilder), weil die Datei ungeteilt committet ist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
338 lines
13 KiB
PHP
338 lines
13 KiB
PHP
<?php
|
|
|
|
namespace App\Services\PressRelease;
|
|
|
|
use App\Enums\ActivityType;
|
|
use App\Enums\ArchiveEvent;
|
|
use App\Enums\ArchiveReasonCategory;
|
|
use App\Models\ArchiveEntry;
|
|
use App\Models\ArchivePendingJob;
|
|
use App\Models\LegalRequest;
|
|
use App\Models\PressRelease;
|
|
use App\Models\PressReleaseImage;
|
|
use App\Models\PressReleaseRedactionSnapshot;
|
|
use App\Services\ActivityLog;
|
|
use App\Services\Archive\ArchivePendingQueue;
|
|
use App\Services\Archive\PressReleaseArchiver;
|
|
use App\Services\Image\ImageService;
|
|
use App\Services\PressRelease\Images\PressReleaseImageRemover;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Throwable;
|
|
|
|
/**
|
|
* 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. Deshalb blockiert auch das Beweisarchiv
|
|
* nicht: Jeder Archiveintrag ist ein Auftrag (ArchivePendingQueue), ein
|
|
* fehlgeschlagener bleibt offen und wird nachgeholt (N11, Umsetzungsaudit
|
|
* 29.09.2026 A-02/A-10).
|
|
*/
|
|
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,
|
|
private readonly PressReleaseImageRemover $imageRemover,
|
|
private readonly PressReleaseArchiver $archiver,
|
|
private readonly ImageService $imageService,
|
|
private readonly ArchivePendingQueue $archiveQueue,
|
|
) {}
|
|
|
|
/**
|
|
* 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 →
|
|
* Anhänge entfernen → Re-Sync-Sperre → Commit → Bilder über den
|
|
* Remover (Beweisarchiv, N12) → Archiveintrag → 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;
|
|
$images = collect();
|
|
$job = null;
|
|
|
|
$snapshot = DB::transaction(function () use (
|
|
$pressRelease, $terms, $replacement, $detachContacts,
|
|
$removeImageIds, $removeAttachmentIds, $legalRequest, &$totalHits, &$images, &$job,
|
|
): 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);
|
|
|
|
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);
|
|
$totalHits += $hits;
|
|
}
|
|
}
|
|
|
|
$pressRelease->save();
|
|
|
|
// Archivauftrag in derselben Transaktion (N11): Vorher-Stand aus
|
|
// dem Snapshot, Nachher-Stand dieser Schwärzung — ein späteres
|
|
// Nachholen bildet nicht einen noch späteren Stand ab (A-04).
|
|
$job = $this->archiveQueue->push(
|
|
(int) $pressRelease->getKey(),
|
|
ArchiveEvent::GdprChange,
|
|
$snapshot,
|
|
ArchiveReasonCategory::Gdpr,
|
|
$legalRequest?->getKey(),
|
|
Auth::id() !== null ? (int) Auth::id() : null,
|
|
'Anonymisierung: '.count($terms).' Begriff(e), '.count($removeImageIds).' Bild(er), '.count($contactIds).' Kontakt(e)',
|
|
[
|
|
'before' => (array) ($snapshot->encrypted_before['fields'] ?? []),
|
|
'after' => $pressRelease->only(self::REDACTABLE_FIELDS),
|
|
],
|
|
);
|
|
|
|
if ($contactIds !== []) {
|
|
$pressRelease->contacts()->detach($contactIds);
|
|
}
|
|
|
|
foreach ($attachments as $attachment) {
|
|
$this->deleteAttachmentFiles($attachment->disk, array_values(array_filter([$attachment->path])));
|
|
$attachment->delete();
|
|
}
|
|
|
|
$pressRelease->lockSync(
|
|
'Anonymisierung im Meldeverfahren'.($legalRequest ? ' '.$legalRequest->reference() : '')
|
|
);
|
|
|
|
return $snapshot;
|
|
});
|
|
|
|
// Klarname in Pressebild/PDF: über den gemeinsamen Lebenszyklus
|
|
// (Beweisarchiv bei veröffentlichten Bildern, Sofortlöschung sonst).
|
|
foreach ($images as $image) {
|
|
$this->removeImage($image, $legalRequest);
|
|
}
|
|
|
|
$this->forgetSitemapCaches();
|
|
|
|
// Beweisarchiv (Block F.4): Diff alt/neu mit Antrag — dort dürfen die
|
|
// Altwerte liegen (verschlüsselt, zugriffsprotokolliert), im
|
|
// Aktivitätsverlauf nicht.
|
|
$entry = $this->archiveChange($pressRelease, $job, $snapshot, $legalRequest);
|
|
|
|
// 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(), 'archive_entry_id' => $entry?->getKey()],
|
|
);
|
|
|
|
return $snapshot;
|
|
}
|
|
|
|
/**
|
|
* Bild über den Remover entfernen (N12). Scheitert das Archiv oder die
|
|
* Sofortlöschung, muss der Klarname trotzdem sofort aus der
|
|
* Auslieferung: Derivate weg, Soft Delete. Der Rest wird als Auftrag
|
|
* festgehalten — Archiveintrag für ein veröffentlichtes v2-Bild,
|
|
* Sofortlöschung für ein nie veröffentlichtes (A-10) — und vom
|
|
* Nachholer erledigt.
|
|
*/
|
|
private function removeImage(PressReleaseImage $image, ?LegalRequest $legalRequest): void
|
|
{
|
|
try {
|
|
$this->imageRemover->remove($image, Auth::user(), ArchiveEvent::ImageRemoved, ArchiveReasonCategory::Gdpr, $legalRequest);
|
|
|
|
return;
|
|
} catch (Throwable $exception) {
|
|
Log::error('Beweisarchiv: Bild aus Anonymisierung konnte nicht überführt werden, wird nachgeholt.', [
|
|
'press_release_image_id' => $image->getKey(),
|
|
'error' => $exception->getMessage(),
|
|
]);
|
|
|
|
$current = PressReleaseImage::withTrashed()->find($image->getKey());
|
|
|
|
if ($current === null) {
|
|
return;
|
|
}
|
|
|
|
$this->imageService->deletePressReleaseImage($current->disk, $current->path, $current->variants);
|
|
|
|
if (! $current->trashed()) {
|
|
$current->delete();
|
|
}
|
|
|
|
if ($current->isLegacyRules()) {
|
|
return;
|
|
}
|
|
|
|
if ($current->wasEverPublished()) {
|
|
$this->archiveQueue->push(
|
|
(int) $current->press_release_id,
|
|
ArchiveEvent::ImageRemoved,
|
|
$current,
|
|
ArchiveReasonCategory::Gdpr,
|
|
$legalRequest?->getKey(),
|
|
Auth::id() !== null ? (int) Auth::id() : null,
|
|
'Bild aus Anonymisierung',
|
|
);
|
|
|
|
return;
|
|
}
|
|
|
|
$this->archiveQueue->pushImagePurge($current, $exception->getMessage());
|
|
}
|
|
}
|
|
|
|
private function archiveChange(PressRelease $pressRelease, ArchivePendingJob $job, PressReleaseRedactionSnapshot $snapshot, ?LegalRequest $legalRequest): ?ArchiveEntry
|
|
{
|
|
$payload = (array) $job->payload;
|
|
|
|
return $this->archiveQueue->completeWith($job, fn () => $this->archiver->gdprChange(
|
|
$pressRelease,
|
|
(array) ($payload['before'] ?? []),
|
|
(array) ($payload['after'] ?? []),
|
|
$legalRequest,
|
|
Auth::user(),
|
|
ArchiveReasonCategory::Gdpr,
|
|
$job->note,
|
|
$snapshot->getKey(),
|
|
));
|
|
}
|
|
|
|
/**
|
|
* 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];
|
|
}
|
|
|
|
/**
|
|
* Anhänge liegen nach der Privatisierung auf `local`, davor auf
|
|
* `public` — gelöscht wird auf der Disk, die die Zeile nennt (A-12).
|
|
*
|
|
* @param list<string> $paths
|
|
*/
|
|
private function deleteAttachmentFiles(?string $disk, array $paths): void
|
|
{
|
|
if ($paths === [] || ! in_array($disk ?? 'public', ['public', 'local'], true)) {
|
|
return;
|
|
}
|
|
|
|
Storage::disk($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);
|
|
}
|
|
}
|
|
}
|
|
}
|