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