xref: /webtrees/app/Module/FamilyTreeNewsModule.php (revision 2ebcf907ed34213f816592af04e6c160335d6311)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\Carbon;
24use Fisharebest\Webtrees\Http\Exceptions\HttpAccessDeniedException;
25use Fisharebest\Webtrees\Http\RequestHandlers\TreePage;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Services\HtmlService;
28use Fisharebest\Webtrees\Tree;
29use Illuminate\Database\Capsule\Manager as DB;
30use Illuminate\Database\Query\Expression;
31use Illuminate\Support\Str;
32use Psr\Http\Message\ResponseInterface;
33use Psr\Http\Message\ServerRequestInterface;
34
35use function assert;
36
37/**
38 * Class FamilyTreeNewsModule
39 */
40class FamilyTreeNewsModule extends AbstractModule implements ModuleBlockInterface
41{
42    use ModuleBlockTrait;
43
44    /** @var HtmlService */
45    private $html_service;
46
47    /**
48     * HtmlBlockModule constructor.
49     *
50     * @param HtmlService $html_service
51     */
52    public function __construct(HtmlService $html_service)
53    {
54        $this->html_service = $html_service;
55    }
56
57    /**
58     * A sentence describing what this module does.
59     *
60     * @return string
61     */
62    public function description(): string
63    {
64        /* I18N: Description of the “News” module */
65        return I18N::translate('Family news and site announcements.');
66    }
67
68    /**
69     * Generate the HTML content of this block.
70     *
71     * @param Tree          $tree
72     * @param int           $block_id
73     * @param string        $context
74     * @param array<string> $config
75     *
76     * @return string
77     */
78    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
79    {
80        $articles = DB::table('news')
81            ->where('gedcom_id', '=', $tree->id())
82            ->orderByDesc('updated')
83            ->get()
84            ->map(static function (object $row): object {
85                $row->updated = Carbon::make($row->updated);
86
87                return $row;
88            });
89
90        $content = view('modules/gedcom_news/list', [
91            'articles' => $articles,
92            'block_id' => $block_id,
93            'limit'    => 5,
94            'tree'     => $tree,
95        ]);
96
97        if ($context !== self::CONTEXT_EMBED) {
98            return view('modules/block-template', [
99                'block'      => Str::kebab($this->name()),
100                'id'         => $block_id,
101                'config_url' => '',
102                'title'      => $this->title(),
103                'content'    => $content,
104            ]);
105        }
106
107        return $content;
108    }
109
110    /**
111     * How should this module be identified in the control panel, etc.?
112     *
113     * @return string
114     */
115    public function title(): string
116    {
117        /* I18N: Name of a module */
118        return I18N::translate('News');
119    }
120
121    /**
122     * Should this block load asynchronously using AJAX?
123     *
124     * Simple blocks are faster in-line, more complex ones can be loaded later.
125     *
126     * @return bool
127     */
128    public function loadAjax(): bool
129    {
130        return false;
131    }
132
133    /**
134     * Can this block be shown on the user’s home page?
135     *
136     * @return bool
137     */
138    public function isUserBlock(): bool
139    {
140        return false;
141    }
142
143    /**
144     * Can this block be shown on the tree’s home page?
145     *
146     * @return bool
147     */
148    public function isTreeBlock(): bool
149    {
150        return true;
151    }
152
153    /**
154     * @param ServerRequestInterface $request
155     *
156     * @return ResponseInterface
157     */
158    public function getEditNewsAction(ServerRequestInterface $request): ResponseInterface
159    {
160        $tree = $request->getAttribute('tree');
161        assert($tree instanceof Tree);
162
163        if (!Auth::isManager($tree)) {
164            throw new HttpAccessDeniedException();
165        }
166
167        $news_id = $request->getQueryParams()['news_id'] ?? '';
168
169        if ($news_id !== '') {
170            $row = DB::table('news')
171                ->where('news_id', '=', $news_id)
172                ->where('gedcom_id', '=', $tree->id())
173                ->first();
174        } else {
175            $row = (object) [
176                'body'    => '',
177                'subject' => '',
178            ];
179        }
180
181        $title = I18N::translate('Add/edit a journal/news entry');
182
183        return $this->viewResponse('modules/gedcom_news/edit', [
184            'body'    => $row->body,
185            'news_id' => $news_id,
186            'subject' => $row->subject,
187            'title'   => $title,
188            'tree'    => $tree,
189        ]);
190    }
191
192    /**
193     * @param ServerRequestInterface $request
194     *
195     * @return ResponseInterface
196     */
197    public function postEditNewsAction(ServerRequestInterface $request): ResponseInterface
198    {
199        $tree = $request->getAttribute('tree');
200        assert($tree instanceof Tree);
201
202        if (!Auth::isManager($tree)) {
203            throw new HttpAccessDeniedException();
204        }
205
206        $news_id = $request->getQueryParams()['news_id'] ?? '';
207
208        $params = (array) $request->getParsedBody();
209
210        $subject = $params['subject'];
211        $body    = $params['body'];
212
213        $subject = $this->html_service->sanitize($subject);
214        $body    = $this->html_service->sanitize($body);
215
216        if ($news_id > 0) {
217            DB::table('news')
218                ->where('news_id', '=', $news_id)
219                ->where('gedcom_id', '=', $tree->id())
220                ->update([
221                    'body'    => $body,
222                    'subject' => $subject,
223                    'updated' => new Expression('updated'), // See issue #3208
224                ]);
225        } else {
226            DB::table('news')->insert([
227                'body'      => $body,
228                'subject'   => $subject,
229                'gedcom_id' => $tree->id(),
230            ]);
231        }
232
233        $url = route(TreePage::class, ['tree' => $tree->name()]);
234
235        return redirect($url);
236    }
237
238    /**
239     * @param ServerRequestInterface $request
240     *
241     * @return ResponseInterface
242     */
243    public function postDeleteNewsAction(ServerRequestInterface $request): ResponseInterface
244    {
245        $tree = $request->getAttribute('tree');
246        assert($tree instanceof Tree);
247
248        $news_id = $request->getQueryParams()['news_id'];
249
250        if (!Auth::isManager($tree)) {
251            throw new HttpAccessDeniedException();
252        }
253
254        DB::table('news')
255            ->where('news_id', '=', $news_id)
256            ->where('gedcom_id', '=', $tree->id())
257            ->delete();
258
259        $url = route(TreePage::class, ['tree' => $tree->name()]);
260
261        return redirect($url);
262    }
263}
264