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