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