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