Loheide-eu-mitarbeiterplatt.../plugins-core/news/src/NewsPlugin.php
Friederich Loheide 2c96fcce1c
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 5m21s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 4m55s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 4m40s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 4m42s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 7m25s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 7m57s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 6m16s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 5m34s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m14s
Startseite frei gestalten, Neuigkeiten-Block mit Kategorien-Filter (0.26.0)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 09:38:18 +00:00

194 lines
9.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Inhaus\Plugins\News;
use App\Dashboard\Widgets;
use App\Editorial\Editorial;
use App\Media\ImagePaths;
use App\Media\MediaUsages;
use App\Models\User;
use App\Pagebuilder\Blocks;
use App\Pagebuilder\BlockType;
use App\Pagebuilder\Field;
use App\Plugins\Plugin;
use App\Profile\ProfilePanels;
use App\Search\GlobalSearch;
use App\Support\Abilities;
use App\Support\Navigation;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Inhaus\Plugins\News\Http\Resources\NewsPostResource;
use Inhaus\Plugins\News\Models\NewsCategory;
use Inhaus\Plugins\News\Models\NewsComment;
use Inhaus\Plugins\News\Models\NewsPost;
use Inhaus\Plugins\News\Policies\NewsCategoryPolicy;
use Inhaus\Plugins\News\Policies\NewsPostPolicy;
class NewsPlugin extends Plugin
{
public function register(): void
{
$this->app->make(GlobalSearch::class)->add('news', 'Neuigkeiten', 'newspaper', fn (...$args) => app(NewsSearch::class)(...$args), sort: 10);
$this->app->make(Navigation::class)->add('news', 'Neuigkeiten', '/neuigkeiten', active: ['news.index', 'news.show'], sort: 20);
$abilities = $this->app->make(Abilities::class);
$abilities->define('news.manage', 'Neuigkeiten: alle Kategorien verwalten', 'Neuigkeiten');
$abilities->define('news.post.create', 'Beiträge schreiben', 'Neuigkeiten', resource: 'news_category', portal: true);
$abilities->define('news.post.publish', 'Beiträge veröffentlichen', 'Neuigkeiten', resource: 'news_category', portal: true);
$abilities->define('news.comments.moderate', 'Kommentare anderer löschen', 'Neuigkeiten', portal: true);
$abilities->resourceType('news_category', 'Kategorie', fn () => NewsCategory::query()->orderBy('sort')->pluck('name', 'id')->all());
Gate::policy(NewsCategory::class, NewsCategoryPolicy::class);
Gate::policy(NewsPost::class, NewsPostPolicy::class);
$this->registerWidgets($this->app->make(Widgets::class));
// Profilseite: Kommentare der Person – nur zu Beiträgen, die die betrachtende Person sehen darf
$this->app->make(ProfilePanels::class)->add('news.comments', 'news::Comments', 20, function (User $person, User $viewer) {
$query = NewsComment::query()->where('user_id', $person->id)
->whereHas('post', fn ($post) => $post->published()->visibleTo($viewer));
$total = (clone $query)->count();
if ($total === 0) {
return null;
}
return [
'total' => $total,
'comments' => $query->with('post:id,title,slug')->latest()->limit(8)->get()->map(fn (NewsComment $comment) => [
'id' => $comment->id,
'excerpt' => Str::limit($comment->body, 180),
'is_reply' => $comment->parent_id !== null,
'created_at' => $comment->created_at?->toIso8601String(),
'post' => ['title' => $comment->post->title, 'url' => route('news.show', $comment->post).'#kommentar-'.$comment->id],
])->all(),
];
});
$this->registerMediaUsages($this->app->make(MediaUsages::class));
$this->app->make(Editorial::class)->add(
'news',
'Neuigkeiten',
'news::EditorialNews',
10,
fn (User $user) => app(NewsPostPolicy::class)->viewAny($user),
fn (User $user) => EditorialNews::props($user),
);
$this->app->make(Blocks::class)->add(BlockType::make('news.latest', 'Neuigkeiten', 'newspaper', 'dynamic', 'news::LatestNews')
->description('Die neuesten Beiträge – aus allen, ausgewählten oder allen außer bestimmten Kategorien.')
->fields([
Field::text('title', 'Überschrift', 150, 'Neuigkeiten'),
Field::select('filter', 'Kategorien', ['all' => 'Alle Kategorien', 'include' => 'Nur die ausgewählten', 'exclude' => 'Alle außer den ausgewählten'], 'all'),
Field::multiselect('categories', 'Auswahl', fn () => NewsCategory::query()->orderBy('sort')->orderBy('name')->pluck('name', 'slug')->all())
->help('Gilt bei „Nur die ausgewählten“ bzw. „Alle außer den ausgewählten“.'),
Field::number('count', 'Anzahl', 1, 12, 3),
Field::select('layout', 'Darstellung', ['large' => 'Große Vorschau (untereinander)', 'featured' => 'Aufmacher und Liste', 'cards' => 'Kacheln nebeneinander', 'list' => 'Liste'], 'cards'),
Field::text('more_label', 'Link unten (leer = kein Link)', 60, 'Alle Beiträge'),
])
->resolveUsing(function (array $data, ?User $user) {
$slugs = $data['filter'] === 'all' ? [] : $data['categories'];
$posts = NewsPost::query()->published()->visibleTo($user)->with('category')
->when($slugs !== [] && $data['filter'] === 'include', fn ($q) => $q->whereHas('category', fn ($c) => $c->whereIn('slug', $slugs)))
->when($slugs !== [] && $data['filter'] === 'exclude', fn ($q) => $q->where(fn ($q) => $q->whereNull('category_id')->orWhereHas('category', fn ($c) => $c->whereNotIn('slug', $slugs))))
->latest('published_at')->limit($data['count'])->get();
$query = match (true) {
$slugs === [] => '',
$data['filter'] === 'include' && count($slugs) === 1 => '?kategorie='.rawurlencode($slugs[0]),
$data['filter'] === 'include' => '?kategorien='.rawurlencode(implode(',', $slugs)),
default => '?ohne='.rawurlencode(implode(',', $slugs)),
};
return [
'posts' => NewsPostResource::collection($posts)->resolve(),
'more_url' => '/neuigkeiten'.$query,
];
}));
}
/**
* Mediathek „Eingebunden in“: Titelbild, Bilder im Text und – sobald Beiträge
* mit dem Pagebuilder geschrieben werden – Bilder in der Spalte „content“.
*/
private function registerMediaUsages(MediaUsages $usages): void
{
$usages->add('news', 'Neuigkeiten', function (NewsPost $post) {
$base = ['label' => $post->title, 'url' => route('news.editor.edit', $post, false), 'draft' => $post->status !== NewsPost::PUBLISHED];
$entries = [
[...$base, 'context' => 'Titelbild', 'paths' => [$post->cover_path]],
[...$base, 'context' => ImagePaths::HTML_CONTEXT, 'paths' => [...ImagePaths::fromHtml($post->body_html), ...ImagePaths::fromHtml($post->body)]],
];
if (self::hasContentColumn()) {
$content = $post->getAttribute('content');
$content = is_string($content) ? json_decode($content, true) : $content;
foreach (ImagePaths::fromContent(is_array($content) ? $content : null) as $context => $paths) {
$entries[] = [...$base, 'context' => $context, 'paths' => $paths];
}
}
return $entries;
}, fn (callable $each) => NewsPost::query()->chunkById(100, fn ($posts) => $posts->each($each)));
$usages->watch('news', NewsPost::class);
}
private static function hasContentColumn(): bool
{
static $has;
return $has ??= Schema::hasColumn('news_posts', 'content');
}
private function registerWidgets(Widgets $widgets): void
{
// Slider: hervorgehobene Beiträge mit Bild, sonst die neuesten mit Bild.
$widgets->add('news.hero', 'news::Hero', 'hero', sort: 10, props: function (User $user) {
$featured = $this->featured($user);
return $featured->isEmpty() ? null : ['posts' => NewsPostResource::collection($featured)->resolve()];
}, label: 'Slider mit hervorgehobenen Beiträgen', mobileSort: 10);
$widgets->add('news.latest', 'news::Latest', 'feed', sort: 10, props: function (User $user, Request $request) {
$posts = NewsPost::query()->published()->visibleTo($user)->with('category')
->whereKeyNot($this->featured($user)->modelKeys())
->latest('published_at')->limit(4)->get();
return [
'posts' => NewsPostResource::collection($posts)->resolve(),
'canWrite' => $user->can('news.manage'),
];
}, label: 'Neuigkeiten', mobileSort: 20);
$widgets->add('news.areas', 'news::Areas', 'main', sort: 20, props: function (User $user) {
$posts = NewsPost::query()->published()->visibleTo($user)->with('category')
->whereKeyNot($this->featured($user)->modelKeys())
->latest('published_at')->skip(4)->limit(8)->get();
return $posts->isEmpty() ? null : ['posts' => NewsPostResource::collection($posts)->resolve()];
}, label: 'Aktuelles aus den Bereichen', mobileSort: 50);
}
/**
* @return Collection<int, NewsPost>
*/
private function featured(User $user)
{
static $cache = [];
return $cache[$user->id] ??= (function () use ($user) {
$featured = NewsPost::query()->published()->visibleTo($user)->with('category')
->where('is_featured', true)->whereNotNull('cover_path')
->latest('published_at')->limit(5)->get();
return $featured->isNotEmpty() ? $featured : NewsPost::query()->published()->visibleTo($user)->with('category')
->whereNotNull('cover_path')->latest('published_at')->limit(3)->get();
})();
}
}