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