xref: /webtrees/app/Module/UserMessagesModule.php (revision 89f7189b61a494347591c99bdb92afb7d8b66e1b)
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\Filter;
26use Fisharebest\Webtrees\Http\RequestHandlers\MessagePage;
27use Fisharebest\Webtrees\Http\RequestHandlers\MessageSelect;
28use Fisharebest\Webtrees\Http\RequestHandlers\TreePage;
29use Fisharebest\Webtrees\Http\RequestHandlers\UserPage;
30use Fisharebest\Webtrees\I18N;
31use Fisharebest\Webtrees\Services\UserService;
32use Fisharebest\Webtrees\Tree;
33use Fisharebest\Webtrees\User;
34use Illuminate\Database\Capsule\Manager as DB;
35use Illuminate\Support\Str;
36use Psr\Http\Message\ResponseInterface;
37use Psr\Http\Message\ServerRequestInterface;
38use stdClass;
39
40use function assert;
41use function e;
42use function route;
43use function str_starts_with;
44use function view;
45
46/**
47 * Class UserMessagesModule
48 */
49class UserMessagesModule extends AbstractModule implements ModuleBlockInterface
50{
51    use ModuleBlockTrait;
52
53    /**
54     * @var UserService
55     */
56    private $user_service;
57
58    /**
59     * UserMessagesModule constructor.
60     *
61     * @param UserService $user_service
62     */
63    public function __construct(UserService $user_service)
64    {
65        $this->user_service = $user_service;
66    }
67
68    /**
69     * How should this module be identified in the control panel, etc.?
70     *
71     * @return string
72     */
73    public function title(): string
74    {
75        /* I18N: Name of a module */
76        return I18N::translate('Messages');
77    }
78
79    /**
80     * A sentence describing what this module does.
81     *
82     * @return string
83     */
84    public function description(): string
85    {
86        /* I18N: Description of the “Messages” module */
87        return I18N::translate('Communicate directly with other users, using private messages.');
88    }
89
90    /**
91     * Delete one or messages belonging to a user.
92     *
93     * @param ServerRequestInterface $request
94     *
95     * @return ResponseInterface
96     */
97    public function postDeleteMessageAction(ServerRequestInterface $request): ResponseInterface
98    {
99        $tree = $request->getAttribute('tree');
100        assert($tree instanceof Tree);
101
102        $params = (array) $request->getParsedBody();
103
104        $message_ids = $params['message_id'] ?? [];
105
106        DB::table('message')
107            ->where('user_id', '=', Auth::id())
108            ->whereIn('message_id', $message_ids)
109            ->delete();
110
111        if ($request->getQueryParams()['context'] === ModuleBlockInterface::CONTEXT_USER_PAGE) {
112            $url = route(UserPage::class, ['tree' => $tree->name()]);
113        } else {
114            $url = route(TreePage::class, ['tree' => $tree->name()]);
115        }
116
117        return redirect($url);
118    }
119
120    /**
121     * Generate the HTML content of this block.
122     *
123     * @param Tree     $tree
124     * @param int      $block_id
125     * @param string   $context
126     * @param string[] $config
127     *
128     * @return string
129     */
130    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
131    {
132        $messages = DB::table('message')
133            ->where('user_id', '=', Auth::id())
134            ->orderByDesc('message_id')
135            ->get()
136            ->map(static function (stdClass $row): stdClass {
137                $row->created = Carbon::make($row->created);
138
139                return $row;
140            });
141
142        $users = $this->user_service->all()->filter(static function (UserInterface $user) use ($tree): bool {
143            $public_tree  = $tree->getPreference('REQUIRE_AUTHENTICATION') !== '1';
144            $can_see_tree = $public_tree || Auth::accessLevel($tree, $user) <= Auth::PRIV_USER;
145
146            return
147                $user->id() !== Auth::id() &&
148                $user->getPreference(UserInterface::PREF_IS_ACCOUNT_APPROVED) &&
149                $can_see_tree &&
150                $user->getPreference(UserInterface::PREF_CONTACT_METHOD) !== 'none';
151        });
152
153        $content = view('modules/user-messages/user-messages', [
154            'block_id'     => $block_id,
155            'context'      => $context,
156            'messages'     => $messages,
157            'module'       => $this,
158            'tree'         => $tree,
159            'user_service' => $this->user_service,
160            'users'        => $users,
161        ]);
162
163        if ($context !== self::CONTEXT_EMBED) {
164            $count = $messages->count();
165
166            return view('modules/block-template', [
167                'block'      => Str::kebab($this->name()),
168                'id'         => $block_id,
169                'config_url' => '',
170                'title'      => I18N::plural('%s message', '%s messages', $count, I18N::number($count)),
171                'content'    => $content,
172            ]);
173        }
174
175        return $content;
176    }
177
178    /**
179     * Should this block load asynchronously using AJAX?
180     *
181     * Simple blocks are faster in-line, more complex ones can be loaded later.
182     *
183     * @return bool
184     */
185    public function loadAjax(): bool
186    {
187        return false;
188    }
189
190    /**
191     * Can this block be shown on the user’s home page?
192     *
193     * @return bool
194     */
195    public function isUserBlock(): bool
196    {
197        return true;
198    }
199
200    /**
201     * Can this block be shown on the tree’s home page?
202     *
203     * @return bool
204     */
205    public function isTreeBlock(): bool
206    {
207        return false;
208    }
209}
210