xref: /webtrees/app/Module/UserJournalModule.php (revision 94582e90d3cfca0ccb8293b56de3ad502f9f0f70)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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\DB;
24use Fisharebest\Webtrees\Http\Exceptions\HttpAccessDeniedException;
25use Fisharebest\Webtrees\Http\Exceptions\HttpNotFoundException;
26use Fisharebest\Webtrees\Http\RequestHandlers\UserPage;
27use Fisharebest\Webtrees\I18N;
28use Fisharebest\Webtrees\Registry;
29use Fisharebest\Webtrees\Services\HtmlService;
30use Fisharebest\Webtrees\Tree;
31use Fisharebest\Webtrees\Validator;
32use Illuminate\Database\Query\Expression;
33use Illuminate\Support\Str;
34use Psr\Http\Message\ResponseInterface;
35use Psr\Http\Message\ServerRequestInterface;
36
37use function redirect;
38
39/**
40 * Class UserJournalModule
41 */
42class UserJournalModule extends AbstractModule implements ModuleBlockInterface
43{
44    use ModuleBlockTrait;
45
46    private HtmlService $html_service;
47
48    /**
49     * @param HtmlService $html_service
50     */
51    public function __construct(HtmlService $html_service)
52    {
53        $this->html_service = $html_service;
54    }
55
56    public function description(): string
57    {
58        /* I18N: Description of the “Journal” module */
59        return I18N::translate('A private area to record notes or keep a journal.');
60    }
61
62    /**
63     * Generate the HTML content of this block.
64     *
65     * @param Tree                 $tree
66     * @param int                  $block_id
67     * @param string               $context
68     * @param array<string,string> $config
69     *
70     * @return string
71     */
72    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
73    {
74        $articles = DB::table('news')
75            ->where('user_id', '=', Auth::id())
76            ->orderByDesc('updated')
77            ->get()
78            ->map(static function (object $row): object {
79                $row->updated = Registry::timestampFactory()->fromString($row->updated);
80
81                return $row;
82            });
83
84        $content = view('modules/user_blog/list', [
85            'articles' => $articles,
86            'block_id' => $block_id,
87            'limit'    => 5,
88            'tree'     => $tree,
89        ]);
90
91        if ($context !== self::CONTEXT_EMBED) {
92            return view('modules/block-template', [
93                'block'      => Str::kebab($this->name()),
94                'id'         => $block_id,
95                'config_url' => '',
96                'title'      => $this->title(),
97                'content'    => $content,
98            ]);
99        }
100
101        return $content;
102    }
103
104    /**
105     * How should this module be identified in the control panel, etc.?
106     *
107     * @return string
108     */
109    public function title(): string
110    {
111        /* I18N: Name of a module */
112        return I18N::translate('Journal');
113    }
114
115    /**
116     * Should this block load asynchronously using AJAX?
117     *
118     * Simple blocks are faster in-line, more complex ones can be loaded later.
119     *
120     * @return bool
121     */
122    public function loadAjax(): bool
123    {
124        return false;
125    }
126
127    /**
128     * Can this block be shown on the user’s home page?
129     *
130     * @return bool
131     */
132    public function isUserBlock(): bool
133    {
134        return true;
135    }
136
137    /**
138     * Can this block be shown on the tree’s home page?
139     *
140     * @return bool
141     */
142    public function isTreeBlock(): bool
143    {
144        return false;
145    }
146
147    /**
148     * @param ServerRequestInterface $request
149     *
150     * @return ResponseInterface
151     */
152    public function getEditJournalAction(ServerRequestInterface $request): ResponseInterface
153    {
154        $tree = Validator::attributes($request)->tree();
155
156        if (!Auth::check()) {
157            throw new HttpAccessDeniedException();
158        }
159
160        $news_id = Validator::queryParams($request)->integer('news_id', 0);
161
162        if ($news_id !== 0) {
163            $row = DB::table('news')
164                ->where('news_id', '=', $news_id)
165                ->where('user_id', '=', Auth::id())
166                ->first();
167
168            // Record was deleted before we could read it?
169            if ($row === null) {
170                throw new HttpNotFoundException(I18N::translate('%s does not exist.', 'news_id:' . $news_id));
171            }
172        } else {
173            $row = (object)['body' => '', 'subject' => ''];
174        }
175
176        $title = I18N::translate('Add/edit a journal/news entry');
177
178        return $this->viewResponse('modules/user_blog/edit', [
179            'body'    => $row->body,
180            'news_id' => $news_id,
181            'subject' => $row->subject,
182            'title'   => $title,
183            'tree'    => $tree,
184        ]);
185    }
186
187    /**
188     * @param ServerRequestInterface $request
189     *
190     * @return ResponseInterface
191     */
192    public function postEditJournalAction(ServerRequestInterface $request): ResponseInterface
193    {
194        $tree = Validator::attributes($request)->tree();
195
196        if (!Auth::check()) {
197            throw new HttpAccessDeniedException();
198        }
199
200        $news_id = Validator::queryParams($request)->integer('news_id', 0);
201        $subject = Validator::parsedBody($request)->string('subject');
202        $body    = Validator::parsedBody($request)->string('body');
203
204        $subject = $this->html_service->sanitize($subject);
205        $body    = $this->html_service->sanitize($body);
206
207        if ($news_id !== 0) {
208            DB::table('news')
209                ->where('news_id', '=', $news_id)
210                ->where('user_id', '=', Auth::id())
211                ->update([
212                    'body'    => $body,
213                    'subject' => $subject,
214                    'updated' => new Expression('updated'), // See issue #3208
215                ]);
216        } else {
217            DB::table('news')->insert([
218                'body'    => $body,
219                'subject' => $subject,
220                'user_id' => Auth::id(),
221            ]);
222        }
223
224        $url = route(UserPage::class, ['tree' => $tree->name()]);
225
226        return redirect($url);
227    }
228
229    /**
230     * @param ServerRequestInterface $request
231     *
232     * @return ResponseInterface
233     */
234    public function postDeleteJournalAction(ServerRequestInterface $request): ResponseInterface
235    {
236        $tree    = Validator::attributes($request)->tree();
237        $news_id = Validator::queryParams($request)->integer('news_id');
238
239        DB::table('news')
240            ->where('news_id', '=', $news_id)
241            ->where('user_id', '=', Auth::id())
242            ->delete();
243
244        $url = route(UserPage::class, ['tree' => $tree->name()]);
245
246        return redirect($url);
247    }
248}
249