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