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