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,57 @@
<?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('forms', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug', 120)->unique();
$table->text('description')->nullable();
$table->json('fields');
$table->json('settings')->nullable();
$table->boolean('is_open')->default(true);
$table->timestamp('closes_at')->nullable();
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
});
Schema::create('form_submissions', function (Blueprint $table) {
$table->id();
$table->foreignId('form_id')->constrained('forms')->cascadeOnDelete();
// Bei anonymen Formularen leer; „nur einmal ausfüllen“ prüft dann user_hash.
$table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
$table->string('user_hash', 64)->nullable();
$table->json('data');
$table->timestamp('read_at')->nullable();
$table->timestamps();
$table->index(['form_id', 'created_at']);
$table->index(['form_id', 'user_hash']);
$table->index(['form_id', 'user_id']);
});
Schema::create('form_files', function (Blueprint $table) {
$table->id();
$table->foreignId('submission_id')->constrained('form_submissions')->cascadeOnDelete();
$table->string('field', 80);
$table->string('name');
$table->string('path');
$table->string('mime', 150)->nullable();
$table->unsignedBigInteger('size')->default(0);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('form_files');
Schema::dropIfExists('form_submissions');
Schema::dropIfExists('forms');
}
};

View file

@ -0,0 +1,13 @@
{
"slug": "forms",
"name": "Formulare",
"version": "1.0.0",
"description": "Formulare zusammenstellen – Anträge, Anmeldungen, Umfragen, Meldungen. Ergebnisse per E-Mail und im Backend, Zugriff je Formular und Rolle.",
"author": "Inhaus",
"namespace": "Inhaus\\Plugins\\Forms\\",
"class": "Inhaus\\Plugins\\Forms\\FormsPlugin",
"requires": {
"core": ">=0.6.0",
"php": ">=8.3"
}
}

View file

@ -0,0 +1,21 @@
<script setup>
import { inject } from 'vue';
import FormRenderer from '../components/FormRenderer.vue';
defineProps({ block: { type: Object, required: true } });
const editing = inject('pagebuilder:editing', false);
</script>
<template>
<section v-if="block.props" class="rounded-lg border bg-card p-5 @3xl:p-8">
<template v-if="block.data.show_title">
<h3 class="text-xl font-semibold tracking-tight">{{ block.props.title }}</h3>
<p v-if="block.props.description" class="mt-2 mb-6 text-sm leading-relaxed whitespace-pre-line text-muted-foreground">{{ block.props.description }}</p>
</template>
<div :class="{ 'pointer-events-none opacity-80': editing }">
<FormRenderer :key="block.props.id" :form="block.props" />
</div>
</section>
<p v-else-if="editing" class="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">Bitte rechts ein Formular auswählen.</p>
</template>

View file

@ -0,0 +1,199 @@
<script setup>
import { computed } from 'vue';
import { useForm, usePage } from '@inertiajs/vue3';
import { CircleCheck, EyeOff, LoaderCircle, Paperclip, Send, X } from '@lucide/vue';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import NativeSelect from '@/components/NativeSelect.vue';
/**
* Stellt ein Formular dar (Formularseite und Pagebuilder-Block).
* Bedingungen werden hier für die Anzeige und auf dem Server für die Prüfung ausgewertet.
*/
const props = defineProps({
form: { type: Object, required: true },
compact: { type: Boolean, default: false },
});
const page = usePage();
const inputTypes = ['text', 'textarea', 'email', 'phone', 'number', 'date', 'select', 'radio', 'checkboxes', 'checkbox', 'file'];
function initial(field) {
const prefilled = props.form.prefill?.[field.key];
if (field.type === 'checkboxes' || field.type === 'file') return [];
if (field.type === 'checkbox') return false;
return prefilled ?? '';
}
const data = useForm({
answers: Object.fromEntries(props.form.fields.filter((f) => inputTypes.includes(f.type)).map((f) => [f.key, initial(f)])),
});
const submitted = computed(() => page.props.flash?.form_submitted === props.form.id);
function isVisible(field, depth = 0) {
if (!field.condition || depth > 10) return true;
const other = props.form.fields.find((f) => f.key === field.condition.field);
if (!other || !isVisible(other, depth + 1)) return false;
const raw = data.answers[field.condition.field];
const values = (Array.isArray(raw) ? raw : raw === true ? ['1'] : raw === false || raw === '' || raw == null ? [] : [String(raw)]).map(String);
const expected = field.condition.value ?? '';
switch (field.condition.operator) {
case 'not_equals': return !values.includes(expected);
case 'filled': return values.length > 0;
case 'empty': return values.length === 0;
default: return values.includes(expected);
}
}
const visibleFields = computed(() => props.form.fields.filter((field) => isVisible(field)));
function error(field) {
return data.errors[`answers.${field.key}`] ?? Object.entries(data.errors).find(([key]) => key.startsWith(`answers.${field.key}.`))?.[1];
}
function toggleOption(field, option) {
const values = new Set(data.answers[field.key]);
values.has(option) ? values.delete(option) : values.add(option);
data.answers[field.key] = [...values];
}
function addFiles(field, event) {
const files = [...(event.target.files ?? [])];
data.answers[field.key] = field.multiple ? [...data.answers[field.key], ...files].slice(0, 10) : files.slice(0, 1);
event.target.value = '';
}
function removeFile(field, index) {
data.answers[field.key] = data.answers[field.key].filter((_, i) => i !== index);
}
function submit() {
const visibleKeys = new Set(visibleFields.value.map((f) => f.key));
data.transform((values) => ({
answers: Object.fromEntries(Object.entries(values.answers).filter(([key]) => visibleKeys.has(key))),
})).post(props.form.url, {
forceFormData: true,
preserveScroll: true,
onSuccess: () => {
if (page.props.flash?.form_submitted === props.form.id) data.reset();
},
});
}
const formatSize = (bytes) => (bytes > 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1).replace('.', ',')} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`);
const fieldId = (field) => `f${props.form.id}-${field.key}`;
</script>
<template>
<div v-if="submitted" class="flex gap-3 rounded-lg border border-emerald-200 bg-emerald-50 p-5 text-emerald-950 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-100" role="status">
<CircleCheck class="mt-0.5 size-5 shrink-0 text-emerald-600" />
<div>
<p class="font-medium whitespace-pre-line">{{ form.confirmation }}</p>
<p v-if="form.send_copy" class="mt-1 text-sm opacity-80">Eine Kopie Ihrer Angaben ist per E-Mail unterwegs.</p>
</div>
</div>
<p v-else-if="form.already_submitted" class="rounded-lg border bg-muted px-5 py-4 text-sm">Sie haben dieses Formular bereits ausgefüllt. Vielen Dank!</p>
<p v-else-if="!form.open" class="rounded-lg border bg-muted px-5 py-4 text-sm">Dieses Formular nimmt keine Einsendungen mehr an.</p>
<form v-else class="grid gap-5 @xl:grid-cols-2" novalidate @submit.prevent="submit">
<p v-if="form.anonymous" class="flex items-start gap-2 rounded-md bg-muted px-3 py-2 text-[13px] text-muted-foreground @xl:col-span-2">
<EyeOff class="mt-0.5 size-4 shrink-0" /> Anonym: Ihr Name und Ihre E-Mail-Adresse werden nicht gespeichert.
</p>
<p v-if="data.errors.form" class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive @xl:col-span-2">{{ data.errors.form }}</p>
<template v-for="field in visibleFields" :key="field.key">
<h3 v-if="field.type === 'heading'" class="pt-2 text-lg font-semibold @xl:col-span-2">{{ field.text }}</h3>
<p v-else-if="field.type === 'paragraph'" class="text-sm leading-relaxed whitespace-pre-line text-muted-foreground @xl:col-span-2">{{ field.text }}</p>
<div v-else class="grid content-start gap-1.5" :class="field.width === 'half' ? '' : '@xl:col-span-2'">
<template v-if="field.type === 'checkbox'">
<label :for="fieldId(field)" class="flex items-start gap-2.5 text-sm">
<input :id="fieldId(field)" v-model="data.answers[field.key]" type="checkbox" class="mt-0.5 size-4 shrink-0 accent-[var(--brand)]" :aria-invalid="!!error(field)" />
<span>{{ field.label }}<span v-if="field.required" class="text-destructive"> *</span></span>
</label>
</template>
<template v-else>
<component :is="['radio', 'checkboxes'].includes(field.type) ? 'span' : 'label'" :for="fieldId(field)" class="text-[13px] font-medium" :id="`${fieldId(field)}-label`">
{{ field.label }}<span v-if="field.required" class="text-destructive"> *</span>
</component>
<Textarea v-if="field.type === 'textarea'" :id="fieldId(field)" v-model="data.answers[field.key]" :rows="field.rows ?? 4" :maxlength="field.max" :aria-invalid="!!error(field)" />
<NativeSelect v-else-if="field.type === 'select'" :id="fieldId(field)" v-model="data.answers[field.key]" :options="field.options.map((o) => ({ value: o, label: o }))" placeholder="Bitte wählen …" />
<div v-else-if="field.type === 'radio' || field.type === 'checkboxes'" class="grid gap-1.5" role="group" :aria-labelledby="`${fieldId(field)}-label`">
<label v-for="option in field.options" :key="option" class="flex items-center gap-2.5 text-sm">
<input
v-if="field.type === 'radio'"
v-model="data.answers[field.key]"
type="radio"
:name="fieldId(field)"
:value="option"
class="size-4 accent-[var(--brand)]"
/>
<input
v-else
type="checkbox"
:checked="data.answers[field.key].includes(option)"
class="size-4 accent-[var(--brand)]"
@change="toggleOption(field, option)"
/>
{{ option }}
</label>
</div>
<div v-else-if="field.type === 'file'" class="grid gap-2">
<ul v-if="data.answers[field.key].length" class="grid gap-1">
<li v-for="(file, index) in data.answers[field.key]" :key="index" class="flex items-center gap-2 rounded-md border bg-card px-3 py-1.5 text-sm">
<Paperclip class="size-4 shrink-0 text-muted-foreground" />
<span class="min-w-0 flex-1 truncate">{{ file.name }}</span>
<span class="text-xs text-muted-foreground">{{ formatSize(file.size) }}</span>
<button type="button" class="grid size-6 place-items-center rounded hover:bg-accent" :aria-label="`${file.name} entfernen`" @click="removeFile(field, index)"><X class="size-3.5" /></button>
</li>
</ul>
<label v-if="field.multiple || !data.answers[field.key].length" class="flex h-10 cursor-pointer items-center justify-center gap-2 rounded-md border border-dashed text-sm text-muted-foreground hover:border-brand-300 hover:text-foreground">
<Paperclip class="size-4" /> {{ field.multiple ? 'Dateien auswählen' : 'Datei auswählen' }}
<input :id="fieldId(field)" type="file" class="sr-only" :accept="field.accept" :multiple="field.multiple" @change="addFiles(field, $event)" />
</label>
</div>
<Input
v-else
:id="fieldId(field)"
v-model="data.answers[field.key]"
:type="{ email: 'email', phone: 'tel', number: 'number', date: 'date' }[field.type] ?? 'text'"
:placeholder="field.placeholder"
:maxlength="field.type === 'text' ? field.max : undefined"
:min="field.type === 'number' ? field.min : undefined"
:max="field.type === 'number' ? field.max : undefined"
:aria-invalid="!!error(field)"
/>
</template>
<p v-if="error(field)" class="text-[13px] text-destructive">{{ error(field) }}</p>
<p v-else-if="field.help" class="text-[13px] text-muted-foreground">
{{ field.help }}<template v-if="field.type === 'file' && field.max_size"> (höchstens {{ field.max_size }} MB)</template>
</p>
</div>
</template>
<div class="flex items-center gap-4 border-t pt-5 @xl:col-span-2">
<Button type="submit" :disabled="data.processing">
<LoaderCircle v-if="data.processing" class="animate-spin" />
<Send v-else />
{{ form.submit_label }}
</Button>
<span class="text-xs text-muted-foreground">* Pflichtfeld</span>
</div>
</form>
</template>

View file

@ -0,0 +1,33 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import { ChevronRight, ClipboardList } from '@lucide/vue';
import EmptyState from '@/components/EmptyState.vue';
import AppLayout from '@/layouts/AppLayout.vue';
import { formatDate } from '@/lib/format';
defineProps({
forms: { type: Array, required: true },
});
</script>
<template>
<AppLayout title="Formulare">
<div class="mb-6">
<h1 class="text-2xl font-semibold tracking-tight">Formulare</h1>
<p class="mt-1 text-sm text-muted-foreground">Anträge, Anmeldungen und Meldungen – direkt online ausfüllen.</p>
</div>
<div v-if="forms.length" class="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<Link v-for="form in forms" :key="form.id" :href="form.url" class="group flex gap-4 rounded-lg border bg-card p-5 hover:border-brand-300">
<span class="grid size-10 shrink-0 place-items-center rounded-lg bg-brand-soft text-brand-text"><ClipboardList class="size-5" /></span>
<span class="min-w-0 flex-1">
<span class="block font-semibold group-hover:underline">{{ form.title }}</span>
<span v-if="form.description" class="mt-1 line-clamp-2 block text-sm text-muted-foreground">{{ form.description }}</span>
<span v-if="form.closes_at" class="mt-2 block text-xs text-muted-foreground">Bis {{ formatDate(form.closes_at) }}</span>
</span>
<ChevronRight class="mt-2.5 size-4 shrink-0 text-muted-foreground" />
</Link>
</div>
<div v-else class="rounded-lg border bg-card"><EmptyState :icon="ClipboardList" title="Keine Formulare" text="Derzeit sind keine Formulare für Sie freigegeben." /></div>
</AppLayout>
</template>

View file

@ -0,0 +1,29 @@
<script setup>
import { Link } from '@inertiajs/vue3';
import { ArrowLeft, CalendarClock } from '@lucide/vue';
import AppLayout from '@/layouts/AppLayout.vue';
import { formatDate } from '@/lib/format';
import FormRenderer from '../components/FormRenderer.vue';
defineProps({
form: { type: Object, required: true },
});
</script>
<template>
<AppLayout :title="form.title">
<div class="mx-auto max-w-3xl">
<Link href="/formulare" class="mb-6 inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground">
<ArrowLeft class="size-4" /> Alle Formulare
</Link>
<h1 class="text-3xl font-semibold tracking-tight">{{ form.title }}</h1>
<p v-if="form.description" class="mt-3 leading-relaxed whitespace-pre-line text-muted-foreground">{{ form.description }}</p>
<p v-if="form.closes_at && form.open" class="mt-3 inline-flex items-center gap-1.5 text-[13px] text-muted-foreground">
<CalendarClock class="size-4" /> Einsendeschluss: {{ formatDate(form.closes_at) }}
</p>
<div class="@container mt-8 rounded-lg border bg-card p-5 sm:p-8">
<FormRenderer :form="form" />
</div>
</div>
</AppLayout>
</template>

View file

@ -0,0 +1,6 @@
<x-filament-panels::page>
@if ($this->record->isAnonymous())
<p class="text-sm text-gray-500">Anonymes Formular – Namen werden nicht gespeichert.</p>
@endif
{{ $this->table }}
</x-filament-panels::page>

View file

@ -0,0 +1,37 @@
<!doctype html>
<html lang="de">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width"></head>
<body style="margin:0;background:#f4f5f7;font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;color:#1a1d21">
<div style="max-width:640px;margin:0 auto;padding:24px">
<p style="margin:0 0 16px;font-size:13px;color:#5f6670">{{ $portalName }}</p>
<div style="background:#fff;border:1px solid #e3e5e8;border-radius:8px;padding:24px">
<h1 style="margin:0 0 4px;font-size:20px">{{ $form->title }}</h1>
<p style="margin:0 0 20px;font-size:14px;color:#5f6670">
@if ($copy)
Vielen Dank! Hier eine Kopie Ihrer Angaben vom {{ $submission->created_at->timezone(config('app.timezone'))->format('d.m.Y, H:i') }} Uhr.
@else
Eingegangen am {{ $submission->created_at->timezone(config('app.timezone'))->format('d.m.Y, H:i') }} Uhr
– {{ $person ? 'von '.$person->name.' ('.$person->email.')' : 'anonym' }}.
@endif
</p>
@if ($answers !== null)
<table style="width:100%;border-collapse:collapse;font-size:14px">
@foreach ($answers as $answer)
<tr>
<td style="padding:8px 12px 8px 0;border-top:1px solid #e3e5e8;vertical-align:top;color:#5f6670;width:40%">{{ $answer['label'] }}</td>
<td style="padding:8px 0;border-top:1px solid #e3e5e8;vertical-align:top;white-space:pre-line">{{ $answer['value'] !== '' ? $answer['value'] : '–' }}</td>
</tr>
@endforeach
</table>
@else
<p style="font-size:14px">Die Angaben sind aus Datenschutzgründen nicht in dieser E-Mail enthalten.</p>
@endif
@if ($resultsUrl)
<p style="margin:24px 0 0"><a href="{{ $resultsUrl }}" style="display:inline-block;background:#1a1d21;color:#fff;text-decoration:none;padding:10px 16px;border-radius:6px;font-size:14px">Ergebnisse im Portal öffnen</a></p>
@endif
</div>
</div>
</body>
</html>

View file

@ -0,0 +1,14 @@
<?php
use Illuminate\Support\Facades\Route;
use Inhaus\Plugins\Forms\Http\Controllers\FormController;
use Inhaus\Plugins\Forms\Http\Controllers\FormResultsController;
Route::middleware('auth')->group(function () {
Route::get('/formulare', [FormController::class, 'index'])->name('forms.index');
Route::get('/formulare/{form:slug}', [FormController::class, 'show'])->name('forms.show');
Route::post('/formulare/{form:slug}', [FormController::class, 'submit'])->middleware('throttle:20,1')->name('forms.submit');
Route::get('/formulare/dateien/{file}', [FormResultsController::class, 'file'])->name('forms.file');
Route::get('/admin/formulare/{form}/export', [FormResultsController::class, 'export'])->name('forms.export');
});

View file

@ -0,0 +1,256 @@
<?php
namespace Inhaus\Plugins\Forms\Filament\Resources\Forms;
use App\Filament\Components\AudienceSection;
use App\Filament\Components\RoleGrantSelect;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Builder\Block;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Fieldset;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\CreateForm;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\EditForm;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\FormResults;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages\ListForms;
use Inhaus\Plugins\Forms\FormFields;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormSubmission;
use UnitEnum;
class FormResource extends Resource
{
protected static ?string $model = Form::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentList;
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
protected static ?int $navigationSort = 5;
protected static ?string $modelLabel = 'Formular';
protected static ?string $pluralModelLabel = 'Formulare';
protected static ?string $slug = 'formulare';
protected static ?string $recordTitleAttribute = 'title';
public static function form(Schema $schema): Schema
{
return $schema->columns(1)->components([
Tabs::make()->persistTabInQueryString()->tabs([
Tab::make('Felder')->icon(Heroicon::OutlinedQueueList)->schema([
TextInput::make('title')->label('Titel')->required()->maxLength(200),
Textarea::make('description')->label('Einleitung')->rows(2)->maxLength(2000),
Builder::make('fields')
->label('Felder')
->blocks(static::fieldBlocks())
->addActionLabel('Feld hinzufügen')
->blockPickerColumns(3)
->blockNumbers(false)
->collapsible()
->collapsed(fn (string $operation) => $operation === 'edit')
->cloneable()
->reorderableWithButtons()
->minItems(1)
->default([]),
]),
Tab::make('Einstellungen')->icon(Heroicon::OutlinedCog6Tooth)->columns(2)->schema([
Toggle::make('is_open')->label('Nimmt Einsendungen an')->default(true),
DateTimePicker::make('closes_at')->label('Einsendeschluss')->native(false)->seconds(false)->displayFormat('d.m.Y H:i'),
TextInput::make('settings.submit_label')->label('Beschriftung des Absende-Knopfs')->placeholder('Absenden')->maxLength(60),
Toggle::make('settings.once_per_user')->label('Jede Person nur einmal')->inline(false),
Textarea::make('settings.confirmation')->label('Bestätigung nach dem Absenden')->placeholder('Vielen Dank! Ihre Angaben sind eingegangen.')->rows(2)->maxLength(1000)->columnSpanFull(),
Toggle::make('settings.anonymous')->label('Anonym')
->helperText('Name und E-Mail-Adresse werden nicht gespeichert und nicht mitgeschickt – z. B. für Umfragen oder vertrauliche Meldungen an die MAV.')
->columnSpanFull(),
TextInput::make('settings.retention_days')->label('Einsendungen automatisch löschen nach')->numeric()->minValue(1)->maxValue(3650)->suffix('Tagen')
->helperText('Leer = nicht automatisch löschen.'),
]),
Tab::make('Benachrichtigung')->icon(Heroicon::OutlinedEnvelope)->schema([
TagsInput::make('settings.notify_emails')->label('E-Mail an')->placeholder('personal@firma.de')
->nestedRecursiveRules(['email'])
->helperText('Bei jeder Einsendung. Auch Funktionspostfächer möglich.'),
Toggle::make('settings.notify_viewers')->label('Alle mit Zugriff auf die Ergebnisse benachrichtigen (E-Mail und Glocke im Portal)'),
Toggle::make('settings.mail_answers')->label('Angaben in die E-Mail aufnehmen')->default(true)
->helperText('Aus, wenn die Angaben vertraulich sind – die E-Mail enthält dann nur einen Link zu den Ergebnissen.'),
Toggle::make('settings.send_copy')->label('Kopie an die ausfüllende Person'),
]),
Tab::make('Zugriff')->icon(Heroicon::OutlinedLockClosed)->schema([
Section::make('Ergebnisse')
->description('Welche Rollen die Einsendungen dieses Formulars sehen – z. B. nur die Personalabteilung.')
->columns(3)
->visible(fn () => auth()->user()->can('forms.manage') || auth()->user()->can('roles.manage'))
->schema([
RoleGrantSelect::make('result_viewers', 'Ansehen und exportieren', 'forms.results', 'form'),
RoleGrantSelect::make('result_deleters', 'Löschen', 'forms.results.delete', 'form'),
RoleGrantSelect::make('editors', 'Formular bearbeiten', 'forms.edit', 'form'),
]),
AudienceSection::make('form', 'Wer das Formular ausfüllen darf. Leer lassen = alle.'),
]),
]),
]);
}
/**
* @return list<Block>
*/
public static function fieldBlocks(): array
{
$common = fn (array $extra = [], bool $prefill = false) => [
TextInput::make('label')->label('Bezeichnung')->required()->maxLength(200)->live(onBlur: true)->columnSpan(2),
Toggle::make('required')->label('Pflichtfeld')->inline(false),
...$extra,
TextInput::make('help')->label('Hinweis unter dem Feld')->maxLength(300)->columnSpan(2),
Select::make('width')->label('Breite')->options(['full' => 'Volle Breite', 'half' => 'Halbe Breite'])->default('full')->native(false),
...($prefill ? [Select::make('prefill')->label('Vorbelegen mit')->options(fn () => FormFields::prefillOptions())->placeholder('–')->native(false)] : []),
static::conditionFieldset(),
TextInput::make('key')->label('Technischer Schlüssel')->helperText('Für Export und Bedingungen. Leer = aus der Bezeichnung.')->maxLength(60)->alphaDash(),
];
$options = TagsInput::make('options')->label('Auswahlmöglichkeiten')->placeholder('Eintrag eingeben und Enter')->required()->reorderable()->columnSpanFull();
return [
Block::make('text')->label(static::blockLabel('text'))->icon(Heroicon::OutlinedPencil)->columns(3)
->schema($common([TextInput::make('placeholder')->label('Platzhalter')->maxLength(100), TextInput::make('max')->label('Höchstlänge')->numeric()->minValue(1)->maxValue(255)], prefill: true)),
Block::make('textarea')->label(static::blockLabel('textarea'))->icon(Heroicon::OutlinedBars3BottomLeft)->columns(3)
->schema($common([TextInput::make('rows')->label('Zeilen')->numeric()->minValue(2)->maxValue(20)->default(4), TextInput::make('max')->label('Höchstlänge')->numeric()->minValue(1)->maxValue(10000)])),
Block::make('email')->label(static::blockLabel('email'))->icon(Heroicon::OutlinedAtSymbol)->columns(3)->schema($common(prefill: true)),
Block::make('phone')->label(static::blockLabel('phone'))->icon(Heroicon::OutlinedPhone)->columns(3)->schema($common(prefill: true)),
Block::make('number')->label(static::blockLabel('number'))->icon(Heroicon::OutlinedHashtag)->columns(3)
->schema($common([TextInput::make('min')->label('Mindestens')->numeric(), TextInput::make('max')->label('Höchstens')->numeric()])),
Block::make('date')->label(static::blockLabel('date'))->icon(Heroicon::OutlinedCalendarDays)->columns(3)->schema($common()),
Block::make('select')->label(static::blockLabel('select'))->icon(Heroicon::OutlinedChevronUpDown)->columns(3)->schema($common([$options])),
Block::make('radio')->label(static::blockLabel('radio'))->icon(Heroicon::OutlinedStop)->columns(3)->schema($common([$options])),
Block::make('checkboxes')->label(static::blockLabel('checkboxes'))->icon(Heroicon::OutlinedCheckCircle)->columns(3)
->schema($common([$options, TextInput::make('min')->label('Mindestens … auswählen')->numeric()->minValue(0), TextInput::make('max')->label('Höchstens … auswählen')->numeric()->minValue(1)])),
Block::make('checkbox')->label(static::blockLabel('checkbox'))->icon(Heroicon::OutlinedCheck)->columns(3)
->schema($common()),
Block::make('file')->label(static::blockLabel('file'))->icon(Heroicon::OutlinedPaperClip)->columns(3)
->schema($common([
Select::make('accept')->label('Erlaubte Dateien')->options(['documents' => 'Dokumente (PDF, Office …)', 'images' => 'Bilder', 'any' => 'Dokumente und Bilder'])->default('any')->native(false),
TextInput::make('max_size')->label('Höchstgröße')->numeric()->minValue(1)->maxValue(50)->default(10)->suffix('MB'),
Toggle::make('multiple')->label('Mehrere Dateien (bis 10)')->inline(false),
])),
Block::make('heading')->label(static::blockLabel('heading'))->icon(Heroicon::OutlinedH2)
->schema([TextInput::make('text')->label('Text')->required()->maxLength(200), static::conditionFieldset()]),
Block::make('paragraph')->label(static::blockLabel('paragraph'))->icon(Heroicon::OutlinedInformationCircle)
->schema([Textarea::make('text')->label('Text')->required()->rows(3)->maxLength(3000), static::conditionFieldset()]),
];
}
/**
* Titel eines Feldes im Baukasten: Typ und Bezeichnung (auch zugeklappt lesbar).
*/
private static function blockLabel(string $type): \Closure
{
return function (?array $state) use ($type) {
$text = $state['label'] ?? $state['text'] ?? null;
$suffix = ($state['required'] ?? false) ? ' *' : '';
$conditional = filled($state['condition_field'] ?? null) ? ' (bedingt)' : '';
return FormFields::TYPES[$type].($text ? ': '.mb_strimwidth((string) $text, 0, 70, '…') : '').$suffix.$conditional;
};
}
private static function conditionFieldset(): Fieldset
{
return Fieldset::make('Nur anzeigen, wenn …')->columns(3)->columnSpanFull()->schema([
Select::make('condition_field')->label('Feld')->placeholder('– immer anzeigen –')->native(false)
->options(function (Get $get) {
// Alle Eingabefelder des Formulars (Bezeichnung → Schlüssel).
$fields = FormFields::normalize((array) $get('../../../fields'));
return collect($fields)->reject(fn ($f) => in_array($f['type'], FormFields::LAYOUT_TYPES, true))
->mapWithKeys(fn ($f) => [$f['data']['key'] => ($f['data']['label'] ?? $f['data']['key'])])->all();
})
->live(),
Select::make('condition_operator')->label('Bedingung')->native(false)->default('equals')
->options(['equals' => 'ist gleich', 'not_equals' => 'ist nicht', 'contains' => 'enthält (Mehrfachauswahl)', 'filled' => 'ist ausgefüllt', 'empty' => 'ist leer'])
->visible(fn (Get $get) => filled($get('condition_field'))),
TextInput::make('condition_value')->label('Wert')->maxLength(200)
->visible(fn (Get $get) => filled($get('condition_field')) && ! in_array($get('condition_operator'), ['filled', 'empty'], true))
->helperText('Bei Kontrollkästchen: 1 für „angehakt“.'),
]);
}
/**
* Sichtbar sind Formulare, die man bearbeiten oder deren Ergebnisse man sehen darf.
*/
public static function getEloquentQuery(): EloquentBuilder
{
$user = auth()->user();
if (! $user || $user->can('forms.manage')) {
return parent::getEloquentQuery();
}
$ids = collect([$user->permissions()->ids('forms.edit', 'form'), $user->permissions()->ids('forms.results', 'form')]);
// Streng vergleichen: eine ID-Liste ist nicht „alle“.
return $ids->contains(fn ($value) => $value === true)
? parent::getEloquentQuery()
: parent::getEloquentQuery()->whereIn('id', $ids->flatten()->unique()->values()->all());
}
public static function table(Table $table): Table
{
return $table
->defaultSort('title')
->columns([
TextColumn::make('title')->label('Titel')->searchable()->weight('medium')
->description(fn (Form $record) => $record->url()),
TextColumn::make('submissions_count')->label('Einsendungen')->counts('submissions')->sortable()
->badge()->color(fn (Form $record) => static::unread($record) ? 'primary' : 'gray')
->formatStateUsing(fn ($state, Form $record) => ($unread = static::unread($record)) ? "{$state} ({$unread} neu)" : $state),
IconColumn::make('is_open')->label('Offen')->boolean(),
IconColumn::make('settings.anonymous')->label('Anonym')->boolean()->trueIcon(Heroicon::OutlinedEyeSlash)->falseIcon(false),
TextColumn::make('closes_at')->label('Einsendeschluss')->dateTime('d.m.Y H:i')->placeholder('–'),
])
->recordActions([
Action::make('results')->label('Ergebnisse')->icon(Heroicon::OutlinedTableCells)
->url(fn (Form $record) => static::getUrl('results', ['record' => $record]))
->visible(fn (Form $record) => auth()->user()->can('viewResults', $record)),
EditAction::make()->visible(fn (Form $record) => auth()->user()->can('update', $record)),
DeleteAction::make()->modalDescription('Das Formular und alle Einsendungen samt Dateien werden gelöscht.'),
])
->recordUrl(fn (Form $record) => auth()->user()->can('update', $record)
? static::getUrl('edit', ['record' => $record])
: static::getUrl('results', ['record' => $record]));
}
private static function unread(Form $form): int
{
return once(fn () => FormSubmission::query()->whereNull('read_at')->selectRaw('form_id, count(*) as c')->groupBy('form_id')->pluck('c', 'form_id')->all())[$form->id] ?? 0;
}
public static function getPages(): array
{
return [
'index' => ListForms::route('/'),
'create' => CreateForm::route('/neu'),
'edit' => EditForm::route('/{record}/bearbeiten'),
'results' => FormResults::route('/{record}/ergebnisse'),
];
}
}

View file

@ -0,0 +1,16 @@
<?php
namespace Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages;
use Filament\Resources\Pages\CreateRecord;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\FormResource;
class CreateForm extends CreateRecord
{
protected static string $resource = FormResource::class;
protected function mutateFormDataBeforeCreate(array $data): array
{
return [...$data, 'created_by' => auth()->id()];
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Icons\Heroicon;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\FormResource;
class EditForm extends EditRecord
{
protected static string $resource = FormResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('view')->label('Ansehen')->icon(Heroicon::OutlinedEye)->color('gray')
->url(fn () => $this->record->url())->openUrlInNewTab(),
Action::make('results')->label('Ergebnisse')->icon(Heroicon::OutlinedTableCells)->color('gray')
->url(fn () => FormResource::getUrl('results', ['record' => $this->record]))
->visible(fn () => auth()->user()->can('viewResults', $this->record)),
DeleteAction::make()->modalDescription('Das Formular und alle Einsendungen samt Dateien werden gelöscht.'),
];
}
}

View file

@ -0,0 +1,141 @@
<?php
namespace Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages;
use App\Support\Audit;
use Filament\Actions\Action;
use Filament\Actions\BulkAction;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
use Filament\Resources\Pages\Page;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\FormResource;
use Inhaus\Plugins\Forms\FormFields;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormSubmission;
/**
* Einsendungen eines Formulars – nur für Rollen mit „Ergebnisse ansehen“ für dieses Formular.
*/
class FormResults extends Page implements HasTable
{
use InteractsWithRecord;
use InteractsWithTable;
protected static string $resource = FormResource::class;
protected string $view = 'forms::filament.results';
public function mount(int|string $record): void
{
$this->record = $this->resolveRecord($record);
abort_unless(auth()->user()->can('viewResults', $this->record), 403);
}
public function getTitle(): string
{
return 'Ergebnisse: '.$this->record->title;
}
public function getBreadcrumbs(): array
{
return [FormResource::getUrl() => 'Formulare', 'Ergebnisse'];
}
public function table(Table $table): Table
{
/** @var Form $form */
$form = $this->record;
$inputs = array_slice(FormFields::inputs($form), 0, 4, true);
$canDelete = auth()->user()->can('deleteResults', $form);
return $table
->query(FormSubmission::query()->where('form_id', $form->id)->with(['user:id,name,email', 'files']))
->defaultSort('created_at', 'desc')
->columns([
TextColumn::make('created_at')->label('Eingegangen')->dateTime('d.m.Y H:i')->sortable()
->weight(fn (FormSubmission $s) => $s->read_at ? null : 'bold')
->description(fn (FormSubmission $s) => $s->read_at ? null : 'neu'),
TextColumn::make('user.name')->label('Person')->placeholder('anonym')->searchable()->visible(! $form->isAnonymous()),
...collect($inputs)->map(fn ($label, $key) => TextColumn::make('answer_'.$key)
->label(Str::limit($label, 30))
->state(fn (FormSubmission $s) => Str::limit($s->display($key), 60))
->wrap())->values()->all(),
])
->filters([
TernaryFilter::make('read_at')->label('Gelesen')->nullable()->trueLabel('Gelesen')->falseLabel('Neu'),
])
->recordActions([
Action::make('view')->label('Ansehen')->icon(Heroicon::OutlinedEye)
->modalHeading(fn (FormSubmission $s) => 'Einsendung vom '.$s->created_at->format('d.m.Y, H:i').' Uhr')
->modalContent(fn (FormSubmission $s) => $this->details($s))
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen')
->mountUsing(fn (FormSubmission $s) => $s->read_at ?? $s->forceFill(['read_at' => now()])->save()),
DeleteAction::make()->visible($canDelete)->after(fn (FormSubmission $s) => Audit::log('forms.submission_deleted', ['form' => $form->id, 'submission' => $s->id])),
])
->toolbarActions([
BulkAction::make('markRead')->label('Als gelesen markieren')->icon(Heroicon::OutlinedCheck)
->action(fn (Collection $records) => FormSubmission::query()->whereIn('id', $records->modelKeys())->whereNull('read_at')->update(['read_at' => now()]))
->deselectRecordsAfterCompletion(),
BulkAction::make('delete')->label('Löschen')->icon(Heroicon::OutlinedTrash)->color('danger')->requiresConfirmation()
->visible($canDelete)
->action(function (Collection $records) use ($form) {
$records->each->delete();
Audit::log('forms.submissions_deleted', ['form' => $form->id, 'count' => $records->count()]);
})
->deselectRecordsAfterCompletion(),
])
->emptyStateHeading('Noch keine Einsendungen')
->emptyStateIcon(Heroicon::OutlinedInboxStack);
}
protected function getHeaderActions(): array
{
return [
Action::make('export')->label('Als CSV exportieren')->icon(Heroicon::OutlinedArrowDownTray)
->url(fn () => route('forms.export', $this->record)),
Action::make('edit')->label('Formular bearbeiten')->icon(Heroicon::OutlinedPencilSquare)->color('gray')
->url(fn () => FormResource::getUrl('edit', ['record' => $this->record]))
->visible(fn () => auth()->user()->can('update', $this->record)),
];
}
private function details(FormSubmission $submission): HtmlString
{
$rows = '';
if (! $this->record->isAnonymous()) {
$rows .= self::row('Person', e($submission->user ? $submission->user->name.' ('.$submission->user->email.')' : 'gelöschtes Konto'));
}
foreach ($submission->data as $key => $answer) {
if (($answer['type'] ?? null) === 'file') {
$value = collect($submission->files->where('field', $key))
->map(fn ($file) => '<a href="'.e($file->url()).'" style="color: rgb(var(--primary-600, 37 99 235)); text-decoration: underline">'.e($file->name).'</a>')
->implode('<br>') ?: '–';
} else {
$value = nl2br(e($submission->display($key) ?: '–'));
}
$rows .= self::row(e($answer['label']), $value);
}
return new HtmlString('<table style="width: 100%; border-collapse: collapse; font-size: 0.875rem">'.$rows.'</table>');
}
private static function row(string $label, string $value): string
{
$cell = 'padding: 0.5rem 0; border-top: 1px solid rgba(127, 127, 127, 0.2); vertical-align: top;';
return '<tr><th style="'.$cell.' width: 40%; padding-right: 1rem; text-align: left; font-weight: 500; opacity: 0.7">'.$label.'</th><td style="'.$cell.'">'.$value.'</td></tr>';
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace Inhaus\Plugins\Forms\Filament\Resources\Forms\Pages;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Inhaus\Plugins\Forms\Filament\Resources\Forms\FormResource;
class ListForms extends ListRecords
{
protected static string $resource = FormResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()->label('Formular anlegen')];
}
}

View file

@ -0,0 +1,295 @@
<?php
namespace Inhaus\Plugins\Forms;
use App\Models\User;
use App\Support\ProfileFields;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
use Inhaus\Plugins\Forms\Models\Form;
/**
* Felder eines Formulars: Typen, Bedingungen, Validierung und Aufbereitung.
*
* Gespeichert wird das Format des Formularbaukastens im Admin:
* [['type' => 'text', 'data' => ['label' => 'Name', 'key' => 'name', 'required' => true, …]], …]
*/
class FormFields
{
public const TYPES = [
'text' => 'Textzeile',
'textarea' => 'Mehrzeiliger Text',
'email' => 'E-Mail-Adresse',
'phone' => 'Telefonnummer',
'number' => 'Zahl',
'date' => 'Datum',
'select' => 'Auswahlliste',
'radio' => 'Einfachauswahl',
'checkboxes' => 'Mehrfachauswahl',
'checkbox' => 'Kontrollkästchen (Ja/Nein)',
'file' => 'Datei-Upload',
'heading' => 'Zwischenüberschrift',
'paragraph' => 'Hinweistext',
];
/** Nur Gestaltung, kein Eingabefeld. */
public const LAYOUT_TYPES = ['heading', 'paragraph'];
public const FILE_TYPES = [
'documents' => ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'odt', 'ods', 'ppt', 'pptx', 'txt', 'csv', 'rtf'],
'images' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'heic'],
'any' => ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'odt', 'ods', 'ppt', 'pptx', 'txt', 'csv', 'rtf', 'jpg', 'jpeg', 'png', 'webp', 'gif', 'heic', 'zip', 'msg', 'eml'],
];
public const PREFILL = [
'name' => 'Name',
'first_name' => 'Vorname',
'last_name' => 'Nachname',
'email' => 'E-Mail-Adresse',
'phone' => 'Telefon',
'mobile' => 'Mobil',
'job_title' => 'Funktion',
'department' => 'Abteilung',
'location' => 'Standort',
];
/**
* Schlüssel ergänzen und eindeutig machen, unbekannte Typen entfernen.
*
* @param array<mixed> $fields
* @return list<array{type: string, data: array<string, mixed>}>
*/
public static function normalize(array $fields): array
{
$result = [];
$used = [];
foreach (array_values($fields) as $index => $field) {
$type = $field['type'] ?? null;
if (! is_array($field) || ! isset(self::TYPES[$type])) {
continue;
}
$data = is_array($field['data'] ?? null) ? $field['data'] : [];
$base = Str::slug((string) (($data['key'] ?? '') ?: ($data['label'] ?? $data['text'] ?? '') ?: $type.'-'.($index + 1)), '_', 'de') ?: $type;
$base = mb_substr($base, 0, 60);
$key = $base;
for ($i = 2; in_array($key, $used, true); $i++) {
$key = $base.'_'.$i;
}
$used[] = $key;
$data['key'] = $key;
$result[] = ['type' => $type, 'data' => $data];
}
return $result;
}
/**
* Beschreibung für das Formular im Portal (ohne interne Einstellungen).
*
* @return list<array<string, mixed>>
*/
public static function forFrontend(Form $form): array
{
return array_map(function (array $field) {
$d = $field['data'];
return array_filter([
'type' => $field['type'],
'key' => $d['key'],
'label' => $d['label'] ?? null,
'text' => $d['text'] ?? null,
'help' => $d['help'] ?? null,
'placeholder' => $d['placeholder'] ?? null,
'required' => (bool) ($d['required'] ?? false),
'options' => array_values(array_filter(array_map('strval', (array) ($d['options'] ?? [])), 'strlen')) ?: null,
'width' => $d['width'] ?? 'full',
'min' => $d['min'] ?? null,
'max' => $d['max'] ?? null,
'rows' => $d['rows'] ?? null,
'multiple' => (bool) ($d['multiple'] ?? false),
'accept' => isset($d['accept']) ? implode(',', array_map(fn ($ext) => '.'.$ext, self::FILE_TYPES[$d['accept']] ?? self::FILE_TYPES['any'])) : null,
'max_size' => $d['max_size'] ?? null,
'condition' => filled($d['condition_field'] ?? null) ? [
'field' => $d['condition_field'],
'operator' => $d['condition_operator'] ?? 'equals',
'value' => (string) ($d['condition_value'] ?? ''),
] : null,
], fn ($value) => $value !== null && $value !== false && $value !== '');
}, $form->fields ?? []);
}
/**
* Vorbelegung aus dem Profil der Person.
*
* @return array<string, mixed>
*/
public static function prefill(Form $form, User $user): array
{
$values = [];
foreach ($form->fields ?? [] as $field) {
$source = $field['data']['prefill'] ?? null;
if (! $source) {
continue;
}
$values[$field['data']['key']] = str_starts_with($source, 'custom.')
? (string) (($user->custom_fields ?? [])[substr($source, 7)] ?? '')
: (string) ($user->{$source} ?? '');
}
return $values;
}
/**
* @return array<string, string>
*/
public static function prefillOptions(): array
{
return self::PREFILL + collect(app(ProfileFields::class)->options())->mapWithKeys(fn ($label, $key) => ['custom.'.$key => $label])->all();
}
/**
* Ist das Feld bei diesen Antworten sichtbar? (Bedingungen, auch verkettet)
*
* @param array<string, mixed> $answers
*/
public static function visible(Form $form, array $field, array $answers, int $depth = 0): bool
{
$d = $field['data'];
if (blank($d['condition_field'] ?? null) || $depth > 10) {
return true;
}
$other = collect($form->fields)->first(fn ($f) => $f['data']['key'] === $d['condition_field']);
if (! $other || ! self::visible($form, $other, $answers, $depth + 1)) {
return false;
}
$value = $answers[$d['condition_field']] ?? null;
$expected = (string) ($d['condition_value'] ?? '');
$values = array_map('strval', is_array($value) ? $value : ($value === null || $value === '' ? [] : [$value === true ? '1' : (string) $value]));
return match ($d['condition_operator'] ?? 'equals') {
'not_equals' => ! in_array($expected, $values, true),
'contains' => in_array($expected, $values, true),
'filled' => $values !== [] && $values !== ['0'],
'empty' => $values === [] || $values === ['0'],
default => in_array($expected, $values, true),
};
}
/**
* Validierungsregeln für die sichtbaren Felder.
*
* @param array<string, mixed> $answers
* @return array{0: array<string, mixed>, 1: array<string, string>, 2: array<string, string>}
*/
public static function rules(Form $form, array $answers): array
{
$rules = [];
$attributes = [];
$messages = [];
foreach ($form->fields ?? [] as $field) {
if (in_array($field['type'], self::LAYOUT_TYPES, true) || ! self::visible($form, $field, $answers)) {
continue;
}
$d = $field['data'];
$name = 'answers.'.$d['key'];
$required = (bool) ($d['required'] ?? false);
$attributes[$name] = $d['label'] ?? $d['key'];
$options = array_values(array_filter(array_map('strval', (array) ($d['options'] ?? [])), 'strlen'));
$max = isset($d['max']) && $d['max'] !== '' ? (int) $d['max'] : null;
$min = isset($d['min']) && $d['min'] !== '' ? (int) $d['min'] : null;
$rules[$name] = match ($field['type']) {
'text' => [$required ? 'required' : 'nullable', 'string', 'max:'.($max ?: 255)],
'textarea' => [$required ? 'required' : 'nullable', 'string', 'max:'.($max ?: 10000)],
'email' => [$required ? 'required' : 'nullable', 'email', 'max:255'],
'phone' => [$required ? 'required' : 'nullable', 'string', 'max:50', 'regex:/^[0-9+()\/\-.\s]{3,50}$/'],
'number' => [$required ? 'required' : 'nullable', 'numeric', ...($min !== null ? ['min:'.$min] : []), ...($max !== null ? ['max:'.$max] : [])],
'date' => [$required ? 'required' : 'nullable', 'date'],
'select', 'radio' => [$required ? 'required' : 'nullable', 'string', Rule::in($options)],
'checkboxes' => [$required ? 'required' : 'nullable', 'array', ...($min ? ['min:'.$min] : []), ...($max ? ['max:'.$max] : [])],
'checkbox' => $required ? ['accepted'] : ['nullable', 'boolean'],
'file' => [$required ? 'required' : 'nullable', 'array', 'max:'.(($d['multiple'] ?? false) ? 10 : 1)],
};
if ($field['type'] === 'checkbox') {
$messages[$name.'.accepted'] = 'Bitte bestätigen.';
}
if ($field['type'] === 'checkboxes') {
$rules[$name.'.*'] = ['string', Rule::in($options)];
}
if ($field['type'] === 'file') {
$rules[$name.'.*'] = [File::types(self::FILE_TYPES[$d['accept'] ?? 'any'] ?? self::FILE_TYPES['any'])->max(min(50, max(1, (int) ($d['max_size'] ?? 10))) * 1024)];
$attributes[$name.'.*'] = $attributes[$name];
}
}
return [$rules, $attributes, $messages];
}
/**
* Antworten zum Speichern aufbereiten – nur sichtbare Felder.
*
* @param array<string, mixed> $answers validierte Eingaben
* @return array{0: array<string, array{label: string, type: string, value: mixed}>, 1: array<string, list<UploadedFile>>}
*/
public static function collect(Form $form, array $answers): array
{
$data = [];
$files = [];
foreach ($form->fields ?? [] as $field) {
if (in_array($field['type'], self::LAYOUT_TYPES, true) || ! self::visible($form, $field, $answers)) {
continue;
}
$key = $field['data']['key'];
$value = $answers[$key] ?? null;
if ($field['type'] === 'file') {
$files[$key] = array_values(array_filter((array) $value, fn ($f) => $f instanceof UploadedFile));
$value = [];
} elseif ($field['type'] === 'checkbox') {
$value = (bool) $value;
} elseif ($field['type'] === 'checkboxes') {
$value = array_values(array_map('strval', (array) $value));
} elseif ($value !== null) {
$value = trim((string) $value);
}
$data[$key] = ['label' => (string) ($field['data']['label'] ?? $key), 'type' => $field['type'], 'value' => $value];
}
return [$data, $files];
}
/**
* Eingabefelder (ohne Gestaltungselemente): Schlüssel => Bezeichnung.
*
* @return array<string, string>
*/
public static function inputs(Form $form): array
{
return collect($form->fields ?? [])
->reject(fn ($f) => in_array($f['type'], self::LAYOUT_TYPES, true))
->mapWithKeys(fn ($f) => [$f['data']['key'] => (string) ($f['data']['label'] ?? $f['data']['key'])])
->all();
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Inhaus\Plugins\Forms;
use App\Models\User;
use Inhaus\Plugins\Forms\Models\Form;
/**
* Daten eines Formulars für das Portal (Seite und Pagebuilder-Block).
*/
final class FormPresenter
{
/**
* @return array<string, mixed>
*/
public static function present(Form $form, User $user): array
{
$once = (bool) $form->setting('once_per_user');
return [
'id' => $form->id,
'title' => $form->title,
'description' => $form->description,
'url' => $form->url(),
'fields' => FormFields::forFrontend($form),
'prefill' => FormFields::prefill($form, $user),
'submit_label' => $form->setting('submit_label') ?: 'Absenden',
'confirmation' => $form->setting('confirmation') ?: 'Vielen Dank! Ihre Angaben sind eingegangen.',
'anonymous' => $form->isAnonymous(),
'send_copy' => (bool) $form->setting('send_copy'),
'open' => $form->acceptsSubmissions(),
'closes_at' => $form->closes_at?->toIso8601String(),
'already_submitted' => $once && $form->alreadySubmittedBy($user),
];
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Inhaus\Plugins\Forms;
use App\Models\User;
use App\Pagebuilder\Blocks;
use App\Pagebuilder\BlockType;
use App\Pagebuilder\Field;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schedule;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Policies\FormPolicy;
class FormsPlugin extends Plugin
{
public function register(): void
{
$this->app->make(Navigation::class)->add('forms', 'Formulare', '/formulare', active: ['forms.index', 'forms.show'], sort: 60);
$abilities = $this->app->make(Abilities::class);
$abilities->define('forms.manage', 'Formulare: alle Formulare und Ergebnisse verwalten', 'Formulare');
$abilities->define('forms.edit', 'Formular bearbeiten', 'Formulare', resource: 'form');
$abilities->define('forms.results', 'Ergebnisse ansehen und exportieren', 'Formulare', resource: 'form');
$abilities->define('forms.results.delete', 'Ergebnisse löschen', 'Formulare', resource: 'form');
$abilities->resourceType('form', 'Formular', fn () => Form::query()->orderBy('title')->pluck('title', 'id')->all());
Gate::policy(Form::class, FormPolicy::class);
$this->app->make(Blocks::class)->add(BlockType::make('forms.form', 'Formular', 'clipboard-list', 'dynamic', 'forms::FormBlock')
->description('Ein Formular direkt auf der Seite ausfüllen lassen.')
->fields([
Field::select('form', 'Formular', fn () => Form::query()->orderBy('title')->pluck('title', 'id')->mapWithKeys(fn ($t, $id) => [(string) $id => $t])->all()),
Field::toggle('show_title', 'Titel und Beschreibung anzeigen', true),
])
->resolveUsing(function (array $data, ?User $user) {
$form = $data['form'] ? Form::query()->find($data['form']) : null;
return $form && $user && $form->isVisibleTo($user) ? FormPresenter::present($form, $user) : null;
}));
}
public function boot(): void
{
// Löschfristen: alte Einsendungen samt Dateien entfernen.
Schedule::call(fn () => app(Retention::class)->purge())->dailyAt('03:15')->name('forms-retention')->withoutOverlapping(30);
}
}

View file

@ -0,0 +1,72 @@
<?php
namespace Inhaus\Plugins\Forms\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Forms\FormFields;
use Inhaus\Plugins\Forms\FormPresenter;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Submissions;
class FormController extends Controller
{
public function index(Request $request): Response
{
$forms = Form::query()->visibleTo($request->user())
->where('is_open', true)
->where(fn ($q) => $q->whereNull('closes_at')->orWhere('closes_at', '>', now()))
->orderBy('title')
->get(['id', 'title', 'slug', 'description', 'closes_at']);
return Inertia::render('forms::Index', [
'forms' => $forms->map(fn (Form $form) => [
'id' => $form->id,
'title' => $form->title,
'description' => $form->description,
'url' => $form->url(),
'closes_at' => $form->closes_at?->toIso8601String(),
]),
]);
}
public function show(Request $request, Form $form): Response
{
abort_unless($form->isVisibleTo($request->user()), 404);
return Inertia::render('forms::Show', [
'form' => FormPresenter::present($form, $request->user()),
]);
}
public function submit(Request $request, Form $form, Submissions $submissions): RedirectResponse
{
$user = $request->user();
abort_unless($form->isVisibleTo($user), 404);
if (! $form->acceptsSubmissions()) {
return back()->withErrors(['form' => 'Dieses Formular nimmt keine Einsendungen mehr an.']);
}
if ($form->setting('once_per_user') && $form->alreadySubmittedBy($user)) {
return back()->withErrors(['form' => 'Sie haben dieses Formular bereits ausgefüllt.']);
}
$answers = (array) $request->input('answers', []);
foreach ($request->allFiles()['answers'] ?? [] as $key => $files) {
$answers[$key] = is_array($files) ? $files : [$files];
}
[$rules, $attributes, $messages] = FormFields::rules($form, $answers);
$validated = Validator::make(['answers' => $answers], $rules, $messages, $attributes)->validate();
$submissions->store($form, $user, $validated['answers'] ?? []);
return back()->with('form_submitted', $form->id);
}
}

View file

@ -0,0 +1,78 @@
<?php
namespace Inhaus\Plugins\Forms\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Support\Audit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inhaus\Plugins\Forms\FormFields;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormFile;
use Symfony\Component\HttpFoundation\StreamedResponse;
class FormResultsController extends Controller
{
public function file(FormFile $file): StreamedResponse
{
Gate::authorize('viewResults', $file->submission->form);
return Storage::disk(FormFile::DISK)->download($file->path, $file->name, [
'Content-Type' => $file->mime ?: 'application/octet-stream',
'X-Content-Type-Options' => 'nosniff',
'Cache-Control' => 'private, no-store',
]);
}
/**
* CSV für Excel: UTF-8 mit BOM, Semikolon als Trenner.
*/
public function export(Request $request, Form $form): StreamedResponse
{
Gate::authorize('viewResults', $form);
Audit::log('forms.exported', ['form' => $form->id, 'title' => $form->title]);
$columns = FormFields::inputs($form);
$anonymous = $form->isAnonymous();
return response()->streamDownload(function () use ($form, $columns, $anonymous) {
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF");
$known = $columns;
// Felder, die es nur noch in älteren Einsendungen gibt, hinten anhängen.
$form->submissions()->select(['id', 'data'])->chunkById(500, function ($chunk) use (&$known) {
foreach ($chunk as $submission) {
foreach ($submission->data as $key => $answer) {
$known[$key] ??= $answer['label'];
}
}
});
fputcsv($out, ['Eingegangen am', ...($anonymous ? [] : ['Name', 'E-Mail']), ...array_values($known)], ';', '"', '');
$form->submissions()->with('user:id,name,email')->orderBy('id')->chunkById(500, function ($chunk) use ($out, $known, $anonymous) {
foreach ($chunk as $submission) {
fputcsv($out, [
$submission->created_at->timezone(config('app.timezone'))->format('d.m.Y H:i'),
...($anonymous ? [] : [$submission->user?->name ?? '', $submission->user?->email ?? '']),
...array_map(fn ($key) => self::cell($submission->display($key)), array_keys($known)),
], ';', '"', '');
}
});
fclose($out);
}, Str::slug($form->title).'-'.now()->format('Y-m-d').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
/**
* Schutz vor Formel-Einschleusung in Tabellenprogrammen.
*/
private static function cell(string $value): string
{
return preg_match('/^[=+\-@\t\r]/', $value) ? "'".$value : $value;
}
}

View file

@ -0,0 +1,54 @@
<?php
namespace Inhaus\Plugins\Forms\Mail;
use App\Models\User;
use App\Support\Branding;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormSubmission;
/**
* Benachrichtigung über eine Einsendung – an die Empfänger des Formulars oder
* als Kopie an die Person selbst. Dateien werden nicht angehängt, sondern nur
* nach Anmeldung abrufbar verlinkt.
*/
class FormSubmitted extends Mailable implements ShouldQueue
{
use Queueable;
use SerializesModels;
public function __construct(
public Form $form,
public FormSubmission $submission,
public ?User $person,
public bool $copy,
) {}
public function envelope(): Envelope
{
return new Envelope(
subject: ($this->copy ? 'Ihre Angaben: ' : 'Neue Einsendung: ').$this->form->title,
replyTo: ! $this->copy && $this->person ? [$this->person->email] : [],
);
}
public function content(): Content
{
$includeAnswers = $this->copy || $this->form->setting('mail_answers', true);
return new Content(view: 'forms::mail.submitted', with: [
'portalName' => app(Branding::class)->portalName(),
'answers' => $includeAnswers ? collect($this->submission->data)->map(fn ($answer, $key) => [
'label' => $answer['label'],
'value' => $this->submission->display($key),
])->values()->all() : null,
'resultsUrl' => $this->copy ? null : url('/admin/formulare/'.$this->form->id.'/ergebnisse'),
]);
}
}

View file

@ -0,0 +1,116 @@
<?php
namespace Inhaus\Plugins\Forms\Models;
use App\Models\User;
use App\Support\Permissions\Audiences;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
use Inhaus\Plugins\Forms\FormFields;
/**
* Ein Formular. „fields“ ist die Liste der Felder aus dem Formularbaukasten
* (siehe FormFields), „settings“ Benachrichtigung, Anonymität, Löschfrist u. a.
*/
#[Fillable(['title', 'slug', 'description', 'fields', 'settings', 'is_open', 'closes_at', 'created_by'])]
class Form extends Model
{
protected static function booted(): void
{
static::saving(function (Form $form) {
if (blank($form->slug)) {
$base = Str::slug($form->title, language: 'de') ?: 'formular';
$slug = $base;
for ($i = 2; static::query()->where('slug', $slug)->whereKeyNot($form->id)->exists(); $i++) {
$slug = "{$base}-{$i}";
}
$form->slug = $slug;
}
$form->fields = FormFields::normalize((array) $form->fields);
});
static::deleting(fn (Form $form) => $form->submissions()->with('files')->get()->each->delete());
}
protected function casts(): array
{
return [
'fields' => 'array',
'settings' => 'array',
'is_open' => 'boolean',
'closes_at' => 'datetime',
];
}
/**
* @return array{0: string, 1: int}
*/
public function permissionResource(): array
{
return ['form', $this->id];
}
/**
* @return HasMany<FormSubmission, $this>
*/
public function submissions(): HasMany
{
return $this->hasMany(FormSubmission::class);
}
public function setting(string $key, mixed $default = null): mixed
{
return $this->settings[$key] ?? $default;
}
public function isAnonymous(): bool
{
return (bool) $this->setting('anonymous', false);
}
public function acceptsSubmissions(): bool
{
return $this->is_open && ($this->closes_at === null || $this->closes_at->isFuture());
}
public function url(): string
{
return '/formulare/'.$this->slug;
}
/**
* Kennung für „nur einmal ausfüllen“, ohne bei anonymen Formularen die Person zu speichern.
*/
public function userHash(User $user): string
{
return hash_hmac('sha256', $this->id.':'.$user->id, (string) config('app.key'));
}
public function alreadySubmittedBy(User $user): bool
{
return $this->submissions()
->where(fn ($q) => $q->where('user_hash', $this->userHash($user))->orWhere('user_id', $user->id))
->exists();
}
/**
* @param Builder<Form> $query
*/
public function scopeVisibleTo(Builder $query, ?User $user): void
{
if (! $user?->can('forms.manage')) {
Audiences::constrain($query, 'form', 'forms.id', $user);
}
}
public function isVisibleTo(?User $user): bool
{
return $user?->can('forms.manage') || Audiences::allows('form', $this->id, $user);
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Inhaus\Plugins\Forms\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;
/**
* Hochgeladene Datei zu einem Formular. Liegt außerhalb von public/; ausgeliefert
* nur an Personen mit Zugriff auf die Ergebnisse des Formulars.
*/
#[Fillable(['submission_id', 'field', 'name', 'path', 'mime', 'size'])]
class FormFile extends Model
{
public const DISK = 'local';
protected static function booted(): void
{
static::deleted(fn (FormFile $file) => Storage::disk(self::DISK)->delete($file->path));
}
/**
* @return BelongsTo<FormSubmission, $this>
*/
public function submission(): BelongsTo
{
return $this->belongsTo(FormSubmission::class, 'submission_id');
}
public function url(): string
{
return route('forms.file', $this);
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Inhaus\Plugins\Forms\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
/**
* Ein ausgefülltes Formular. „data“ enthält je Feld Bezeichnung, Typ und Wert –
* so bleiben Ergebnisse lesbar, auch wenn das Formular später geändert wird.
*/
#[Fillable(['form_id', 'user_id', 'user_hash', 'data', 'read_at'])]
class FormSubmission extends Model
{
protected static function booted(): void
{
static::deleting(fn (FormSubmission $submission) => $submission->files->each->delete());
}
protected function casts(): array
{
return ['data' => 'array', 'read_at' => 'datetime'];
}
/**
* @return BelongsTo<Form, $this>
*/
public function form(): BelongsTo
{
return $this->belongsTo(Form::class);
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* @return HasMany<FormFile, $this>
*/
public function files(): HasMany
{
return $this->hasMany(FormFile::class, 'submission_id');
}
/**
* Wert als Text (Listen mit Komma, Ja/Nein, Dateinamen).
*/
public function display(string $key): string
{
$answer = $this->data[$key] ?? null;
if ($answer === null) {
return '';
}
$value = $answer['value'] ?? null;
return match (true) {
($answer['type'] ?? null) === 'checkbox' => $value ? 'Ja' : 'Nein',
($answer['type'] ?? null) === 'file' => implode(', ', array_column((array) $value, 'name')),
($answer['type'] ?? null) === 'date' && is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) => Carbon::parse($value)->format('d.m.Y'),
is_array($value) => implode(', ', $value),
default => (string) $value,
};
}
}

View file

@ -0,0 +1,53 @@
<?php
namespace Inhaus\Plugins\Forms\Policies;
use App\Models\User;
use Inhaus\Plugins\Forms\Models\Form;
/**
* „Formulare verwalten“ gilt für alle Formulare. Je Formular vergibt man
* „Bearbeiten“, „Ergebnisse ansehen“ und „Ergebnisse löschen“ an Rollen –
* z. B. sieht nur die Personalabteilung die Anträge auf Fortbildung.
*/
class FormPolicy
{
public function viewAny(User $user): bool
{
$permissions = $user->permissions();
return $user->can('forms.manage')
|| $permissions->ids('forms.edit', 'form') !== []
|| $permissions->ids('forms.results', 'form') !== [];
}
public function create(User $user): bool
{
return $user->can('forms.manage');
}
public function update(User $user, Form $form): bool
{
return $user->can('forms.manage') || $user->can('forms.edit', ['form', $form->id]);
}
public function delete(User $user, Form $form): bool
{
return $user->can('forms.manage');
}
public function viewResults(User $user, Form $form): bool
{
return $user->can('forms.manage') || $user->can('forms.results', ['form', $form->id]);
}
public function deleteResults(User $user, Form $form): bool
{
return $user->can('forms.manage') || $user->can('forms.results.delete', ['form', $form->id]);
}
public function submit(User $user, Form $form): bool
{
return $form->acceptsSubmissions() && $form->isVisibleTo($user);
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace Inhaus\Plugins\Forms;
use Inhaus\Plugins\Forms\Models\Form;
/**
* Löscht Einsendungen, deren Aufbewahrungsfrist abgelaufen ist (Einstellung je Formular).
*/
class Retention
{
public function purge(): int
{
$deleted = 0;
foreach (Form::query()->get() as $form) {
$days = (int) $form->setting('retention_days', 0);
if ($days <= 0) {
continue;
}
$form->submissions()->with('files')->where('created_at', '<', now()->subDays($days))
->chunkById(100, function ($submissions) use (&$deleted) {
$submissions->each->delete();
$deleted += $submissions->count();
});
}
return $deleted;
}
}

View file

@ -0,0 +1,118 @@
<?php
namespace Inhaus\Plugins\Forms;
use App\Models\User;
use App\Notifications\PortalNotification;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Inhaus\Plugins\Forms\Mail\FormSubmitted;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Forms\Models\FormFile;
use Inhaus\Plugins\Forms\Models\FormSubmission;
use Throwable;
/**
* Speichert eine Einsendung und verschickt die Benachrichtigungen.
*/
class Submissions
{
/**
* @param array<string, mixed> $answers validierte Eingaben
*/
public function store(Form $form, User $user, array $answers): FormSubmission
{
[$data, $uploads] = FormFields::collect($form, $answers);
$anonymous = $form->isAnonymous();
$submission = DB::transaction(function () use ($form, $user, $data, $uploads, $anonymous) {
$submission = $form->submissions()->create([
'user_id' => $anonymous ? null : $user->id,
'user_hash' => $form->setting('once_per_user') ? $form->userHash($user) : null,
'data' => $data,
]);
foreach ($uploads as $key => $files) {
$stored = [];
foreach ($files as $upload) {
$name = Str::limit(preg_replace('/[^\pL\pN ._()\-]+/u', '_', $upload->getClientOriginalName()) ?: 'datei', 180, '');
$file = $submission->files()->create([
'field' => $key,
'name' => $name,
'path' => $upload->storeAs('forms/'.$form->id, Str::random(40).'.'.strtolower($upload->getClientOriginalExtension() ?: 'bin'), FormFile::DISK),
'mime' => $upload->getMimeType(),
'size' => $upload->getSize(),
]);
$stored[] = ['id' => $file->id, 'name' => $name, 'size' => $file->size];
}
$data[$key]['value'] = $stored;
}
$submission->update(['data' => $data]);
return $submission;
});
$this->notify($form, $submission, $user);
return $submission;
}
private function notify(Form $form, FormSubmission $submission, User $user): void
{
$recipients = collect((array) $form->setting('notify_emails', []))
->map(fn ($email) => strtolower(trim((string) $email)))
->filter(fn ($email) => filter_var($email, FILTER_VALIDATE_EMAIL));
$viewers = $form->setting('notify_viewers') ? $this->resultViewers($form) : collect();
try {
foreach ($recipients->merge($viewers->pluck('email'))->unique() as $email) {
Mail::to($email)->queue(new FormSubmitted($form, $submission, $form->isAnonymous() ? null : $user, copy: false));
}
if ($form->setting('send_copy')) {
Mail::to($user->email)->queue(new FormSubmitted($form, $submission, $user, copy: true));
}
} catch (Throwable $e) {
// Die Einsendung ist gespeichert – ein Versandfehler darf sie nicht verwerfen.
Log::error("Formular {$form->id}: Benachrichtigung fehlgeschlagen: ".$e->getMessage());
}
if ($viewers->isNotEmpty()) {
Notification::send($viewers, new PortalNotification(
'Neue Einsendung: '.$form->title,
$form->isAnonymous() ? 'Anonyme Einsendung' : 'Von '.$user->name,
route('filament.admin.resources.formulare.results', ['record' => $form]),
'file-check',
));
}
}
/**
* Personen mit Zugriff auf die Ergebnisse dieses Formulars.
*
* @return Collection<int, User>
*/
public function resultViewers(Form $form): Collection
{
$roleIds = DB::table('grants')
->where(function ($q) use ($form) {
$q->whereIn('ability', ['*', 'forms.manage'])->whereNull('resource_type');
$q->orWhere(fn ($q) => $q->where('ability', 'forms.results')->where('resource_type', 'form')
->where(fn ($q) => $q->whereNull('resource_id')->orWhere('resource_id', $form->id)));
})
->pluck('role_id');
return User::query()->active()
->whereIn('id', DB::table('role_user')->whereIn('role_id', $roleIds)->select('user_id'))
->limit(100)
->get();
}
}

View file

@ -16,6 +16,7 @@ class PageRevision extends Model
'published' => 'Veröffentlicht',
'scheduled' => 'Zeitgesteuert veröffentlicht',
'restored' => 'Wiederhergestellt',
'imported' => 'Importiert',
];
protected function casts(): array

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,
];
}
}