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