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