xref: /webtrees/app/Module/UserMessagesModule.php (revision f70bcff589628705e50ed72a6fc6cbad68558677)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\Carbon;
24use Fisharebest\Webtrees\Contracts\UserInterface;
25use Fisharebest\Webtrees\Http\RequestHandlers\TreePage;
26use Fisharebest\Webtrees\Http\RequestHandlers\UserPage;
27use Fisharebest\Webtrees\I18N;
28use Fisharebest\Webtrees\Services\UserService;
29use Fisharebest\Webtrees\Tree;
30use Illuminate\Database\Capsule\Manager as DB;
31use Illuminate\Support\Str;
32use Psr\Http\Message\ResponseInterface;
33use Psr\Http\Message\ServerRequestInterface;
34
35use function assert;
36use function route;
37use function view;
38
39/**
40 * Class UserMessagesModule
41 */
42class UserMessagesModule extends AbstractModule implements ModuleBlockInterface
43{
44    use ModuleBlockTrait;
45
46    /**
47     * @var UserService
48     */
49    private $user_service;
50
51    /**
52     * UserMessagesModule constructor.
53     *
54     * @param UserService $user_service
55     */
56    public function __construct(UserService $user_service)
57    {
58        $this->user_service = $user_service;
59    }
60
61    /**
62     * How should this module be identified in the control panel, etc.?
63     *
64     * @return string
65     */
66    public function title(): string
67    {
68        /* I18N: Name of a module */
69        return I18N::translate('Messages');
70    }
71
72    /**
73     * A sentence describing what this module does.
74     *
75     * @return string
76     */
77    public function description(): string
78    {
79        /* I18N: Description of the “Messages” module */
80        return I18N::translate('Communicate directly with other users, using private messages.');
81    }
82
83    /**
84     * Delete one or messages belonging to a user.
85     *
86     * @param ServerRequestInterface $request
87     *
88     * @return ResponseInterface
89     */
90    public function postDeleteMessageAction(ServerRequestInterface $request): ResponseInterface
91    {
92        $tree = $request->getAttribute('tree');
93        assert($tree instanceof Tree);
94
95        $params = (array) $request->getParsedBody();
96
97        $message_ids = $params['message_id'] ?? [];
98
99        DB::table('message')
100            ->where('user_id', '=', Auth::id())
101            ->whereIn('message_id', $message_ids)
102            ->delete();
103
104        if ($request->getQueryParams()['context'] === ModuleBlockInterface::CONTEXT_USER_PAGE) {
105            $url = route(UserPage::class, ['tree' => $tree->name()]);
106        } else {
107            $url = route(TreePage::class, ['tree' => $tree->name()]);
108        }
109
110        return redirect($url);
111    }
112
113    /**
114     * Generate the HTML content of this block.
115     *
116     * @param Tree          $tree
117     * @param int           $block_id
118     * @param string        $context
119     * @param array<string> $config
120     *
121     * @return string
122     */
123    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
124    {
125        $messages = DB::table('message')
126            ->where('user_id', '=', Auth::id())
127            ->orderByDesc('message_id')
128            ->get()
129            ->map(static function (object $row): object {
130                $row->created = Carbon::make($row->created);
131
132                return $row;
133            });
134
135        $users = $this->user_service->all()->filter(static function (UserInterface $user) use ($tree): bool {
136            $public_tree  = $tree->getPreference('REQUIRE_AUTHENTICATION') !== '1';
137            $can_see_tree = $public_tree || Auth::accessLevel($tree, $user) <= Auth::PRIV_USER;
138
139            return
140                $user->id() !== Auth::id() &&
141                $user->getPreference(UserInterface::PREF_IS_ACCOUNT_APPROVED) &&
142                $can_see_tree &&
143                $user->getPreference(UserInterface::PREF_CONTACT_METHOD) !== 'none';
144        });
145
146        $content = view('modules/user-messages/user-messages', [
147            'block_id'     => $block_id,
148            'context'      => $context,
149            'messages'     => $messages,
150            'module'       => $this,
151            'tree'         => $tree,
152            'user_service' => $this->user_service,
153            'users'        => $users,
154        ]);
155
156        if ($context !== self::CONTEXT_EMBED) {
157            $count = $messages->count();
158
159            return view('modules/block-template', [
160                'block'      => Str::kebab($this->name()),
161                'id'         => $block_id,
162                'config_url' => '',
163                'title'      => I18N::plural('%s message', '%s messages', $count, I18N::number($count)),
164                'content'    => $content,
165            ]);
166        }
167
168        return $content;
169    }
170
171    /**
172     * Should this block load asynchronously using AJAX?
173     *
174     * Simple blocks are faster in-line, more complex ones can be loaded later.
175     *
176     * @return bool
177     */
178    public function loadAjax(): bool
179    {
180        return false;
181    }
182
183    /**
184     * Can this block be shown on the user’s home page?
185     *
186     * @return bool
187     */
188    public function isUserBlock(): bool
189    {
190        return true;
191    }
192
193    /**
194     * Can this block be shown on the tree’s home page?
195     *
196     * @return bool
197     */
198    public function isTreeBlock(): bool
199    {
200        return false;
201    }
202}
203