xref: /webtrees/app/Module/UserMessagesModule.php (revision 26684e686fb5ab50ecb57e7e6c6a0a55852d2203)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Module;
19
20use Fisharebest\Webtrees\Auth;
21use Fisharebest\Webtrees\Filter;
22use Fisharebest\Webtrees\Functions\FunctionsDate;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Tree;
25use Fisharebest\Webtrees\User;
26use Illuminate\Database\Capsule\Manager as DB;
27use Symfony\Component\HttpFoundation\RedirectResponse;
28use Symfony\Component\HttpFoundation\Request;
29use Symfony\Component\HttpFoundation\Response;
30
31/**
32 * Class UserMessagesModule
33 */
34class UserMessagesModule extends AbstractModule implements ModuleInterface, ModuleBlockInterface
35{
36    use ModuleBlockTrait;
37
38    /**
39     * How should this module be labelled on tabs, menus, etc.?
40     *
41     * @return string
42     */
43    public function title(): string
44    {
45        /* I18N: Name of a module */
46        return I18N::translate('Messages');
47    }
48
49    /**
50     * A sentence describing what this module does.
51     *
52     * @return string
53     */
54    public function description(): string
55    {
56        /* I18N: Description of the “Messages” module */
57        return I18N::translate('Communicate directly with other users, using private messages.');
58    }
59
60    /**
61     * Delete one or messages belonging to a user.
62     *
63     * @param Request $request
64     * @param Tree    $tree
65     *
66     * @return Response
67     */
68    public function postDeleteMessageAction(Request $request, Tree $tree): Response
69    {
70        $message_ids = (array) $request->get('message_id', []);
71
72        DB::table('message')
73            ->where('user_id', '=', Auth::id())
74            ->whereIn('message_id', $message_ids)
75            ->delete();
76
77        if ($request->get('ctype') === 'user') {
78            $url = route('user-page', ['ged' => $tree->name()]);
79        } else {
80            $url = route('tree-page', ['ged' => $tree->name()]);
81        }
82
83        return new RedirectResponse($url);
84    }
85
86    /**
87     * Generate the HTML content of this block.
88     *
89     * @param Tree     $tree
90     * @param int      $block_id
91     * @param string   $ctype
92     * @param string[] $cfg
93     *
94     * @return string
95     */
96    public function getBlock(Tree $tree, int $block_id, string $ctype = '', array $cfg = []): string
97    {
98        $messages = DB::table('message')
99            ->where('user_id', '=', Auth::id())
100            ->orderByDesc('message_id')
101            ->select(['message_id', 'sender', 'subject', 'body', DB::raw('UNIX_TIMESTAMP(created) AS created')])
102            ->get();
103
104        $users = User::all()->filter(function (User $user) use ($tree): bool {
105            $public_tree  = $tree->getPreference('REQUIRE_AUTHENTICATION') !== '1';
106            $can_see_tree = $public_tree || Auth::accessLevel($tree, $user) <= Auth::PRIV_USER;
107
108            return
109                $user->id() !== Auth::id() &&
110                $user->getPreference('verified_by_admin') &&
111                $can_see_tree &&
112                $user->getPreference('contactmethod') !== 'none';
113        });
114
115        $content = '';
116        if ($users->isNotEmpty()) {
117            $url = route('user-page', ['ged' => $tree->name()]);
118
119            $content .= '<form onsubmit="return $(&quot;#to&quot;).val() !== &quot;&quot;">';
120            $content .= '<input type="hidden" name="route" value="message">';
121            $content .= '<input type="hidden" name="ged" value="' . e($tree->name()) . '">';
122            $content .= '<input type="hidden" name="url" value="' . e($url) . '">';
123            $content .= '<label for="to">' . I18N::translate('Send a message') . '</label>';
124            $content .= '<select id="to" name="to">';
125            $content .= '<option value="">' . I18N::translate('&lt;select&gt;') . '</option>';
126            foreach ($users as $user) {
127                $content .= sprintf('<option value="%1$s">%2$s - %1$s</option>', e($user->getUserName()), e($user->getRealName()));
128            }
129            $content .= '</select>';
130            $content .= '<button type="submit">' . I18N::translate('Send') . '</button><br><br>';
131            $content .= '</form>';
132        }
133        $content .= '<form id="messageform" name="messageform" method="post" action="' . e(route('module', [
134                'action' => 'DeleteMessage',
135                'module' => $this->name(),
136                'ctype'  => $ctype,
137                'ged'    => $tree->name(),
138            ])) . '" data-confirm="' . I18N::translate('Are you sure you want to delete this message? It cannot be retrieved later.') . '" onsubmit="return confirm(this.dataset.confirm);">';
139        $content .= csrf_field();
140
141        if ($messages->isNotEmpty()) {
142            $content .= '<table class="list_table w-100"><tr>';
143            $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>';
144            $content .= '<th class="list_label">' . I18N::translate('Subject') . '</th>';
145            $content .= '<th class="list_label">' . I18N::translate('Date sent') . '</th>';
146            $content .= '<th class="list_label">' . I18N::translate('Email address') . '</th>';
147            $content .= '</tr>';
148            foreach ($messages as $message) {
149                $content .= '<tr>';
150                $content .= '<td class="list_value_wrap center"><input type="checkbox" name="message_id[]" value="' . $message->message_id . '" id="cb_message' . $message->message_id . '"></td>';
151                $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>';
152                $content .= '<td class="list_value_wrap">' . FunctionsDate::formatTimestamp((int) $message->created) . '</td>';
153                $content .= '<td class="list_value_wrap">';
154
155                $user = User::findByIdentifier($message->sender);
156
157                if ($user instanceof User) {
158                    $content .= '<span dir="auto">' . e($user->getRealName()) . '</span> - <span dir="auto">' . $user->getEmail() . '</span>';
159                } else {
160                    $content .= '<a href="mailto:' . e($message->sender) . '">' . e($message->sender) . '</a>';
161                }
162
163                $content .= '</td>';
164                $content .= '</tr>';
165                $content .= '<tr><td class="list_value_wrap" colspan="4"><div id="message' . $message->message_id . '" style="display:none;">';
166                $content .= '<div dir="auto" style="white-space: pre-wrap;">' . Filter::expandUrls($message->body, $tree) . '</div><br>';
167
168                /* I18N: When replying to an email, the subject becomes “RE: <subject>” */
169                if (strpos($message->subject, I18N::translate('RE: ')) !== 0) {
170                    $message->subject = I18N::translate('RE: ') . $message->subject;
171                }
172
173                // If this user still exists, show a reply link.
174                if ($user) {
175                    $reply_url = route('message', [
176                        'to'      => $user->getUserName(),
177                        'subject' => $message->subject,
178                        'ged'     => $tree->name(),
179                    ]);
180
181                    $content .= '<a class="btn btn-primary" href="' . e($reply_url) . '" title="' . I18N::translate('Reply') . '">' . I18N::translate('Reply') . '</a> ';
182                }
183                $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>';
184            }
185            $content .= '</table>';
186            $content .= '<p><button type="submit">' . I18N::translate('Delete selected messages') . '</button></p>';
187        }
188        $content .= '</form>';
189
190        if ($ctype !== '') {
191            $count = $messages->count();
192
193            return view('modules/block-template', [
194                'block'      => str_replace('_', '-', $this->name()),
195                'id'         => $block_id,
196                'config_url' => '',
197                'title'      => I18N::plural('%s message', '%s messages', $count, I18N::number($count)),
198                'content'    => $content,
199            ]);
200        }
201
202        return $content;
203    }
204
205    /** {@inheritdoc} */
206    public function loadAjax(): bool
207    {
208        return false;
209    }
210
211    /** {@inheritdoc} */
212    public function isUserBlock(): bool
213    {
214        return true;
215    }
216
217    /** {@inheritdoc} */
218    public function isGedcomBlock(): bool
219    {
220        return false;
221    }
222
223    /**
224     * Update the configuration for a block.
225     *
226     * @param Request $request
227     * @param int     $block_id
228     *
229     * @return void
230     */
231    public function saveBlockConfiguration(Request $request, int $block_id)
232    {
233    }
234
235    /**
236     * An HTML form to edit block settings
237     *
238     * @param Tree $tree
239     * @param int  $block_id
240     *
241     * @return void
242     */
243    public function editBlockConfiguration(Tree $tree, int $block_id)
244    {
245    }
246}
247