Gruppen-Plugin 1.0.0

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-27 17:17:10 +00:00
commit 5bdfb8a082
49 changed files with 4679 additions and 0 deletions

382
src/Groups.php Normal file
View file

@ -0,0 +1,382 @@
<?php
namespace Inhaus\Plugins\Gruppen;
use App\Models\User;
use App\Notifications\PortalNotification;
use App\Plugins\PluginAccess;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inhaus\Plugins\Gruppen\Models\Comment;
use Inhaus\Plugins\Gruppen\Models\Group;
use Inhaus\Plugins\Gruppen\Models\Member;
use Inhaus\Plugins\Gruppen\Models\Post;
/**
* Diskussionsgruppen: Zugriff je Art (offen, geschlossen, privat), Mitgliedschaft,
* Beiträge, Kommentare, Reaktionen und Umfragen.
*/
class Groups
{
public const MAX_PINNED = 3;
public const MAX_FILES = 10;
public function __construct(private readonly Files $files) {}
/**
* Was darf die Person in dieser Gruppe?
*
* @return array{member: ?Member, see: bool, read: bool, post: bool, moderate: bool, admin: bool}
*/
public function access(Group $group, User $user): array
{
$member = $group->membership($user);
$active = $member?->isActive() ?? false;
$manager = $user->can('gruppen.manage');
return [
'member' => $member,
'see' => $group->privacy !== 'secret' || $manager || in_array($member?->status, ['active', 'invited'], true),
'read' => $group->privacy === 'open' || $active || $manager,
'post' => $active,
'moderate' => ($member?->canModerate() ?? false) || $manager,
'admin' => ($member?->isAdmin() ?? false) || $manager,
];
}
public function create(User $creator, array $data, ?UploadedFile $cover = null): Group
{
$group = DB::transaction(function () use ($creator, $data) {
$group = Group::query()->create([
'name' => $data['name'],
'slug' => $this->slug($data['name']),
'description' => $data['description'] ?? null,
'privacy' => $data['privacy'],
'created_by' => $creator->id,
'last_activity_at' => now(),
]);
$group->memberships()->create(['user_id' => $creator->id, 'role' => 'admin', 'status' => 'active', 'joined_at' => now()]);
return $group;
});
if ($cover) {
$group->update(['cover_path' => $this->files->storeCover($group->id, $cover)]);
}
$group->refreshCounts();
return $group;
}
/** Beitreten: offen sofort, geschlossen als Anfrage, privat nur mit Einladung */
public function join(Group $group, User $user): string
{
$member = $group->membership($user);
if ($member?->isActive()) {
return 'active';
}
if ($member?->status === 'invited' || $group->privacy === 'open') {
$this->upsert($group, $user, ['status' => 'active', 'joined_at' => now()]);
$group->refreshCounts();
return 'active';
}
abort_if($group->privacy === 'secret', 404);
$this->upsert($group, $user, ['status' => 'pending']);
Notification::send($this->moderators($group), new PortalNotification(
"Beitrittsanfrage für „{$group->name}“",
"{$user->name} möchte beitreten.",
route('gruppen.show', [$group, 'tab' => 'mitglieder'], false),
'users',
));
return 'pending';
}
public function leave(Group $group, User $user): void
{
$member = $group->membership($user);
if (! $member) {
return;
}
$member->delete();
// Letzte Admin-Person weg: die am längsten dabei ist, übernimmt
if (! $group->memberships()->where('status', 'active')->where('role', 'admin')->exists()) {
$group->memberships()->where('status', 'active')->orderBy('joined_at')->first()?->forceFill(['role' => 'admin'])->save();
}
$group->refreshCounts();
}
/**
* Einladen: in offenen Gruppen alle Mitglieder, sonst Admins und Moderation.
*
* @param list<int> $userIds
*/
public function invite(Group $group, User $actor, array $userIds): int
{
$access = $this->access($group, $actor);
abort_unless($access['post'] && ($group->privacy === 'open' || $access['moderate']), 403);
$count = 0;
foreach (User::query()->whereKey(array_slice(array_map('intval', $userIds), 0, 100))->whereKeyNot($actor->id)->get() as $user) {
if (! $user->is_active || ! app(PluginAccess::class)->allows('gruppen', $user)) {
continue;
}
$existing = $group->membership($user);
if ($existing?->isActive() || $existing?->status === 'invited') {
continue;
}
// Wer schon angefragt hat, ist mit der Einladung drin
$this->upsert($group, $user, $existing?->status === 'pending'
? ['status' => 'active', 'joined_at' => now()]
: ['status' => 'invited', 'invited_by' => $actor->id]);
$count++;
$user->notify(new PortalNotification("Einladung in die Gruppe „{$group->name}“", "{$actor->name} lädt Sie ein.", route('gruppen.show', $group, false), 'users'));
}
$group->refreshCounts();
return $count;
}
public function decide(Group $group, User $actor, User $user, bool $accept): void
{
abort_unless($this->access($group, $actor)['moderate'], 403);
$member = $group->membership($user);
abort_unless($member?->status === 'pending', 404);
if ($accept) {
$member->forceFill(['status' => 'active', 'joined_at' => now()])->save();
$user->notify(new PortalNotification("Willkommen in „{$group->name}“", 'Ihre Beitrittsanfrage wurde angenommen.', route('gruppen.show', $group, false), 'users'));
} else {
$member->delete();
}
$group->refreshCounts();
}
public function setRole(Group $group, User $actor, User $user, string $role): void
{
abort_unless($this->access($group, $actor)['admin'] && isset(Member::ROLES[$role]), 403);
$member = $group->membership($user);
abort_unless($member?->isActive(), 404);
if ($role !== 'admin' && $member->role === 'admin' && $group->memberships()->where('role', 'admin')->where('status', 'active')->count() === 1) {
throw ValidationException::withMessages(['role' => 'Eine Gruppe braucht mindestens eine Admin-Person.']);
}
$member->forceFill(['role' => $role])->save();
}
public function removeMember(Group $group, User $actor, User $user): void
{
$access = $this->access($group, $actor);
$member = $group->membership($user);
abort_unless($member && $access['moderate'] && ($access['admin'] || $member->role === 'member'), 403);
$this->leave($group, $user);
}
/**
* @param list<UploadedFile> $files
* @param list<string>|null $pollOptions
*/
public function post(Group $group, User $user, ?string $body, array $files = [], ?array $pollOptions = null, bool $multiple = false): Post
{
abort_unless($this->access($group, $user)['post'], 403);
$body = filled($body) ? trim($body) : null;
$options = $pollOptions ? array_values(array_filter(array_map(fn ($o) => Str::limit(trim((string) $o), 120, ''), $pollOptions))) : [];
if ($pollOptions !== null && count($options) < 2) {
throw ValidationException::withMessages(['poll' => 'Eine Umfrage braucht mindestens zwei Antworten.']);
}
if ($body === null && $files === [] && $options === []) {
throw ValidationException::withMessages(['body' => 'Der Beitrag ist leer.']);
}
$post = $group->posts()->create(['user_id' => $user->id, 'body' => $body, 'poll' => $options ? ['options' => array_slice($options, 0, 10), 'multiple' => $multiple] : null]);
foreach (array_values($files) as $i => $file) {
$this->files->attach($post, $file, $i);
}
$group->forceFill(['last_activity_at' => now()])->save();
$group->refreshCounts();
$this->notifyNewPost($group, $post, $user);
return $post;
}
public function deletePost(Post $post, User $user): void
{
abort_unless($post->user_id === $user->id || $this->access($post->group, $user)['moderate'], 403);
$this->files->deletePost($post);
$post->delete();
$post->group->refreshCounts();
}
public function pin(Post $post, User $user, bool $pinned): void
{
abort_unless($this->access($post->group, $user)['moderate'], 403);
if ($pinned && $post->group->posts()->whereNotNull('pinned_at')->count() >= self::MAX_PINNED) {
throw ValidationException::withMessages(['pin' => 'Höchstens '.self::MAX_PINNED.' Beiträge lassen sich anpinnen.']);
}
$post->forceFill(['pinned_at' => $pinned ? now() : null])->save();
}
public function react(Post $post, User $user, ?string $emoji): void
{
abort_unless($this->access($post->group, $user)['post'], 403);
DB::table('gruppen_reactions')->where(['post_id' => $post->id, 'user_id' => $user->id])->delete();
if ($emoji !== null) {
abort_unless(in_array($emoji, Post::REACTIONS, true), 422);
DB::table('gruppen_reactions')->insert(['post_id' => $post->id, 'user_id' => $user->id, 'emoji' => $emoji]);
}
}
/**
* @param list<int> $options
*/
public function vote(Post $post, User $user, array $options): void
{
abort_unless($post->poll && $this->access($post->group, $user)['post'], 403);
$count = count($post->poll['options']);
$options = array_values(array_unique(array_filter(array_map('intval', $options), fn ($o) => $o >= 0 && $o < $count)));
$options = $post->poll['multiple'] ? $options : array_slice($options, 0, 1);
DB::transaction(function () use ($post, $user, $options) {
DB::table('gruppen_poll_votes')->where(['post_id' => $post->id, 'user_id' => $user->id])->delete();
DB::table('gruppen_poll_votes')->insert(array_map(fn ($o) => ['post_id' => $post->id, 'user_id' => $user->id, 'option' => $o], $options));
});
}
public function comment(Post $post, User $user, string $body, ?int $parentId): Comment
{
abort_unless($this->access($post->group, $user)['post'], 403);
$parent = $parentId ? $post->comments()->find($parentId) : null;
// Antworten hängen immer am obersten Kommentar
$parent = $parent?->parent_id ? $post->comments()->find($parent->parent_id) : $parent;
$comment = $post->comments()->create(['user_id' => $user->id, 'parent_id' => $parent?->id, 'body' => trim($body)]);
$post->forceFill(['comments_count' => $post->comments()->count()])->saveQuietly();
$post->group->forceFill(['last_activity_at' => now()])->save();
$url = route('gruppen.post', [$post->group, $post], false).'#kommentar-'.$comment->id;
$recipients = collect([$post->user, $parent?->user])->filter()->unique('id')->reject(fn (User $u) => $u->is($user) || ! $u->is_active);
foreach ($recipients as $recipient) {
$recipient->notify(new PortalNotification(
$recipient->is($parent?->user) ? "{$user->name} hat Ihnen geantwortet" : "{$user->name} hat Ihren Beitrag kommentiert",
Str::limit($comment->body, 100),
$url,
'message-circle',
));
}
return $comment;
}
public function deleteComment(Comment $comment, User $user): void
{
abort_unless($comment->user_id === $user->id || $this->access($comment->post->group, $user)['moderate'], 403);
$post = $comment->post;
$comment->delete();
$post->forceFill(['comments_count' => $post->comments()->count()])->saveQuietly();
}
public function report(Post $post, ?Comment $comment, User $user, string $reason): void
{
abort_unless($this->access($post->group, $user)['read'], 404);
$created = DB::table('gruppen_reports')->insertOrIgnore([
'group_id' => $post->group_id, 'post_id' => $post->id, 'comment_id' => $comment?->id, 'user_id' => $user->id,
'reason' => $reason, 'created_at' => now(), 'updated_at' => now(),
]);
if ($created) {
Notification::send($this->moderators($post->group)->reject(fn (User $u) => $u->is($user)), new PortalNotification(
($comment ? 'Kommentar' : 'Beitrag')." in „{$post->group->name}“ gemeldet",
Str::limit($reason, 100),
route('gruppen.post', [$post->group, $post], false),
'flag',
));
}
}
/** Beim Besuch: gesehen – ab jetzt wieder benachrichtigen */
public function seen(Group $group, User $user): void
{
$group->memberships()->where('user_id', $user->id)->update(['last_seen_at' => now()]);
}
/**
* @return Collection<int, User>
*/
public function moderators(Group $group): Collection
{
return User::query()->active()->whereIn('id', $group->memberships()->where('status', 'active')->whereIn('role', ['admin', 'moderator'])->pluck('user_id'))->get();
}
/**
* Neue Beiträge: Mitglieder mit „alle Beiträge“ – je Gruppe einmal, bis sie wieder vorbeischauen.
*/
private function notifyNewPost(Group $group, Post $post, User $author): void
{
$members = $group->memberships()->with('user')->where('status', 'active')->where('notify', 'all')->where('user_id', '!=', $author->id)
->where(fn ($q) => $q->whereNull('notified_at')->orWhereColumn('last_seen_at', '>', 'notified_at'))->get();
foreach ($members as $member) {
if (! $member->user?->is_active) {
continue;
}
$member->forceFill(['notified_at' => now()])->save();
$member->user->notify(new PortalNotification(
"Neu in „{$group->name}“",
$author->name.': '.Str::limit($post->body ?: ($post->poll ? 'Umfrage' : 'Fotos/Dateien'), 90),
route('gruppen.post', [$group, $post], false),
'users',
));
}
}
private function upsert(Group $group, User $user, array $values): void
{
$existing = $group->membership($user);
$existing ? $existing->forceFill($values)->save() : $group->memberships()->create(['user_id' => $user->id, 'role' => 'member', ...$values]);
}
private function slug(string $name): string
{
$base = Str::slug($name, language: 'de') ?: 'gruppe';
$slug = $base;
for ($i = 2; Group::query()->where('slug', $slug)->exists(); $i++) {
$slug = "{$base}-{$i}";
}
return $slug;
}
}