xref: /webtrees/app/Module/UserMessagesModule.php (revision d28419ce271b6a24649dc7a43b342296a448f27c)
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) use ($tree): bool {
100            $public_tree = $tree->getPreference('REQUIRE_AUTHENTICATION') !== '1';
101            $can_see_tree = $public_tree || Auth::accessLevel($tree, $user) <= Auth::PRIV_USER;
102
103            return
104                $user->getUserId() !== Auth::id() &&
105                $user->getPreference('verified_by_admin') &&
106                $can_see_tree &&
107                $user->getPreference('contactmethod') !== 'none';
108        });
109
110        $content = '';
111        if (!empty($users)) {
112            $url = route('user-page', ['ged' => $tree->name()]);
113            $content .= '<form onsubmit="return $(&quot;#to&quot;).val() !== &quot;&quot;">';
114            $content .= '<input type="hidden" name="route" value="message">';
115            $content .= '<input type="hidden" name="ged" value="' . e($tree->name()) . '">';
116            $content .= '<input type="hidden" name="url" value="' . e($url) . '">';
117            $content .= '<label for="to">' . I18N::translate('Send a message') . '</label>';
118            $content .= '<select id="to" name="to">';
119            $content .= '<option value="">' . I18N::translate('&lt;select&gt;') . '</option>';
120            foreach ($users as $user) {
121                $content .= sprintf('<option value="%1$s">%2$s - %1$s</option>', e($user->getUserName()), e($user->getRealName()));
122            }
123            $content .= '</select>';
124            $content .= '<button type="submit">' . I18N::translate('Send') . '</button><br><br>';
125            $content .= '</form>';
126        }
127        $content .= '<form id="messageform" name="messageform" method="post" action="' . e(route('module', [
128                'action' => 'DeleteMessage',
129                'module' => $this->getName(),
130                'ctype'  => $ctype,
131                'ged'    => $tree->name(),
132            ])) . '" data-confirm="' . I18N::translate('Are you sure you want to delete this message? It cannot be retrieved later.') . '" onsubmit="return confirm(this.dataset.confirm);">';
133        $content .= csrf_field();
134
135        if (!empty($messages)) {
136            $content .= '<table class="list_table w-100"><tr>';
137            $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>';
138            $content .= '<th class="list_label">' . I18N::translate('Subject') . '</th>';
139            $content .= '<th class="list_label">' . I18N::translate('Date sent') . '</th>';
140            $content .= '<th class="list_label">' . I18N::translate('Email address') . '</th>';
141            $content .= '</tr>';
142            foreach ($messages as $message) {
143                $content .= '<tr>';
144                $content .= '<td class="list_value_wrap center"><input type="checkbox" name="message_id[]" value="' . $message->message_id . '" id="cb_message' . $message->message_id . '"></td>';
145                $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>';
146                $content .= '<td class="list_value_wrap">' . FunctionsDate::formatTimestamp($message->created + WT_TIMESTAMP_OFFSET) . '</td>';
147                $content .= '<td class="list_value_wrap">';
148                $user = User::findByIdentifier($message->sender);
149                if ($user instanceof User) {
150                    $content .= '<span dir="auto">' . e($user->getRealName()) . '</span> - <span dir="auto">' . $user->getEmail() . '</span>';
151                } else {
152                    $content .= '<a href="mailto:' . e($message->sender) . '">' . e($message->sender) . '</a>';
153                }
154                $content .= '</td>';
155                $content .= '</tr>';
156                $content .= '<tr><td class="list_value_wrap" colspan="4"><div id="message' . $message->message_id . '" style="display:none;">';
157                $content .= '<div dir="auto" style="white-space: pre-wrap;">' . Filter::expandUrls($message->body, $tree) . '</div><br>';
158                /* I18N: When replying to an email, the subject becomes “RE: <subject>” */
159                if (strpos($message->subject, I18N::translate('RE: ')) !== 0) {
160                    $message->subject = I18N::translate('RE: ') . $message->subject;
161                }
162
163                // If this user still exists, show a reply link.
164                if ($user) {
165                    $reply_url = route('message', [
166                        'to'      => $user->getUserName(),
167                        'subject' => $message->subject,
168                        'ged'     => $tree->name(),
169                    ]);
170                    $content .= '<a class="btn btn-primary" href="' . e($reply_url) . '" title="' . I18N::translate('Reply') . '">' . I18N::translate('Reply') . '</a> ';
171                }
172                $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>';
173            }
174            $content .= '</table>';
175            $content .= '<p><button type="submit">' . I18N::translate('Delete selected messages') . '</button></p>';
176        }
177        $content .= '</form>';
178
179        if ($template) {
180            return view('modules/block-template', [
181                'block'      => str_replace('_', '-', $this->getName()),
182                'id'         => $block_id,
183                'config_url' => '',
184                'title'      => I18N::plural('%s message', '%s messages', $count, I18N::number($count)),
185                'content'    => $content,
186            ]);
187        }
188
189        return $content;
190    }
191
192    /** {@inheritdoc} */
193    public function loadAjax(): bool
194    {
195        return false;
196    }
197
198    /** {@inheritdoc} */
199    public function isUserBlock(): bool
200    {
201        return true;
202    }
203
204    /** {@inheritdoc} */
205    public function isGedcomBlock(): bool
206    {
207        return false;
208    }
209
210    /**
211     * Update the configuration for a block.
212     *
213     * @param Request $request
214     * @param int     $block_id
215     *
216     * @return void
217     */
218    public function saveBlockConfiguration(Request $request, int $block_id)
219    {
220    }
221
222    /**
223     * An HTML form to edit block settings
224     *
225     * @param Tree $tree
226     * @param int  $block_id
227     *
228     * @return void
229     */
230    public function editBlockConfiguration(Tree $tree, int $block_id)
231    {
232    }
233}
234