xref: /webtrees/app/Module/UserMessagesModule.php (revision 06a438b41c4b328354bcb5bd8d8d578a3a78f995)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2020 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\Contracts\UserInterface;
25use Fisharebest\Webtrees\Filter;
26use Fisharebest\Webtrees\Http\RequestHandlers\MessagePage;
27use Fisharebest\Webtrees\Http\RequestHandlers\MessageSelect;
28use Fisharebest\Webtrees\Http\RequestHandlers\TreePage;
29use Fisharebest\Webtrees\Http\RequestHandlers\UserPage;
30use Fisharebest\Webtrees\I18N;
31use Fisharebest\Webtrees\Services\UserService;
32use Fisharebest\Webtrees\Tree;
33use Fisharebest\Webtrees\User;
34use Illuminate\Database\Capsule\Manager as DB;
35use Illuminate\Support\Str;
36use Psr\Http\Message\ResponseInterface;
37use Psr\Http\Message\ServerRequestInterface;
38use stdClass;
39
40use function assert;
41use function e;
42use function route;
43use function str_starts_with;
44use function view;
45
46/**
47 * Class UserMessagesModule
48 */
49class UserMessagesModule extends AbstractModule implements ModuleBlockInterface
50{
51    use ModuleBlockTrait;
52
53    /**
54     * @var UserService
55     */
56    private $user_service;
57
58    /**
59     * UserMessagesModule constructor.
60     *
61     * @param UserService $user_service
62     */
63    public function __construct(UserService $user_service)
64    {
65        $this->user_service = $user_service;
66    }
67
68    /**
69     * How should this module be identified in the control panel, etc.?
70     *
71     * @return string
72     */
73    public function title(): string
74    {
75        /* I18N: Name of a module */
76        return I18N::translate('Messages');
77    }
78
79    /**
80     * A sentence describing what this module does.
81     *
82     * @return string
83     */
84    public function description(): string
85    {
86        /* I18N: Description of the “Messages” module */
87        return I18N::translate('Communicate directly with other users, using private messages.');
88    }
89
90    /**
91     * Delete one or messages belonging to a user.
92     *
93     * @param ServerRequestInterface $request
94     *
95     * @return ResponseInterface
96     */
97    public function postDeleteMessageAction(ServerRequestInterface $request): ResponseInterface
98    {
99        $tree = $request->getAttribute('tree');
100        assert($tree instanceof Tree);
101
102        $params = (array) $request->getParsedBody();
103
104        $message_ids = $params['message_id'] ?? [];
105
106        DB::table('message')
107            ->where('user_id', '=', Auth::id())
108            ->whereIn('message_id', $message_ids)
109            ->delete();
110
111        if ($request->getQueryParams()['context'] === ModuleBlockInterface::CONTEXT_USER_PAGE) {
112            $url = route(UserPage::class, ['tree' => $tree->name()]);
113        } else {
114            $url = route(TreePage::class, ['tree' => $tree->name()]);
115        }
116
117        return redirect($url);
118    }
119
120    /**
121     * Generate the HTML content of this block.
122     *
123     * @param Tree     $tree
124     * @param int      $block_id
125     * @param string   $context
126     * @param string[] $config
127     *
128     * @return string
129     */
130    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
131    {
132        $messages = DB::table('message')
133            ->where('user_id', '=', Auth::id())
134            ->orderByDesc('message_id')
135            ->get()
136            ->map(static function (stdClass $row): stdClass {
137                $row->created = Carbon::make($row->created);
138
139                return $row;
140            });
141
142        $users = $this->user_service->all()->filter(static function (UserInterface $user) use ($tree): bool {
143            $public_tree  = $tree->getPreference('REQUIRE_AUTHENTICATION') !== '1';
144            $can_see_tree = $public_tree || Auth::accessLevel($tree, $user) <= Auth::PRIV_USER;
145
146            return
147                $user->id() !== Auth::id() &&
148                $user->getPreference(User::PREF_IS_ACCOUNT_APPROVED) &&
149                $can_see_tree &&
150                $user->getPreference(User::PREF_CONTACT_METHOD) !== 'none';
151        });
152
153        $content = '';
154        if ($users->isNotEmpty()) {
155            $url = route(UserPage::class, ['tree' => $tree->name()]);
156
157            $content .= '<form method="post" action="' . e(route(MessageSelect::class, ['tree' => $tree->name()])) . '">';
158            $content .= csrf_field();
159            $content .= '<input type="hidden" name="url" value="' . e($url) . '">';
160            $content .= '<label for="to">' . I18N::translate('Send a message') . '</label>';
161            $content .= '<select id="to" name="to" required>';
162            $content .= '<option value="">' . I18N::translate('&lt;select&gt;') . '</option>';
163            foreach ($users as $user) {
164                $content .= sprintf('<option value="%1$s">%2$s - %1$s</option>', e($user->userName()), e($user->realName()));
165            }
166            $content .= '</select>';
167            $content .= '<button type="submit">' . I18N::translate('Send') . '</button><br><br>';
168            $content .= '</form>';
169        }
170        $content .= '<form method="post" action="' . e(route('module', [
171                'action'  => 'DeleteMessage',
172                'module'  => $this->name(),
173                'context' => $context,
174                'tree'     => $tree->name(),
175            ])) . '" data-confirm="' . I18N::translate('Are you sure you want to delete this message? It cannot be retrieved later.') . '" onsubmit="return confirm(this.dataset.confirm);" id="messageform" name="messageform">';
176        $content .= csrf_field();
177
178        if ($messages->isNotEmpty()) {
179            $content .= '<div class="table-responsive">';
180            $content .= '<table class="table table-sm w-100"><tr>';
181            $content .= '<th class="list_label">' . I18N::translate('Delete') . '<br><a href="#" onclick="$(\'#block-' . $block_id . ' :checkbox\').prop(\'checked\', true); return false;">' . I18N::translate('All') . '</a></th>';
182            $content .= '<th class="list_label">' . I18N::translate('Subject') . '</th>';
183            $content .= '<th class="list_label">' . I18N::translate('Date sent') . '</th>';
184            $content .= '<th class="list_label">' . I18N::translate('Email address') . '</th>';
185            $content .= '</tr>';
186            foreach ($messages as $message) {
187                $content .= '<tr>' .
188                    '<td class="list_value_wrap center"><input type="checkbox" name="message_id[]" value="' . $message->message_id . '" id="cb_message' . $message->message_id . '"></td>' .
189                    '<td class="list_value_wrap">' .
190                    '<a href="#message' . $message->message_id . '" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="message' . $message->message_id . '">' .
191                    view('icons/expand') .
192                    view('icons/collapse') .
193                    '<b dir="auto">' . e($message->subject) . '</b>' .
194                    '</a></td>' .
195                    '<td class="list_value_wrap">' . view('components/datetime', ['timestamp' => $message->created]) . '</td>' .
196                    '<td class="list_value_wrap">';
197
198                $user = $this->user_service->findByIdentifier($message->sender);
199
200                if ($user instanceof User) {
201                    $content .= '<span dir="auto">' . e($user->realName()) . '</span> - <span dir="auto">' . $user->email() . '</span>';
202                } else {
203                    $content .= '<a href="mailto:' . e($message->sender) . '">' . e($message->sender) . '</a>';
204                }
205
206                $content .= '</td>';
207                $content .= '</tr>';
208                $content .= '<tr><td class="list_value_wrap" colspan="4"><div id="message' . $message->message_id . '" class="collapse">';
209                $content .= '<div dir="auto" style="white-space: pre-wrap;">' . Filter::expandUrls($message->body, $tree) . '</div><br>';
210
211                /* I18N: When replying to an email, the subject becomes “RE: <subject>” */
212                if (!str_starts_with($message->subject, I18N::translate('RE: '))) {
213                    $message->subject = I18N::translate('RE: ') . $message->subject;
214                }
215
216                // If this user still exists, show a reply link.
217                if ($user instanceof User) {
218                    $reply_url = route(MessagePage::class, [
219                        'subject' => $message->subject,
220                        'to'      => $user->userName(),
221                        'tree'    => $tree->name(),
222                        'url'     => route(UserPage::class, ['tree' => $tree->name()]),
223                    ]);
224
225                    $content .= '<a class="btn btn-primary" href="' . e($reply_url) . '" title="' . I18N::translate('Reply') . '">' . I18N::translate('Reply') . '</a> ';
226                }
227                $content .= '<button type="button" class="btn btn-danger" data-confirm="' . I18N::translate('Are you sure you want to delete this message? It cannot be retrieved later.') . '" onclick="if (confirm(this.dataset.confirm)) {$(\'#messageform :checkbox\').prop(\'checked\', false); $(\'#cb_message' . $message->message_id . '\').prop(\'checked\', true); document.messageform.submit();}">' . I18N::translate('Delete') . '</button></div></td></tr>';
228            }
229            $content .= '</table>';
230            $content .= '</div>';
231            $content .= '<p><button type="submit">' . I18N::translate('Delete selected messages') . '</button></p>';
232        }
233        $content .= '</form>';
234
235        if ($context !== self::CONTEXT_EMBED) {
236            $count = $messages->count();
237
238            return view('modules/block-template', [
239                'block'      => Str::kebab($this->name()),
240                'id'         => $block_id,
241                'config_url' => '',
242                'title'      => I18N::plural('%s message', '%s messages', $count, I18N::number($count)),
243                'content'    => $content,
244            ]);
245        }
246
247        return $content;
248    }
249
250    /**
251     * Should this block load asynchronously using AJAX?
252     *
253     * Simple blocks are faster in-line, more complex ones can be loaded later.
254     *
255     * @return bool
256     */
257    public function loadAjax(): bool
258    {
259        return false;
260    }
261
262    /**
263     * Can this block be shown on the user’s home page?
264     *
265     * @return bool
266     */
267    public function isUserBlock(): bool
268    {
269        return true;
270    }
271
272    /**
273     * Can this block be shown on the tree’s home page?
274     *
275     * @return bool
276     */
277    public function isTreeBlock(): bool
278    {
279        return false;
280    }
281}
282