summaryrefslogtreecommitdiff
path: root/app/Services/MessageService.php
blob: ed8a123bbce16baf97a68ed5989030661c926b77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
<?php

/**
 * webtrees: online genealogy
 * Copyright (C) 2026 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

declare(strict_types=1);

namespace Fisharebest\Webtrees\Services;

use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\Contracts\UserInterface;
use Fisharebest\Webtrees\DB;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Registry;
use Fisharebest\Webtrees\SiteUser;
use Fisharebest\Webtrees\Tree;
use Fisharebest\Webtrees\User;
use Illuminate\Support\Collection;

use function array_filter;
use function in_array;
use function view;

/**
 * Send messages between users and from visitors to the site.
 */
class MessageService
{
    // Users can be contacted by various methods
    public const string CONTACT_METHOD_INTERNAL           = 'messaging';
    public const string CONTACT_METHOD_INTERNAL_AND_EMAIL = 'messaging2';
    public const string CONTACT_METHOD_EMAIL              = 'messaging3';
    public const string CONTACT_METHOD_MAILTO             = 'mailto';
    public const string CONTACT_METHOD_NONE               = 'none';

    private const string BROADCAST_ALL   = 'all';
    private const string BROADCAST_NEVER = 'never';
    private const string BROADCAST_GONE  = 'gone';

    public function __construct(
        private readonly EmailService $email_service,
        private readonly UserService $user_service,
    ) {
    }

    /**
     * Contact messages can only be sent to the designated contacts
     *
     * @param Tree $tree
     *
     * @return array<UserInterface>
     */
    public function validContacts(Tree $tree): array
    {
        $contacts = [
            $this->user_service->find($tree->contactUserId()),
            $this->user_service->find($tree->supportUserId()),
        ];

        return array_filter($contacts);
    }

    /**
     * Add a message to a user's inbox, send it to them via email, or both.
     *
     * @param UserInterface $sender
     * @param UserInterface $recipient
     * @param string        $subject
     * @param string        $body
     * @param string        $url
     * @param string        $ip
     *
     * @return bool
     */
    public function deliverMessage(UserInterface $sender, UserInterface $recipient, string $subject, string $body, string $url, string $ip): bool
    {
        $success = true;

        // Temporarily switch to the recipient's language
        $old_language = I18N::languageTag();
        I18N::init($recipient->getPreference(UserInterface::PREF_LANGUAGE, 'en-US'));

        $body_text = view('emails/message-user-text', [
            'sender'    => $sender,
            'recipient' => $recipient,
            'message'   => $body,
            'url'       => $url,
        ]);

        $body_html = view('emails/message-user-html', [
            'sender'    => $sender,
            'recipient' => $recipient,
            'message'   => $body,
            'url'       => $url,
        ]);

        // Send via the internal messaging system.
        if ($this->sendInternalMessage($recipient)) {
            DB::table('message')->insert([
                'sender'     => Auth::check() ? Auth::user()->email() : $sender->email(),
                'ip_address' => $ip,
                'user_id'    => $recipient->id(),
                'subject'    => $subject,
                'body'       => $body_text,
            ]);
        }

        // Send via email
        if ($this->sendEmail($recipient)) {
            $success = $this->email_service->send(
                new SiteUser(),
                $recipient,
                $sender,
                I18N::translate('webtrees message') . ' - ' . $subject,
                $body_text,
                $body_html
            );
        }

        I18N::init($old_language);

        return $success;
    }

    /**
     * Should we send messages to this user via internal messaging?
     *
     * @param UserInterface $user
     *
     * @return bool
     */
    public function sendInternalMessage(UserInterface $user): bool
    {
        return in_array($user->getPreference(UserInterface::PREF_CONTACT_METHOD), [
            self::CONTACT_METHOD_INTERNAL,
            self::CONTACT_METHOD_INTERNAL_AND_EMAIL,
            self::CONTACT_METHOD_MAILTO,
            self::CONTACT_METHOD_NONE,
        ], true);
    }

    /**
     * Should we send messages to this user via email?
     *
     * @param UserInterface $user
     *
     * @return bool
     */
    public function sendEmail(UserInterface $user): bool
    {
        return in_array($user->getPreference(UserInterface::PREF_CONTACT_METHOD), [
            self::CONTACT_METHOD_INTERNAL_AND_EMAIL,
            self::CONTACT_METHOD_EMAIL,
            self::CONTACT_METHOD_MAILTO,
            self::CONTACT_METHOD_NONE,
        ], true);
    }

    /**
     * Convert a username (or mailing list name) into an array of recipients.
     *
     * @param string $to
     *
     * @return Collection<int,User>
     */
    public function recipientUsers(string $to): Collection
    {
        switch ($to) {
            default:
            case self::BROADCAST_ALL:
                return $this->user_service->all();
            case self::BROADCAST_NEVER:
                return $this->user_service->all()
                    ->filter(static fn (UserInterface $user): bool => $user->getPreference(UserInterface::PREF_IS_ACCOUNT_APPROVED) === '1' && $user->getPreference(UserInterface::PREF_TIMESTAMP_REGISTERED) > $user->getPreference(UserInterface::PREF_TIMESTAMP_ACTIVE));
            case self::BROADCAST_GONE:
                $six_months_ago = Registry::timestampFactory()->now()->subtractMonths(6)->timestamp();

                return $this->user_service->all()->filter(static function (UserInterface $user) use ($six_months_ago): bool {
                    $session_time = (int) $user->getPreference(UserInterface::PREF_TIMESTAMP_ACTIVE);

                    return $session_time > 0 && $session_time < $six_months_ago;
                });
        }
    }

    /**
     * Recipients for broadcast messages
     *
     * @return array<string,string>
     */
    public function recipientTypes(): array
    {
        return [
            self::BROADCAST_ALL   => I18N::translate('Send a message to all users'),
            self::BROADCAST_NEVER => I18N::translate('Send a message to users who have never signed in'),
            self::BROADCAST_GONE  => I18N::translate('Send a message to users who have not signed in for 6 months'),
        ];
    }

    /**
     * A list of contact methods (e.g. for an edit control).
     *
     * @return array<string>
     */
    public function contactMethods(): array
    {
        return [
            self::CONTACT_METHOD_INTERNAL           => I18N::translate('Internal messaging'),
            self::CONTACT_METHOD_INTERNAL_AND_EMAIL => I18N::translate('Internal messaging with emails'),
            self::CONTACT_METHOD_EMAIL              => I18N::translate('webtrees sends emails with no storage'),
            self::CONTACT_METHOD_MAILTO             => I18N::translate('Mailto link'),
            self::CONTACT_METHOD_NONE               => I18N::translate('No contact'),
        ];
    }
}