Formulare, WordPress-Import und E-Mail-Versand
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m0s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m11s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m7s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m52s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 3m2s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m31s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 2m27s
CI / Build-Artefakte aktuell (pull_request) Successful in 53s

- Formular-Plugin: Baukasten mit 13 Feldtypen, Bedingungen, Vorbelegung
  aus dem Profil, Datei-Uploads (geschützt), anonyme Formulare, „nur einmal“,
  Einsendeschluss, Sichtbarkeit, Löschfrist; Einsendungen im Backend und per
  Mail (optional ohne Angaben, Kopie an die Person); Rechte je Formular und
  Rolle für Ansehen/Export und Löschen; CSV für Excel; Pagebuilder-Block
- WordPress-Import (Plugin): WXR-Datei einlesen, Kategorien/Personen zuordnen,
  Beiträge mit Status, Datum, Beitragsbild und Bildern im Text übernehmen,
  optional Seiten mit Hierarchie; in Portionen, wiederholbar ohne Doppelungen
- E-Mail-Versand im Admin (SMTP, verschlüsseltes Passwort, Test-Mail)
- Speichertest unabhängig vom Verbrauch der Test-Suite

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 09:20:54 +00:00
parent f3987e8386
commit 11123fecc0
118 changed files with 4446 additions and 169 deletions

View file

@ -0,0 +1,60 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('wp_imports', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
$table->string('file');
$table->string('site_title')->nullable();
$table->string('site_url')->nullable();
// analyzed → running → done (oder failed)
$table->string('status', 20)->default('analyzed');
$table->json('options')->nullable();
$table->json('stats')->nullable();
$table->longText('log')->nullable();
$table->timestamps();
});
// Zwischenablage der Exportdatei: je Eintrag eine Zeile, abgearbeitet in Portionen.
Schema::create('wp_import_items', function (Blueprint $table) {
$table->id();
$table->foreignId('import_id')->constrained('wp_imports')->cascadeOnDelete();
$table->string('type', 20); // category, author, attachment, post, page
$table->unsignedBigInteger('wp_id')->default(0);
$table->unsignedBigInteger('wp_parent')->default(0);
$table->string('status', 12)->default('pending'); // pending, done, skipped, failed
$table->longText('data');
$table->string('message', 500)->nullable();
$table->index(['import_id', 'type', 'status']);
$table->index(['import_id', 'type', 'wp_id']);
});
// Was schon übernommen wurde – ein erneuter Import legt nichts doppelt an.
Schema::create('wp_import_refs', function (Blueprint $table) {
$table->id();
$table->string('source', 191);
$table->string('type', 20); // post, page, category, media
$table->string('wp_key', 191);
$table->string('local_type', 60);
$table->string('local_value', 500);
$table->timestamps();
$table->unique(['source', 'type', 'wp_key']);
});
}
public function down(): void
{
Schema::dropIfExists('wp_import_refs');
Schema::dropIfExists('wp_import_items');
Schema::dropIfExists('wp_imports');
}
};

View file

@ -0,0 +1,14 @@
{
"slug": "wordpress-import",
"name": "WordPress-Import",
"version": "1.0.0",
"description": "Übernimmt Beiträge, Kategorien, Bilder und Seiten aus einer WordPress-Exportdatei – für den Umstieg auf das Portal.",
"author": "Inhaus",
"namespace": "Inhaus\\Plugins\\WordpressImport\\",
"class": "Inhaus\\Plugins\\WordpressImport\\WordpressImportPlugin",
"requires": {
"core": ">=0.6.0",
"php": ">=8.3",
"plugins": ["news"]
}
}

View file

@ -0,0 +1,79 @@
@php($import = $this->getImport())
<x-filament-panels::page>
@if (! $import)
<form wire:submit="analyze" class="grid gap-6">
{{ $this->uploadForm }}
<div>
<x-filament::button type="submit" icon="heroicon-o-magnifying-glass">Datei prüfen</x-filament::button>
</div>
</form>
@if ($this->history()->isNotEmpty())
<x-filament::section heading="Bisherige Importe">
<ul class="divide-y divide-gray-100 text-sm dark:divide-white/5">
@foreach ($this->history() as $past)
<li class="flex flex-wrap justify-between gap-2 py-2">
<span>{{ $past->site_title ?: $past->site_url }} · {{ $past->created_at->format('d.m.Y H:i') }}</span>
<span class="text-gray-500">
{{ $past->status === 'done' ? 'abgeschlossen' : 'abgebrochen' }}:
{{ $past->stats['created'] ?? 0 }} neu, {{ $past->stats['updated'] ?? 0 }} aktualisiert, {{ $past->stats['skipped'] ?? 0 }} übersprungen, {{ $past->stats['failed'] ?? 0 }} Fehler
</span>
</li>
@endforeach
</ul>
</x-filament::section>
@endif
@elseif ($import->status === 'analyzed')
@php($found = $import->stats['found'] ?? [])
<x-filament::section :heading="'Gefunden in „'.($import->site_title ?: 'WordPress').'“'" :description="$import->site_url">
<dl class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-5">
@foreach (['post' => 'Beiträge', 'page' => 'Seiten', 'category' => 'Kategorien', 'author' => 'Autor:innen', 'attachment' => 'Medien'] as $key => $label)
<div class="rounded-lg bg-gray-50 p-3 dark:bg-white/5">
<dt class="text-gray-500">{{ $label }}</dt>
<dd class="text-2xl font-semibold">{{ $found[$key] ?? 0 }}</dd>
</div>
@endforeach
</dl>
@if (($found['drafts'] ?? 0) > 0)
<p class="mt-3 text-sm text-gray-500">Davon {{ $found['drafts'] }} Entwürfe. Kommentare, Schlagwörter und Einträge anderer Plugins werden nicht übernommen.</p>
@endif
</x-filament::section>
<form wire:submit="start" class="grid gap-6">
{{ $this->optionsForm }}
<div class="flex gap-3">
<x-filament::button type="submit" icon="heroicon-o-arrow-down-tray">Import starten</x-filament::button>
<x-filament::button color="gray" wire:click="discard" type="button">Verwerfen</x-filament::button>
</div>
</form>
@else
@php($stats = $import->stats ?? [])
<x-filament::section :heading="$import->status === 'running' ? 'Import läuft …' : ($import->status === 'done' ? 'Import abgeschlossen' : 'Import abgebrochen')">
<div @if ($import->status === 'running') wire:poll.750ms="step" @endif class="grid gap-4">
<div class="h-2 overflow-hidden rounded-full bg-gray-100 dark:bg-white/10">
<div class="h-full bg-primary-600 transition-all" style="width: {{ $import->progress() }}%"></div>
</div>
<p class="text-sm">
{{ $stats['processed'] ?? 0 }} von {{ $stats['total'] ?? 0 }} Einträgen ·
{{ $stats['created'] ?? 0 }} neu · {{ $stats['updated'] ?? 0 }} aktualisiert ·
{{ $stats['skipped'] ?? 0 }} übersprungen · {{ $stats['failed'] ?? 0 }} Fehler
</p>
@if ($import->status === 'running')
<p class="text-sm text-gray-500">Bitte die Seite geöffnet lassen – der Import läuft in Portionen weiter.</p>
<div><x-filament::button color="gray" wire:click="cancel" size="sm">Abbrechen</x-filament::button></div>
@else
<div class="flex gap-3">
<x-filament::button tag="a" href="/admin/neuigkeiten" icon="heroicon-o-newspaper">Zu den Neuigkeiten</x-filament::button>
<x-filament::button color="gray" wire:click="discard">Neuer Import</x-filament::button>
</div>
@endif
</div>
</x-filament::section>
@if ($import->log)
<x-filament::section heading="Protokoll" collapsible>
<pre class="max-h-96 overflow-y-auto text-xs whitespace-pre-wrap">{{ $import->log }}</pre>
</x-filament::section>
@endif
@endif
</x-filament-panels::page>

View file

@ -0,0 +1,85 @@
<?php
namespace Inhaus\Plugins\WordpressImport;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Inhaus\Plugins\WordpressImport\Models\WpImport;
/**
* Erster Schritt: Exportdatei einlesen und in die Zwischenablage schreiben.
* Danach zeigt die Admin-Seite, was gefunden wurde, und fragt die Optionen ab.
*/
class Analyzer
{
public function __construct(private readonly WxrReader $reader) {}
public function analyze(string $file, User $user): WpImport
{
@set_time_limit(300);
$import = WpImport::query()->create(['user_id' => $user->id, 'file' => $file, 'status' => 'analyzing']);
$buffer = [];
$counts = ['post' => 0, 'page' => 0, 'attachment' => 0, 'category' => 0, 'author' => 0, 'other' => 0, 'drafts' => 0];
$flush = function () use (&$buffer) {
if ($buffer !== []) {
DB::table('wp_import_items')->insert($buffer);
$buffer = [];
}
};
try {
$this->reader->read($file, function (string $kind, array $data) use ($import, &$buffer, &$counts, $flush) {
if ($kind === 'site') {
$import->forceFill(['site_title' => $data['title'], 'site_url' => $data['url']]);
return;
}
$type = $kind === 'item' ? $data['type'] : $kind;
if ($kind === 'item' && ! in_array($type, ['post', 'page', 'attachment'], true)) {
$counts['other']++;
return;
}
if ($kind === 'item' && in_array($data['status'], ['auto-draft', 'inherit', 'trash'], true) && $type !== 'attachment') {
return;
}
$counts[$type]++;
if (in_array($type, ['post', 'page'], true) && in_array($data['status'], ['draft', 'pending'], true)) {
$counts['drafts']++;
}
$buffer[] = [
'import_id' => $import->id,
'type' => $type,
'wp_id' => (int) ($data['wp_id'] ?? 0),
'wp_parent' => (int) ($data['parent'] ?? 0),
// Anhänge werden nicht importiert, nur ihre Adressen gebraucht (Beitragsbilder).
'status' => $type === 'attachment' ? 'skipped' : 'pending',
'data' => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
];
if (count($buffer) >= 100) {
$flush();
}
});
$flush();
} catch (\Throwable $e) {
$import->items()->delete();
$import->delete();
throw $e;
}
$import->forceFill(['status' => 'analyzed', 'stats' => ['found' => $counts]])->save();
return $import;
}
}

View file

@ -0,0 +1,179 @@
<?php
namespace Inhaus\Plugins\WordpressImport;
use DOMDocument;
use DOMElement;
use DOMXPath;
/**
* Wandelt WordPress-Inhalte (klassischer Editor oder Gutenberg) in schlichtes
* HTML für das Portal: Absätze, Bildunterschriften, Galerien, Shortcodes und
* Bilder (auf Wunsch ins Portal kopiert). Bereinigt wird danach wie immer.
*/
class ContentConverter
{
private const BLOCK_TAGS = 'p|div|h[1-6]|ul|ol|li|table|thead|tbody|tr|td|th|blockquote|figure|figcaption|pre|hr|iframe|section|dl|dt|dd|address|form|video|audio';
/**
* @param callable(string): ?string $image alte Bildadresse => neue (null = Bild weglassen)
* @param array<int, string> $attachments Anhang-ID => Adresse (für [gallery])
*/
public function convert(string $content, callable $image, array $attachments = []): string
{
$html = str_replace(["\r\n", "\r"], "\n", $content);
$gutenberg = str_contains($html, '<!-- wp:');
// Skripte und Stile samt Inhalt entfernen – sie sollen auch nicht als Text übrig bleiben.
$html = preg_replace('#<(script|style|noscript)\b[^>]*>.*?</\1>#is', '', $html) ?? $html;
// Gutenberg-Markierungen entfernen, der HTML-Inhalt bleibt.
$html = preg_replace('/<!--\s*\/?wp:.*?-->/s', '', $html) ?? $html;
$html = $this->shortcodes($html, $attachments);
if (! $gutenberg) {
$html = $this->autop($html);
}
return $this->rewriteImages($html, $image);
}
/**
* Kurzer Anreißer aus Auszug oder Text.
*/
public function teaser(string $excerpt, string $html, int $length = 280): string
{
$text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags($excerpt !== '' ? $excerpt : $html), ENT_QUOTES)) ?? '');
if (mb_strlen($text) <= $length) {
return $text;
}
$cut = mb_substr($text, 0, $length);
return rtrim(mb_substr($cut, 0, (int) (mb_strrpos($cut, ' ') ?: $length)), ' ,.;:–-').' …';
}
/**
* Vereinfachtes wpautop(): Leerzeilen trennen Absätze, einfache Umbrüche werden <br>.
*/
private function autop(string $html): string
{
$chunks = preg_split('/\n\s*\n/', trim($html)) ?: [];
return implode("\n", array_map(function (string $chunk) {
$chunk = trim($chunk);
if ($chunk === '') {
return '';
}
return preg_match('/^<('.self::BLOCK_TAGS.')\b/i', $chunk) ? $chunk : '<p>'.nl2br($chunk, false).'</p>';
}, $chunks));
}
/**
* @param array<int, string> $attachments
*/
private function shortcodes(string $html, array $attachments): string
{
// [caption]<img …> Text[/caption] → Bild und Unterschrift als eigener Absatz
$html = preg_replace_callback('/\[caption[^\]]*\](.*?)\[\/caption\]/is', function ($m) {
$inner = trim($m[1]);
preg_match('/(<a[^>]*>\s*)?<img[^>]*>(\s*<\/a>)?/is', $inner, $img);
$caption = trim(strip_tags(str_replace($img[0] ?? '', '', $inner)));
return "\n\n".($img[0] ?? '')."\n\n".($caption !== '' ? '<p><em>'.e($caption).'</em></p>' : '')."\n\n";
}, $html) ?? $html;
// [gallery ids="1,2,3"] → Bilder untereinander
$html = preg_replace_callback('/\[gallery[^\]]*\]/i', function ($m) use ($attachments) {
if (! preg_match('/ids=["\']?([\d,\s]+)/', $m[0], $ids)) {
return '';
}
$images = array_filter(array_map(fn ($id) => $attachments[(int) trim($id)] ?? null, explode(',', $ids[1])));
return "\n\n".implode("\n\n", array_map(fn ($url) => '<p><img src="'.e($url).'" alt=""></p>', $images))."\n\n";
}, $html) ?? $html;
// [embed]https://…[/embed] und alleinstehende Video-Links → Link
$html = preg_replace('/\[embed[^\]]*\](.*?)\[\/embed\]/is', "\n\n<p><a href=\"$1\">$1</a></p>\n\n", $html) ?? $html;
$html = preg_replace('/^\s*(https?:\/\/(www\.)?(youtube\.com|youtu\.be|vimeo\.com)\/\S+)\s*$/mi', '<p><a href="$1">$1</a></p>', $html) ?? $html;
// Übrige Shortcodes: Klammern entfernen, eingeschlossenen Text behalten.
return preg_replace('/\[\/?[a-z][a-z0-9_-]*(?:\s[^\]]*)?\]/i', '', $html) ?? $html;
}
/**
* @param callable(string): ?string $image
*/
private function rewriteImages(string $html, callable $image): string
{
if (! str_contains($html, '<img') && ! str_contains($html, '<figure')) {
return $html;
}
$dom = new DOMDocument;
@$dom->loadHTML('<?xml encoding="utf-8"?><div id="wp-root">'.$html.'</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NONET);
$xpath = new DOMXPath($dom);
// Gutenberg-Bilder: <figure><img><figcaption>…</figcaption></figure> → Bild + Unterschrift als Absatz
foreach (iterator_to_array($xpath->query('//figure')) as $figure) {
/** @var DOMElement $figure */
$caption = $xpath->query('.//figcaption', $figure)->item(0);
$paragraph = null;
if ($caption) {
$paragraph = $dom->createElement('p');
$em = $dom->createElement('em');
$em->appendChild($dom->createTextNode(trim($caption->textContent)));
$paragraph->appendChild($em);
$caption->parentNode->removeChild($caption);
}
while ($figure->firstChild) {
$figure->parentNode->insertBefore($figure->firstChild, $figure);
}
if ($paragraph) {
$figure->parentNode->insertBefore($paragraph, $figure);
}
$figure->parentNode->removeChild($figure);
}
foreach (iterator_to_array($xpath->query('//img')) as $img) {
/** @var DOMElement $img */
$src = $img->getAttribute('src');
$new = $src !== '' ? $image($src) : null;
// Verlinkung auf das Originalbild der alten Website entfernen.
$link = $img->parentNode;
if ($link instanceof DOMElement && $link->nodeName === 'a' && preg_match('/\.(jpe?g|png|gif|webp)(\?.*)?$/i', $link->getAttribute('href'))) {
$link->parentNode->replaceChild($img, $link);
}
if ($new === null) {
$img->parentNode->removeChild($img);
continue;
}
foreach (['srcset', 'sizes', 'class', 'width', 'height', 'style', 'loading', 'decoding'] as $attribute) {
$img->removeAttribute($attribute);
}
$img->setAttribute('src', $new);
}
$root = $dom->getElementById('wp-root');
$out = '';
foreach ($root->childNodes as $child) {
$out .= $dom->saveHTML($child);
}
return $out;
}
}

View file

@ -0,0 +1,226 @@
<?php
namespace Inhaus\Plugins\WordpressImport\Filament\Pages;
use App\Models\User;
use BackedEnum;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Inhaus\Plugins\News\Models\NewsCategory;
use Inhaus\Plugins\Pages\PageTree;
use Inhaus\Plugins\WordpressImport\Analyzer;
use Inhaus\Plugins\WordpressImport\Importer;
use Inhaus\Plugins\WordpressImport\Models\WpImport;
use Throwable;
use UnitEnum;
/**
* Umstieg von WordPress: Exportdatei hochladen, prüfen, Optionen wählen, importieren.
*/
class WordpressImport extends Page
{
protected string $view = 'wordpress-import::import';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedArrowDownTray;
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
protected static ?int $navigationSort = 20;
protected static ?string $navigationLabel = 'WordPress-Import';
protected static ?string $title = 'WordPress-Import';
protected static ?string $slug = 'wordpress-import';
public ?int $importId = null;
/** @var array<string, mixed>|null */
public ?array $upload = [];
/** @var array<string, mixed>|null */
public ?array $options = [];
public static function canAccess(): bool
{
return auth()->user()?->can('news.manage') ?? false;
}
public function mount(): void
{
// Laufenden oder zuletzt geprüften Import fortsetzen.
$this->importId = WpImport::query()->whereIn('status', ['analyzed', 'running'])->latest('id')->value('id');
$this->uploadForm->fill();
$this->fillOptions();
}
public function getImport(): ?WpImport
{
return $this->importId ? WpImport::query()->find($this->importId) : null;
}
public function uploadForm(Schema $schema): Schema
{
return $schema->statePath('upload')->components([
Section::make('Exportdatei hochladen')
->description('In WordPress unter „Werkzeuge → Daten exportieren“ „Alle Inhalte“ wählen und die XML-Datei hier hochladen. Bilder werden anschließend direkt von der alten Website geladen – sie muss also noch erreichbar sein.')
->schema([
FileUpload::make('file')
->hiddenLabel()
->disk('local')
->directory('wp-import')
->acceptedFileTypes(['text/xml', 'application/xml', 'application/rss+xml'])
->maxSize(256 * 1024)
->required(),
]),
]);
}
public function optionsForm(Schema $schema): Schema
{
$import = $this->getImport();
$categories = $import ? $import->items()->where('type', 'category')->get()->map(fn ($item) => $item->data) : collect();
$authors = $import ? $import->items()->where('type', 'author')->get()->map(fn ($item) => $item->data) : collect();
$existing = NewsCategory::query()->orderBy('name')->pluck('name', 'id')->all();
return $schema->statePath('options')->components([
Section::make('Was übernommen wird')
->columns(2)
->schema([
Toggle::make('include_drafts')->label('Auch Entwürfe übernehmen')->helperText('Veröffentlichte und geplante Beiträge werden immer übernommen.'),
Toggle::make('download_images')->label('Bilder ins Portal kopieren')->helperText('Beitragsbilder und Bilder im Text. Sonst bleiben Bilder auf der alten Website verlinkt.'),
Toggle::make('import_pages')->label('WordPress-Seiten als Seiten übernehmen')->visible(Importer::pagesAvailable())->live(),
Toggle::make('publish_pages')->label('Seiten gleich veröffentlichen')->helperText('Sonst als Entwurf zum Durchsehen.')->visible(fn ($get) => Importer::pagesAvailable() && $get('import_pages')),
Select::make('pages_parent')->label('Seiten unterhalb von')->placeholder('– oberste Ebene –')
->options(fn () => Importer::pagesAvailable() ? app(PageTree::class)->options() : [])
->visible(fn ($get) => Importer::pagesAvailable() && $get('import_pages')),
Toggle::make('update_existing')->label('Bereits importierte Einträge aktualisieren')->helperText('Sonst werden sie bei einem erneuten Import übersprungen.'),
]),
Section::make('Kategorien')
->description('Beiträge haben im Portal eine Kategorie – bei mehreren gilt die erste.')
->columns(2)
->visible($categories->isNotEmpty())
->schema([
...$categories->map(fn (array $c) => Select::make('categories.'.$c['slug'])
->label($c['name'])
->options(['auto' => 'Übernehmen (neu anlegen oder gleichnamige nutzen)', 'skip' => 'Nicht übernehmen'] + $existing)
->native(false)
->required())->all(),
Select::make('default_category')->label('Kategorie für Beiträge ohne Kategorie')->options($existing)->placeholder('Ohne Kategorie'),
]),
Section::make('Autorinnen und Autoren')
->description('Zuordnung über die E-Mail-Adresse. Wer im Portal nicht gefunden wird, erscheint als unten gewählte Person.')
->columns(2)
->schema([
...$authors->map(fn (array $a) => Select::make('authors.'.$a['login'])
->label($a['name'].' ('.$a['email'].')')
->placeholder(User::query()->where('email', $a['email'])->exists() ? 'Gefunden über die E-Mail-Adresse' : 'Nicht gefunden – Ersatz verwenden')
->searchable()
->getSearchResultsUsing(fn (string $search) => User::query()->where('name', 'like', "%{$search}%")->orWhere('email', 'like', "%{$search}%")->limit(20)->pluck('name', 'id')->all())
->getOptionLabelUsing(fn ($value) => User::query()->find($value)?->name))->all(),
Select::make('fallback_author')->label('Ersatz')
->searchable()
->getSearchResultsUsing(fn (string $search) => User::query()->where('name', 'like', "%{$search}%")->orWhere('email', 'like', "%{$search}%")->limit(20)->pluck('name', 'id')->all())
->getOptionLabelUsing(fn ($value) => User::query()->find($value)?->name)
->required(),
]),
]);
}
protected function getForms(): array
{
return ['uploadForm', 'optionsForm'];
}
public function analyze(Analyzer $analyzer): void
{
$state = $this->uploadForm->getState();
$file = is_array($state['file']) ? reset($state['file']) : $state['file'];
try {
$import = $analyzer->analyze(Storage::disk('local')->path($file), auth()->user());
$import->update(['file' => $file]);
// Neu laden: Die Optionen hängen von den gefundenen Kategorien und Personen ab.
$this->redirect(static::getUrl());
} catch (Throwable $e) {
Storage::disk('local')->delete($file);
Notification::make()->danger()->title('Datei konnte nicht gelesen werden')->body($e->getMessage())->persistent()->send();
}
}
public function start(Importer $importer): void
{
$import = $this->getImport();
abort_unless($import?->status === 'analyzed', 404);
$options = $this->optionsForm->getState();
$options['categories'] = array_filter((array) ($options['categories'] ?? []));
$options['authors'] = array_filter((array) ($options['authors'] ?? []));
$importer->start($import, $options);
}
/**
* Wird von der Seite im Sekundentakt aufgerufen, solange der Import läuft.
*/
public function step(Importer $importer): void
{
$import = $this->getImport();
if ($import?->status === 'running' && $importer->step($import)) {
Notification::make()->success()->title('Import abgeschlossen')->send();
}
}
public function discard(): void
{
$import = $this->getImport();
if ($import && $import->status !== 'running') {
Storage::disk('local')->delete($import->file);
$import->status === 'analyzed' ? $import->delete() : null;
}
$this->importId = null;
$this->uploadForm->fill();
}
public function cancel(): void
{
$import = $this->getImport();
$import?->forceFill(['status' => 'failed'])->save();
$import?->addLog('Abgebrochen.');
$import?->save();
}
/**
* @return Collection<int, WpImport>
*/
public function history()
{
return WpImport::query()->whereIn('status', ['done', 'failed'])->latest('id')->limit(10)->get();
}
private function fillOptions(): void
{
$import = $this->getImport();
$this->optionsForm->fill([
'include_drafts' => false,
'download_images' => true,
'import_pages' => false,
'publish_pages' => true,
'update_existing' => false,
'fallback_author' => auth()->id(),
'categories' => $import ? $import->items()->where('type', 'category')->get()->mapWithKeys(fn ($item) => [$item->data['slug'] => 'auto'])->all() : [],
]);
}
}

View file

@ -0,0 +1,409 @@
<?php
namespace Inhaus\Plugins\WordpressImport;
use App\Models\User;
use App\Pagebuilder\Content;
use App\Plugins\PluginManager;
use App\Support\Audit;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inhaus\Plugins\News\Models\NewsCategory;
use Inhaus\Plugins\News\Models\NewsPost;
use Inhaus\Plugins\Pages\Models\Page;
use Inhaus\Plugins\Pages\PageTree;
use Inhaus\Plugins\WordpressImport\Models\WpImport;
use Inhaus\Plugins\WordpressImport\Models\WpImportItem;
use Throwable;
/**
* Übernimmt die Einträge der Zwischenablage in Portionen: erst Kategorien,
* dann Beiträge, dann Seiten (Eltern vor Kindern). Jeder Aufruf arbeitet
* höchstens bis zur Frist und macht beim nächsten weiter – so passt der
* Import auch in die Laufzeitgrenzen von Shared Hosting.
*/
class Importer
{
/** @var array<string, User|null> */
private array $authors = [];
/** @var array<int, string>|null */
private ?array $attachments = null;
public function __construct(
private readonly ContentConverter $converter,
private readonly MediaDownloader $media,
) {}
public static function pagesAvailable(): bool
{
return app(PluginManager::class)->isLoaded('pages');
}
/**
* @param array<string, mixed> $options
*/
public function start(WpImport $import, array $options): void
{
$types = ['category', 'post', ...(($options['import_pages'] ?? false) && self::pagesAvailable() ? ['page'] : [])];
$import->items()->whereIn('type', ['post', 'page', 'category'])->whereNotIn('type', $types)->update(['status' => 'skipped', 'message' => 'Nicht ausgewählt']);
$import->forceFill([
'status' => 'running',
'options' => $options,
'stats' => [
...($import->stats ?? []),
'total' => $import->items()->whereIn('type', $types)->where('status', 'pending')->count(),
'processed' => 0,
'created' => 0,
'updated' => 0,
'skipped' => 0,
'failed' => 0,
],
])->save();
}
/**
* @return bool true = fertig
*/
public function step(WpImport $import, float $seconds = 8.0): bool
{
if ($import->status !== 'running') {
return true;
}
@set_time_limit((int) ceil($seconds) + 30);
$deadline = microtime(true) + $seconds;
foreach (['category', 'post', 'page'] as $type) {
while (microtime(true) < $deadline) {
$items = $type === 'page' ? $this->nextPages($import) : $import->items()->where('type', $type)->where('status', 'pending')->orderBy('id')->limit(10)->get();
if ($items->isEmpty()) {
break;
}
foreach ($items as $item) {
$this->process($import, $item);
if (microtime(true) >= $deadline) {
break;
}
}
}
if ($import->items()->where('type', $type)->where('status', 'pending')->exists()) {
$import->save();
return false;
}
}
$this->finish($import);
return true;
}
private function finish(WpImport $import): void
{
$import->status = 'done';
$import->addLog('Import abgeschlossen.');
$import->save();
if (self::pagesAvailable()) {
PageTree::flush(true);
}
// Die hochgeladene Exportdatei wird nicht mehr gebraucht.
Storage::disk('local')->delete($import->file);
Audit::log('wordpress.imported', ['import' => $import->id, 'stats' => $import->stats], $import->user_id);
}
private function process(WpImport $import, WpImportItem $item): void
{
try {
[$result, $message] = match ($item->type) {
'category' => $this->category($import, $item->data),
'post' => $this->post($import, $item->data),
'page' => $this->page($import, $item->data),
};
} catch (Throwable $e) {
report($e);
[$result, $message] = ['failed', $e->getMessage()];
}
$item->forceFill(['status' => $result === 'failed' ? 'failed' : ($result === 'skipped' ? 'skipped' : 'done'), 'message' => $message ? mb_substr($message, 0, 500) : null])->save();
$stats = $import->stats;
$stats['processed'] = ($stats['processed'] ?? 0) + 1;
$stats[$result] = ($stats[$result] ?? 0) + 1;
$import->stats = $stats;
if ($message && in_array($result, ['failed', 'skipped'], true) && $item->type !== 'category') {
$import->addLog(($result === 'failed' ? 'Fehler' : 'Übersprungen').': „'.($item->data['title'] ?? $item->wp_id).'“ – '.$message);
}
}
/**
* @param array<string, mixed> $data
* @return array{0: string, 1: string|null}
*/
private function category(WpImport $import, array $data): array
{
$choice = $import->option('categories', [])[$data['slug']] ?? 'auto';
if ($choice === 'skip') {
return ['skipped', null];
}
if (is_numeric($choice) && NewsCategory::query()->whereKey($choice)->exists()) {
$this->ref($import, 'category', $data['slug'], 'news_category', (string) $choice);
return ['updated', null];
}
$slug = Str::slug($data['slug'] ?: $data['name'], language: 'de') ?: 'kategorie';
$existing = NewsCategory::query()->where('slug', $slug)->orWhere('name', $data['name'])->first();
if ($existing) {
$this->ref($import, 'category', $data['slug'], 'news_category', (string) $existing->id);
return ['updated', null];
}
$category = NewsCategory::query()->create([
'name' => mb_substr($data['name'] ?: $slug, 0, 60),
'slug' => $slug,
'sort' => (int) NewsCategory::query()->max('sort') + 1,
]);
$this->ref($import, 'category', $data['slug'], 'news_category', (string) $category->id);
return ['created', null];
}
/**
* @param array<string, mixed> $data
* @return array{0: string, 1: string|null}
*/
private function post(WpImport $import, array $data): array
{
if ($reason = $this->statusProblem($import, $data['status'])) {
return ['skipped', $reason];
}
$existingId = $this->lookup($import, 'post', (string) $data['wp_id']);
$post = $existingId ? NewsPost::query()->find($existingId) : null;
if ($post && ! $import->option('update_existing', false)) {
return ['skipped', 'bereits importiert'];
}
$post ??= new NewsPost;
$html = $this->html($import, $data['content'], 'news/inline');
$post->fill([
'title' => mb_substr($data['title'] !== '' ? $data['title'] : 'Ohne Titel', 0, 160),
'teaser' => mb_substr($this->converter->teaser($data['excerpt'], $html), 0, 300) ?: null,
'body' => $html,
'category_id' => $this->categoryFor($import, $data['categories']),
]);
$post->author_id = $this->author($import, $data['creator'])?->id;
if (! $post->exists) {
$slug = Str::slug(rawurldecode($data['slug']), language: 'de');
$post->slug = $slug !== '' && ! NewsPost::query()->where('slug', $slug)->exists() ? $slug : NewsPost::uniqueSlug($post->title);
}
[$status, $publishedAt] = $this->statusFor($data);
$post->published_at = $publishedAt;
$post->status = $status;
if ($import->option('download_images', true) && $data['thumbnail_id'] && ($url = $this->attachmentUrl($import, (int) $data['thumbnail_id']))) {
$post->cover_path = $this->media->cover($import, $url) ?? $post->cover_path;
}
$created = ! $post->exists;
$post->save();
// save() leitet den Status aus published_at ab – Freigabe-Status erhalten.
if ($status === NewsPost::PENDING) {
$post->forceFill(['status' => NewsPost::PENDING, 'submitted_at' => now()])->saveQuietly();
}
$this->ref($import, 'post', (string) $data['wp_id'], 'news_post', (string) $post->id);
return [$created ? 'created' : 'updated', null];
}
/**
* @param array<string, mixed> $data
* @return array{0: string, 1: string|null}
*/
private function page(WpImport $import, array $data): array
{
if ($reason = $this->statusProblem($import, $data['status'])) {
return ['skipped', $reason];
}
$existingId = $this->lookup($import, 'page', (string) $data['wp_id']);
$page = $existingId ? Page::query()->find($existingId) : null;
if ($page && ! $import->option('update_existing', false)) {
return ['skipped', 'bereits importiert'];
}
$title = mb_substr($data['title'] !== '' ? $data['title'] : 'Ohne Titel', 0, 200);
$html = $this->html($import, $data['content'], 'pagebuilder/imported');
$content = app(Content::class)->sanitize(['blocks' => $html === '' ? [] : [['type' => 'text', 'data' => ['html' => $html]]]]);
$user = $this->author($import, $data['creator']);
$created = $page === null;
if (! $page) {
$parentId = $data['parent'] ? $this->lookup($import, 'page', (string) $data['parent']) : null;
$page = Page::query()->create([
'title' => $title,
'slug' => Str::slug(rawurldecode($data['slug']), language: 'de') ?: null,
'parent_id' => $parentId ? (int) $parentId : ($import->option('pages_parent') ?: null),
'sort' => (int) $data['menu_order'],
'created_by' => $user?->id,
]);
}
if ($data['status'] === 'publish' && $import->option('publish_pages', true)) {
$page->publish($title, $content, $user, 'imported');
} else {
$page->forceFill(['draft_title' => $title, 'draft' => $content, 'draft_updated_at' => now(), 'draft_updated_by' => $user?->id])->save();
}
$this->ref($import, 'page', (string) $data['wp_id'], 'page', (string) $page->id);
return [$created ? 'created' : 'updated', null];
}
/**
* Seiten in einer Reihenfolge, in der übergeordnete Seiten zuerst kommen.
*
* @return Collection<int, WpImportItem>
*/
private function nextPages(WpImport $import)
{
$pending = $import->items()->where('type', 'page')->where('status', 'pending')->get(['id', 'wp_id', 'wp_parent']);
if ($pending->isEmpty()) {
return collect();
}
$pendingIds = $pending->pluck('wp_id')->all();
$ready = $pending->filter(fn ($item) => $item->wp_parent === 0 || ! in_array($item->wp_parent, $pendingIds, true))->take(10);
// Zirkelbezug (sollte nicht vorkommen): dann eben ohne Reihenfolge.
$ids = ($ready->isNotEmpty() ? $ready : $pending->take(10))->pluck('id');
return WpImportItem::query()->whereIn('id', $ids)->orderBy('id')->get();
}
private function statusProblem(WpImport $import, string $status): ?string
{
return match ($status) {
'publish', 'future' => null,
'draft', 'pending' => $import->option('include_drafts', false) ? null : 'Entwurf (nicht ausgewählt)',
'private' => 'privater Eintrag',
default => 'Status „'.$status.'“',
};
}
/**
* @param array<string, mixed> $data
* @return array{0: string, 1: Carbon|null}
*/
private function statusFor(array $data): array
{
$gmt = $data['date_gmt'] && ! str_starts_with($data['date_gmt'], '0000') ? Carbon::parse($data['date_gmt'], 'UTC') : null;
$date = $gmt ?? ($data['date'] && ! str_starts_with($data['date'], '0000') ? Carbon::parse($data['date']) : now());
return match ($data['status']) {
'publish', 'future' => [NewsPost::PUBLISHED, $date],
'pending' => [NewsPost::PENDING, null],
default => [NewsPost::DRAFT, null],
};
}
private function html(WpImport $import, string $content, string $directory): string
{
$download = (bool) $import->option('download_images', true);
return $this->converter->convert($content, function (string $src) use ($import, $download, $directory) {
if (! $download) {
return $src;
}
// Bilder der alten Website übernehmen; fremde Bilder weglassen, wenn sie nicht ladbar sind.
return $this->media->inline($import, $src, $directory);
}, $this->attachments($import));
}
/**
* @param list<array{slug: string, name: string}> $categories
*/
private function categoryFor(WpImport $import, array $categories): ?int
{
foreach ($categories as $category) {
if ($id = $this->lookup($import, 'category', $category['slug'])) {
return (int) $id;
}
}
$fallback = $import->option('default_category');
return $fallback ? (int) $fallback : null;
}
private function author(WpImport $import, string $login): ?User
{
if (array_key_exists($login, $this->authors)) {
return $this->authors[$login];
}
$mapped = $import->option('authors', [])[$login] ?? null;
$email = $import->items()->where('type', 'author')->get()->first(fn ($a) => $a->data['login'] === $login)?->data['email'];
$user = ($mapped ? User::query()->find($mapped) : null)
?? ($email ? User::query()->where('email', $email)->first() : null)
?? User::query()->find($import->option('fallback_author', $import->user_id));
return $this->authors[$login] = $user;
}
/**
* @return array<int, string>
*/
private function attachments(WpImport $import): array
{
return $this->attachments ??= $import->items()->where('type', 'attachment')->get(['wp_id', 'data'])
->mapWithKeys(fn ($item) => [(int) $item->wp_id => (string) ($item->data['attachment_url'] ?? '')])
->filter()
->all();
}
private function attachmentUrl(WpImport $import, int $id): ?string
{
return $this->attachments($import)[$id] ?? null;
}
private function lookup(WpImport $import, string $type, string $key): ?string
{
return DB::table('wp_import_refs')->where('source', $import->source())->where('type', $type)->where('wp_key', $key)->value('local_value');
}
private function ref(WpImport $import, string $type, string $key, string $localType, string $value): void
{
DB::table('wp_import_refs')->updateOrInsert(
['source' => $import->source(), 'type' => $type, 'wp_key' => mb_substr($key, 0, 191)],
['local_type' => $localType, 'local_value' => $value, 'updated_at' => now(), 'created_at' => now()],
);
}
}

View file

@ -0,0 +1,114 @@
<?php
namespace Inhaus\Plugins\WordpressImport;
use App\Support\Images;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inhaus\Plugins\WordpressImport\Models\WpImport;
use Throwable;
/**
* Lädt Bilder der alten Website herunter und legt sie im Portal ab.
* Jede Adresse wird nur einmal geladen – auch über mehrere Importläufe hinweg.
*/
class MediaDownloader
{
public const MAX_BYTES = 15 * 1024 * 1024;
public function __construct(private readonly Images $images) {}
/**
* Titelbild: Originaldatei in „news/“ (Varianten erzeugt das Beitragsmodell).
*/
public function cover(WpImport $import, string $url): ?string
{
return $this->remember($import, 'cover', $url, function (string $tmp, string $extension) {
$path = 'news/wp-'.Str::random(24).'.'.$extension;
Storage::disk('uploads')->put($path, (string) file_get_contents($tmp));
return $path;
});
}
/**
* Bild im Text: verkleinert als WebP, liefert die neue Adresse.
*/
public function inline(WpImport $import, string $url, string $directory = 'news/inline'): ?string
{
$path = $this->remember($import, 'inline:'.$directory, $url, fn (string $tmp, string $extension, string $mime) => $this->images->storeContentImage(
new UploadedFile($tmp, 'bild.'.$extension, $mime, null, true),
$directory,
));
return $path ? Storage::disk('uploads')->url($path) : null;
}
/**
* @param callable(string $tmp, string $extension, string $mime): string $store
*/
private function remember(WpImport $import, string $kind, string $url, callable $store): ?string
{
$url = $this->absolute($import, $url);
if ($url === null) {
return null;
}
$key = $kind.':'.sha1($url);
$known = DB::table('wp_import_refs')->where('source', $import->source())->where('type', 'media')->where('wp_key', $key)->value('local_value');
if ($known && Storage::disk('uploads')->exists($known)) {
return $known;
}
$tmp = tempnam(sys_get_temp_dir(), 'wpimg');
try {
$response = Http::timeout(20)->connectTimeout(10)->get($url);
$mime = strtolower(explode(';', (string) $response->header('Content-Type'))[0]);
$extension = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp'][$mime] ?? null;
$body = $response->successful() ? $response->body() : '';
if (! $extension || $body === '' || strlen($body) > self::MAX_BYTES) {
return null;
}
file_put_contents($tmp, $body);
unset($body);
if (@getimagesize($tmp) === false) {
return null;
}
$path = $store($tmp, $extension, $mime);
DB::table('wp_import_refs')->updateOrInsert(
['source' => $import->source(), 'type' => 'media', 'wp_key' => $key],
['local_type' => 'upload', 'local_value' => $path, 'updated_at' => now(), 'created_at' => now()],
);
return $path;
} catch (Throwable) {
return null;
} finally {
@unlink($tmp);
}
}
private function absolute(WpImport $import, string $url): ?string
{
$url = html_entity_decode(trim($url));
if (str_starts_with($url, '//')) {
$url = 'https:'.$url;
} elseif (str_starts_with($url, '/') && $import->site_url) {
$url = rtrim($import->site_url, '/').$url;
}
return preg_match('#^https?://#i', $url) ? $url : null;
}
}

View file

@ -0,0 +1,49 @@
<?php
namespace Inhaus\Plugins\WordpressImport\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['user_id', 'file', 'site_title', 'site_url', 'status', 'options', 'stats', 'log'])]
class WpImport extends Model
{
protected function casts(): array
{
return ['options' => 'array', 'stats' => 'array'];
}
/**
* @return HasMany<WpImportItem, $this>
*/
public function items(): HasMany
{
return $this->hasMany(WpImportItem::class, 'import_id');
}
/** Kennung der Quelle für wp_import_refs. */
public function source(): string
{
return mb_substr((string) (parse_url((string) $this->site_url, PHP_URL_HOST) ?: $this->site_url ?: 'wordpress'), 0, 191);
}
public function option(string $key, mixed $default = null): mixed
{
return $this->options[$key] ?? $default;
}
public function addLog(string $line): void
{
$lines = array_slice(array_filter(explode("\n", (string) $this->log)), -499);
$lines[] = $line;
$this->log = implode("\n", $lines);
}
public function progress(): int
{
$total = (int) ($this->stats['total'] ?? 0);
return $total === 0 ? 100 : (int) floor(100 * (int) ($this->stats['processed'] ?? 0) / $total);
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace Inhaus\Plugins\WordpressImport\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
#[Fillable(['import_id', 'type', 'wp_id', 'wp_parent', 'status', 'data', 'message'])]
class WpImportItem extends Model
{
public $timestamps = false;
protected function casts(): array
{
return ['data' => 'array'];
}
}

View file

@ -0,0 +1,12 @@
<?php
namespace Inhaus\Plugins\WordpressImport;
use App\Plugins\Plugin;
/**
* Umstieg von WordPress: Die Admin-Seite „WordPress-Import“ liegt unter
* src/Filament/Pages und wird vom Kern gefunden. Nach dem Umstieg kann das
* Plugin deaktiviert werden.
*/
class WordpressImportPlugin extends Plugin {}

View file

@ -0,0 +1,189 @@
<?php
namespace Inhaus\Plugins\WordpressImport;
use RuntimeException;
use SimpleXMLElement;
use XMLReader;
/**
* Liest eine WordPress-Exportdatei (WXR, „Werkzeuge → Daten exportieren“)
* Eintrag für Eintrag – auch große Dateien brauchen kaum Arbeitsspeicher.
*/
class WxrReader
{
/** @var array<string, string> Präfix => URI */
private array $namespaces = [];
private const NS = [
'wp' => ['http://wordpress.org/export/1.2/', 'http://wordpress.org/export/1.1/', 'http://wordpress.org/export/1.0/'],
'content' => ['http://purl.org/rss/1.0/modules/content/'],
'excerpt' => ['http://wordpress.org/export/1.2/excerpt/', 'http://wordpress.org/export/1.1/excerpt/', 'http://wordpress.org/export/1.0/excerpt/'],
'dc' => ['http://purl.org/dc/elements/1.1/'],
];
/**
* @param callable(string $type, array<string, mixed> $data): void $callback type: site, category, author, item
*/
public function read(string $file, callable $callback): void
{
$reader = new XMLReader;
if (! @$reader->open($file, null, LIBXML_NONET | LIBXML_COMPACT | LIBXML_PARSEHUGE)) {
throw new RuntimeException('Die Datei konnte nicht gelesen werden.');
}
$site = ['title' => null, 'url' => null, 'wxr' => false];
$sawChannel = false;
$this->namespaces = [];
try {
while (@$reader->read()) {
if ($reader->nodeType !== XMLReader::ELEMENT) {
continue;
}
$name = $reader->name;
if ($name === 'rss') {
// Namensräume des Wurzelelements merken (wp, content, excerpt, dc, wfw, …).
while ($reader->moveToNextAttribute()) {
if (str_starts_with($reader->name, 'xmlns:')) {
$this->namespaces[substr($reader->name, 6)] = $reader->value;
}
}
$reader->moveToElement();
} elseif ($name === 'channel') {
$sawChannel = true;
} elseif ($sawChannel && $reader->depth === 2 && $name === 'title' && $site['title'] === null) {
$site['title'] = trim($reader->readString());
} elseif ($name === 'wp:base_blog_url' || ($name === 'wp:base_site_url' && $site['url'] === null)) {
$site['url'] = trim($reader->readString());
} elseif ($name === 'wp:wxr_version') {
$site['wxr'] = true;
} elseif ($name === 'wp:category') {
$callback('category', $this->category($this->element($reader)));
} elseif ($name === 'wp:author') {
$callback('author', $this->author($this->element($reader)));
} elseif ($name === 'item') {
if (! $site['wxr']) {
throw new RuntimeException('Das ist keine WordPress-Exportdatei (WXR).');
}
$callback('item', $this->item($this->element($reader)));
$reader->next();
}
}
} finally {
$reader->close();
}
if (! $site['wxr']) {
throw new RuntimeException('Das ist keine WordPress-Exportdatei (WXR). Bitte in WordPress unter „Werkzeuge → Daten exportieren“ erzeugen.');
}
$callback('site', $site);
}
private function element(XMLReader $reader): SimpleXMLElement
{
// Einzelnes Element mit den Namensräumen des Wurzelelements neu aufbauen.
// Die WordPress-Versionen 1.0–1.2 werden dabei auf 1.2 vereinheitlicht.
$namespaces = $this->namespaces + ['wp' => '', 'content' => '', 'excerpt' => '', 'dc' => ''];
$namespaces['wp'] = self::NS['wp'][0];
$namespaces['excerpt'] = self::NS['excerpt'][0];
$namespaces['content'] = self::NS['content'][0];
$namespaces['dc'] = self::NS['dc'][0];
$declarations = implode(' ', array_map(fn ($prefix, $uri) => 'xmlns:'.$prefix.'="'.htmlspecialchars($uri, ENT_XML1).'"', array_keys($namespaces), $namespaces));
$xml = preg_replace('/\s+xmlns:[A-Za-z0-9_-]+="[^"]*"/', '', $reader->readOuterXml());
$element = @simplexml_load_string('<root '.$declarations.'>'.$xml.'</root>', SimpleXMLElement::class, LIBXML_NOCDATA | LIBXML_NONET | LIBXML_PARSEHUGE);
if ($element === false) {
throw new RuntimeException('Die Exportdatei enthält fehlerhaftes XML.');
}
// Erstes Kindelement, egal in welchem Namensraum (z. B. wp:author).
$first = $element->xpath('./*')[0] ?? null;
if ($first === null) {
throw new RuntimeException('Die Exportdatei enthält fehlerhaftes XML.');
}
return $first;
}
private function wp(SimpleXMLElement $e, string $name): string
{
return trim((string) $e->children(self::NS['wp'][0])->{$name});
}
/**
* @return array<string, mixed>
*/
private function category(SimpleXMLElement $e): array
{
return [
'wp_id' => (int) $this->wp($e, 'term_id'),
'slug' => $this->wp($e, 'category_nicename'),
'name' => html_entity_decode($this->wp($e, 'cat_name'), ENT_QUOTES),
'parent' => $this->wp($e, 'category_parent'),
];
}
/**
* @return array<string, mixed>
*/
private function author(SimpleXMLElement $e): array
{
return [
'wp_id' => (int) $this->wp($e, 'author_id'),
'login' => $this->wp($e, 'author_login'),
'email' => strtolower($this->wp($e, 'author_email')),
'name' => html_entity_decode($this->wp($e, 'author_display_name'), ENT_QUOTES),
];
}
/**
* @return array<string, mixed>
*/
private function item(SimpleXMLElement $e): array
{
$wp = $e->children(self::NS['wp'][0]);
$meta = [];
foreach ($wp->postmeta as $postmeta) {
$pm = $postmeta->children(self::NS['wp'][0]);
$meta[(string) $pm->meta_key] = (string) $pm->meta_value;
}
$categories = [];
foreach ($e->category as $category) {
if ((string) $category['domain'] === 'category') {
$categories[] = ['slug' => (string) $category['nicename'], 'name' => html_entity_decode((string) $category, ENT_QUOTES)];
}
}
return [
'wp_id' => (int) $wp->post_id,
'type' => (string) $wp->post_type,
'status' => (string) $wp->status,
'title' => html_entity_decode(trim((string) $e->title), ENT_QUOTES),
'slug' => (string) $wp->post_name,
'link' => trim((string) $e->link),
'creator' => trim((string) $e->children(self::NS['dc'][0])->creator),
'content' => (string) $e->children(self::NS['content'][0])->encoded,
'excerpt' => trim((string) $e->children(self::NS['excerpt'][0])->encoded),
'date_gmt' => (string) $wp->post_date_gmt,
'date' => (string) $wp->post_date,
'parent' => (int) $wp->post_parent,
'menu_order' => (int) $wp->menu_order,
'attachment_url' => (string) $wp->attachment_url,
'thumbnail_id' => (int) ($meta['_thumbnail_id'] ?? 0),
'categories' => $categories,
];
}
}