xref: /webtrees/app/Module/UserJournalModule.php (revision fcfa147e10aaa6c7ff580c29bd6e5b88666befc1)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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 <http://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\I18N;
25use Fisharebest\Webtrees\Services\HtmlService;
26use Fisharebest\Webtrees\Tree;
27use Illuminate\Database\Capsule\Manager as DB;
28use Illuminate\Support\Str;
29use InvalidArgumentException;
30use Psr\Http\Message\ResponseInterface;
31use Psr\Http\Message\ServerRequestInterface;
32use stdClass;
33use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
34
35use function assert;
36
37/**
38 * Class UserJournalModule
39 */
40class UserJournalModule extends AbstractModule implements ModuleBlockInterface
41{
42    use ModuleBlockTrait;
43
44    /** @var HtmlService */
45    private $html_service;
46
47    /**
48     * HtmlBlockModule bootstrap.
49     *
50     * @param HtmlService $html_service
51     */
52    public function boot(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 “Journal” module */
65        return I18N::translate('A private area to record notes or keep a journal.');
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 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('user_id', '=', Auth::id())
82            ->orderByDesc('updated')
83            ->get()
84            ->map(static function (stdClass $row): stdClass {
85                $row->updated = Carbon::make($row->updated);
86
87                return $row;
88            });
89
90        $content = view('modules/user_blog/list', [
91            'articles' => $articles,
92            'block_id' => $block_id,
93            'limit'    => 5,
94        ]);
95
96        if ($context !== self::CONTEXT_EMBED) {
97            return view('modules/block-template', [
98                'block'      => Str::kebab($this->name()),
99                'id'         => $block_id,
100                'config_url' => '',
101                'title'      => $this->title(),
102                'content'    => $content,
103            ]);
104        }
105
106        return $content;
107    }
108
109    /**
110     * How should this module be identified in the control panel, etc.?
111     *
112     * @return string
113     */
114    public function title(): string
115    {
116        /* I18N: Name of a module */
117        return I18N::translate('Journal');
118    }
119
120    /**
121     * Should this block load asynchronously using AJAX?
122     *
123     * Simple blocks are faster in-line, more complex ones can be loaded later.
124     *
125     * @return bool
126     */
127    public function loadAjax(): bool
128    {
129        return false;
130    }
131
132    /**
133     * Can this block be shown on the user’s home page?
134     *
135     * @return bool
136     */
137    public function isUserBlock(): bool
138    {
139        return true;
140    }
141
142    /**
143     * Can this block be shown on the tree’s home page?
144     *
145     * @return bool
146     */
147    public function isTreeBlock(): bool
148    {
149        return false;
150    }
151
152    /**
153     * @param ServerRequestInterface $request
154     *
155     * @return ResponseInterface
156     */
157    public function getEditJournalAction(ServerRequestInterface $request): ResponseInterface
158    {
159        if (!Auth::check()) {
160            throw new AccessDeniedHttpException();
161        }
162
163        $news_id = $request->getQueryParams()['news_id'] ?? '';
164
165        if ($news_id !== '') {
166            $row = DB::table('news')
167                ->where('news_id', '=', $news_id)
168                ->where('user_id', '=', Auth::id())
169                ->first();
170        } else {
171            $row = (object) [
172                'body'    => '',
173                'subject' => '',
174            ];
175        }
176
177        $title = I18N::translate('Add/edit a journal/news entry');
178
179        return $this->viewResponse('modules/user_blog/edit', [
180            'body'    => $row->body,
181            'news_id' => $news_id,
182            'subject' => $row->subject,
183            'title'   => $title,
184        ]);
185    }
186
187    /**
188     * @param ServerRequestInterface $request
189     *
190     * @return ResponseInterface
191     */
192    public function postEditJournalAction(ServerRequestInterface $request): ResponseInterface
193    {
194        $tree = $request->getAttribute('tree');
195        assert($tree instanceof Tree, new InvalidArgumentException());
196
197        if (!Auth::check()) {
198            throw new AccessDeniedHttpException();
199        }
200
201        $news_id = $request->getQueryParams()['news_id'] ?? '';
202        $subject = $request->getParsedBody()['subject'];
203        $body    = $request->getParsedBody()['body'];
204
205        $subject = $this->html_service->sanitize($subject);
206        $body    = $this->html_service->sanitize($body);
207
208        if ($news_id !== '') {
209            DB::table('news')
210                ->where('news_id', '=', $news_id)
211                ->where('user_id', '=', Auth::id())
212                ->update([
213                    'body'    => $body,
214                    'subject' => $subject,
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('user-page', ['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    = $request->getAttribute('tree');
237        $news_id = $request->getQueryParams()['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('user-page', ['tree' => $tree->name()]);
245
246        return redirect($url);
247    }
248}
249