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