xref: /webtrees/app/Module/UserMessagesModule.php (revision 342dcecd8628deacd49d86f3247fd77e64bf33c3)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 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 */
16namespace Fisharebest\Webtrees\Module;
17
18use Fisharebest\Webtrees\Auth;
19use Fisharebest\Webtrees\Database;
20use Fisharebest\Webtrees\Filter;
21use Fisharebest\Webtrees\Functions\FunctionsDate;
22use Fisharebest\Webtrees\I18N;
23use Fisharebest\Webtrees\Tree;
24use Fisharebest\Webtrees\User;
25use Symfony\Component\HttpFoundation\RedirectResponse;
26use Symfony\Component\HttpFoundation\Request;
27use Symfony\Component\HttpFoundation\Response;
28
29/**
30 * Class UserMessagesModule
31 */
32class UserMessagesModule extends AbstractModule implements ModuleBlockInterface
33{
34    /** {@inheritdoc} */
35    public function getTitle()
36    {
37        /* I18N: Name of a module */
38        return I18N::translate('Messages');
39    }
40
41    /** {@inheritdoc} */
42    public function getDescription()
43    {
44        /* I18N: Description of the “Messages” module */
45        return I18N::translate('Communicate directly with other users, using private messages.');
46    }
47
48    /**
49     * Delete one or messages belonging to a user.
50     *
51     * @param Request $request
52     * @param Tree    $tree
53     *
54     * @return Response
55     */
56    public function postDeleteMessageAction(Request $request, Tree $tree): Response
57    {
58        $message_ids = (array)$request->get('message_id', []);
59
60        $stmt = Database::prepare("DELETE FROM `##message` WHERE user_id = :user_id AND message_id = :message_id");
61
62        foreach ($message_ids as $message_id) {
63            $stmt->execute([
64                'message_id' => $message_id,
65                'user_id'    => Auth::id(),
66            ]);
67        }
68
69        if ($request->get('ctype') === 'user') {
70            $url = route('user-page', ['ged' => $tree->getName()]);
71        } else {
72            $url = route('tree-page', ['ged' => $tree->getName()]);
73        }
74
75        return new RedirectResponse($url);
76    }
77
78    /**
79     * Generate the HTML content of this block.
80     *
81     * @param Tree     $tree
82     * @param int      $block_id
83     * @param bool     $template
84     * @param string[] $cfg
85     *
86     * @return string
87     */
88    public function getBlock(Tree $tree, int $block_id, bool $template = true, array $cfg = []): string
89    {
90        global $ctype;
91
92        $messages = Database::prepare("SELECT message_id, sender, subject, body, UNIX_TIMESTAMP(created) AS created FROM `##message` WHERE user_id=? ORDER BY message_id DESC")
93            ->execute([Auth::id()])
94            ->fetchAll();
95
96        $count = count($messages);
97        $users = array_filter(User::all(), function (User $user): bool {
98            return $user->getUserId() !== Auth::id() && $user->getPreference('verified_by_admin') && $user->getPreference('contactmethod') !== 'none';
99        });
100
101        $content = '';
102        if (!empty($users)) {
103            $url     = route('user-page', ['ged' => $tree->getName()]);
104            $content .= '<form onsubmit="return $(&quot;#to&quot;).val() !== &quot;&quot;">';
105            $content .= '<input type="hidden" name="route" value="message">';
106            $content .= '<input type="hidden" name="ged" value="' . e($tree->getName()) . '">';
107            $content .= '<input type="hidden" name="url" value="' . e($url) . '">';
108            $content .= '<label for="to">' . I18N::translate('Send a message') . '</label>';
109            $content .= '<select id="to" name="to">';
110            $content .= '<option value="">' . I18N::translate('&lt;select&gt;') . '</option>';
111            foreach ($users as $user) {
112                $content .= sprintf('<option value="%1$s">%2$s - %1$s</option>', e($user->getUserName()), e($user->getRealName()));
113            }
114            $content .= '</select>';
115            $content .= '<button type="submit">' . I18N::translate('Send') . '</button><br><br>';
116            $content .= '</form>';
117        }
118        $content .= '<form id="messageform" name="messageform" method="post" action="' . e(route('module', [
119                'action' => 'DeleteMessage',
120                'module' => $this->getName(),
121                'ctype'  => $ctype,
122                'ged'    => $tree->getName(),
123            ])) . '" data-confirm="' . I18N::translate('Are you sure you want to delete this message? It cannot be retrieved later.') . '" onsubmit="return confirm(this.dataset.confirm);">';
124        $content .= csrf_field();
125
126        if (!empty($messages)) {
127            $content .= '<table class="list_table w-100"><tr>';
128            $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>';
129            $content .= '<th class="list_label">' . I18N::translate('Subject') . '</th>';
130            $content .= '<th class="list_label">' . I18N::translate('Date sent') . '</th>';
131            $content .= '<th class="list_label">' . I18N::translate('Email address') . '</th>';
132            $content .= '</tr>';
133            foreach ($messages as $message) {
134                $content .= '<tr>';
135                $content .= '<td class="list_value_wrap center"><input type="checkbox" name="message_id[]" value="' . $message->message_id . '" id="cb_message' . $message->message_id . '"></td>';
136                $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>';
137                $content .= '<td class="list_value_wrap">' . FunctionsDate::formatTimestamp($message->created + WT_TIMESTAMP_OFFSET) . '</td>';
138                $content .= '<td class="list_value_wrap">';
139                $user    = User::findByIdentifier($message->sender);
140                if ($user) {
141                    $content .= '<span dir="auto">' . e($user->getRealName()) . '</span> - <span dir="auto">' . $user->getEmail() . '</span>';
142                } else {
143                    $content .= '<a href="mailto:' . e($message->sender) . '">' . e($message->sender) . '</a>';
144                }
145                $content .= '</td>';
146                $content .= '</tr>';
147                $content .= '<tr><td class="list_value_wrap" colspan="4"><div id="message' . $message->message_id . '" style="display:none;">';
148                $content .= '<div dir="auto" style="white-space: pre-wrap;">' . Filter::expandUrls($message->body, $tree) . '</div><br>';
149                /* I18N: When replying to an email, the subject becomes “RE: <subject>” */
150                if (strpos($message->subject, I18N::translate('RE: ')) !== 0) {
151                    $message->subject = I18N::translate('RE: ') . $message->subject;
152                }
153
154                // If this user still exists, show a reply link.
155                if ($user) {
156                    $reply_url = route('message', [
157                        'to'      => $user->getUserName(),
158                        'subject' => $message->subject,
159                        'ged'     => $tree->getName(),
160                    ]);
161                    $content   .= '<a class="btn btn-primary" href="' . e($reply_url) . '" title="' . I18N::translate('Reply') . '">' . I18N::translate('Reply') . '</a> ';
162                }
163                $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>';
164            }
165            $content .= '</table>';
166            $content .= '<p><button type="submit">' . I18N::translate('Delete selected messages') . '</button></p>';
167        }
168        $content .= '</form>';
169
170        if ($template) {
171            return view('modules/block-template', [
172                'block'      => str_replace('_', '-', $this->getName()),
173                'id'         => $block_id,
174                'config_url' => '',
175                'title'      => I18N::plural('%s message', '%s messages', $count, I18N::number($count)),
176                'content'    => $content,
177            ]);
178        } else {
179            return $content;
180        }
181    }
182
183    /** {@inheritdoc} */
184    public function loadAjax(): bool
185    {
186        return false;
187    }
188
189    /** {@inheritdoc} */
190    public function isUserBlock(): bool
191    {
192        return true;
193    }
194
195    /** {@inheritdoc} */
196    public function isGedcomBlock(): bool
197    {
198        return false;
199    }
200
201    /**
202     * An HTML form to edit block settings
203     *
204     * @param Tree $tree
205     * @param int  $block_id
206     *
207     * @return void
208     */
209    public function configureBlock(Tree $tree, int $block_id)
210    {
211    }
212}
213