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