/var/www/html_fr/wp-content/plugins/fluent-smtp/app/Services/Mailer/Providers/AmazonSes/Handler.php


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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
<?php

namespace FluentMail\App\Services\Mailer\Providers\AmazonSes;

use 
FluentMail\App\Models\Settings;
use 
FluentMail\App\Services\Mailer\BaseHandler;
use 
FluentMail\Includes\Support\Arr;

class 
Handler extends BaseHandler
{
    use 
ValidatorTrait;

    protected 
$client null;

    const 
RAW_REQUEST true;

    const 
TRIGGER_ERROR false;

    public function 
send()
    {
        if (
$this->preSend() && $this->phpMailer->preSend()) {
            
$this->client = new SimpleEmailServiceMessage;
            return 
$this->postSend();
        }

        return 
$this->handleResponse(new \WP_Error(422__('Something went wrong!''fluent-smtp'), []));
    }

    public function 
postSend()
    {
        
$mime chunk_split(base64_encode($this->phpMailer->getSentMIMEMessage()), 76"\n");

        
$connectionSettings $this->filterConnectionVars($this->getSetting());

        
$ses fluentMailSesConnection($connectionSettings);

        
$this->response $ses->sendRawEmail($mime);

        return 
$this->handleResponse($this->response);
    }

    protected function 
getFrom()
    {
        return 
$this->getParam('from');
    }

    public function 
getVerifiedEmails()
    {
        return (new 
Settings)->getVerifiedEmails();
    }

    protected function 
getReplyTo()
    {
        
$replyTo $this->getRecipients(
            
$this->getParam('headers.reply-to')
        );

        if (
is_array($replyTo)) {
            
$replyTo reset($replyTo);
        }

        return 
$replyTo;
    }

    protected function 
getTo()
    {
        return 
$this->getRecipients($this->getParam('to'));
    }

    protected function 
getCarbonCopy()
    {
        return 
$this->getRecipients($this->getParam('headers.cc'));
    }

    protected function 
getBlindCarbonCopy()
    {
        return 
$this->getRecipients($this->getParam('headers.bcc'));
    }

    protected function 
getRecipients($recipients)
    {
        
$array array_map(function ($recipient) {
            return isset(
$recipient['name'])
                ? 
$recipient['name'] . ' <' $recipient['email'] . '>'
                
$recipient['email'];
        }, 
$recipients);

        return 
implode(', '$array);
    }

    protected function 
getBody()
    {
        return [
            
$this->phpMailer->AltBody,
            
$this->phpMailer->Body
        
];
    }

    protected function 
getAttachments()
    {
        
$attachments = [];

        foreach (
$this->getParam('attachments') as $attachment) {
            
$file false;

            try {
                if (
is_file($attachment[0]) && is_readable($attachment[0])) {
                    
$fileName basename($attachment[0]);
                    
$file file_get_contents($attachment[0]);
                    
$mimeType mime_content_type($attachment[0]);
                    
$filetype str_replace(';'''trim($mimeType));
                }
            } catch (
\Exception $e) {
                
$file false;
            }

            if (
$file === false) {
                continue;
            }

            
$attachments[] = [
                
'type'    => $filetype,
                
'name'    => $fileName,
                
'content' => $file
            
];
        }

        return 
$attachments;
    }

    protected function 
getCustomEmailHeaders()
    {
        
$customHeaders = [
            
'X-Mailer' => 'Amazon-SES'
        
];

        
$headers = [];
        foreach (
$customHeaders as $key => $header) {
            
$headers[] = $key ':' $header;
        }

        return 
$headers;
    }

    protected function 
getRegion()
    {
        return 
'email.' $this->getSetting('region') . '.amazonaws.com';
    }

    public function 
getValidSenders($config)
    {
        
$config $this->filterConnectionVars($config);

        
$senders $this->getSendersFromMappingsAndApi($config);

        return 
$senders['all_senders'];
    }

    public function 
getValidSendingIdentities($config)
    {
        
$config $this->filterConnectionVars($config);

        
$region 'email.' $config['region'] . '.amazonaws.com';

        
$ses = new SimpleEmailService(
            
$config['access_key'],
            
$config['secret_key'],
            
$region,
            static::
TRIGGER_ERROR
        
);

        
$validSenders $ses->listVerifiedEmailAddresses();

        
$addresses = [];

        if (
is_wp_error($validSenders)) {
            return [
                
'emails'          => [$config['sender_email']],
                
'verified_domain' => ''
            
];
        }

        if (
$validSenders && isset($validSenders['Addresses'])) {
            
$addresses $validSenders['Addresses'];
        }

        
$primaryEmail $config['sender_email'];
        
$domainArray explode('@'$primaryEmail);
        
$domainName $domainArray[1];

        if (
apply_filters('fluent_mail_ses_primary_domain_only'true)) {
            
$addresses array_filter($addresses, function ($email) use ($domainName) {
                return !!
strpos($email$domainName);
            });
            
$addresses array_values($addresses);
        }

        return [
            
'emails'          => apply_filters('fluentsmtp_ses_valid_senders'$addresses$config),
            
'verified_domain' => in_array($domainName$validSenders['domains']) ? $domainName ''
        
];
    }

    public function 
getConnectionInfo($connection)
    {
        
$connection $this->filterConnectionVars($connection);

        
$stats $this->getStats($connection);
        
$error '';
        if (
is_wp_error($stats)) {
            
$error $stats->get_error_message();
            
$stats = [];
        }

        
$validSenders $this->getSendersFromMappingsAndApi($connection);

        
$info = (string)fluentMail('view')->make('admin.ses_connection_info', [
            
'connection'    => $connection,
            
'valid_senders' => $validSenders['all_senders'],
            
'stats'         => $stats,
            
'error'         => $error
        
]);

        return [
            
'info'                 => $info,
            
'verificationSettings' => [
                
'connection_name'  => 'Amazon SES',
                
'all_senders'      => $validSenders['all_senders'],
                
'verified_senders' => $validSenders['verified_senders'],
                
'verified_domain'  => $validSenders['verified_domain']
            ]
        ];
    }

    public function 
addNewSenderEmail($connection$email)
    {
        
$connection $this->filterConnectionVars($connection);
        
$validSenders $this->getValidSendingIdentities($connection);

        
$emailDomain explode('@'$email);
        
$emailDomain $emailDomain[1];

        if (
$emailDomain != $validSenders['verified_domain']) {
            return new 
\WP_Error(422__('Invalid email address! Please use a verified domain.''fluent-smtp'));
        }

        
$settings fluentMailGetSettings();
        
$mappings Arr::get($settings'mappings', []);

        if (isset(
$mappings[$email])) {
            return new 
\WP_Error(422__('Email address already exists with another connection. Please choose a different email.''fluent-smtp'));
        }

        
$settings get_option('fluentmail-settings');

        
$settings['mappings'][$email] = md5($connection['sender_email']);

        
update_option('fluentmail-settings'$settings);

        return 
true;
    }

    public function 
removeSenderEmail($connection$email)
    {
        
$connection $this->filterConnectionVars($connection);
        
$validSenders $this->getValidSendingIdentities($connection);

        
$emailDomain explode('@'$email);
        
$emailDomain $emailDomain[1];

        if (
$emailDomain != $validSenders['verified_domain']) {
            return new 
\WP_Error(422__('Invalid email address! Please use a verified domain.''fluent-smtp'));
        }

        if (
in_array($email$validSenders['emails'])) {
            return new 
\WP_Error(422__('Sorry! you can not remove this email from this connection''fluent-smtp'));
        }

        
$settings fluentMailGetSettings();
        
$mappings Arr::get($settings'mappings', []);

        if (!isset(
$mappings[$email])) {
            return new 
\WP_Error(422__('Email does not exists. Please try again.''fluent-smtp'));
        }

        
// check if the it's the same email or not
        
if ($mappings[$email] != md5($connection['sender_email'])) {
            return new 
\WP_Error(422__('Email does not exists. Please try again.''fluent-smtp'));
        }

        
$settings get_option('fluentmail-settings');

        unset(
$settings['mappings'][$email]);

        
update_option('fluentmail-settings'$settings);

        return 
true;
    }


    private function 
getStats($config)
    {
        
$region 'email.' $config['region'] . '.amazonaws.com';

        
$ses = new SimpleEmailService(
            
$config['access_key'],
            
$config['secret_key'],
            
$region,
            static::
TRIGGER_ERROR
        
);

        return 
$ses->getSendQuota();
    }

    private function 
filterConnectionVars($connection)
    {
        if (
$connection['key_store'] == 'wp_config') {
            
$connection['access_key'] = defined('FLUENTMAIL_AWS_ACCESS_KEY_ID') ? FLUENTMAIL_AWS_ACCESS_KEY_ID '';
            
$connection['secret_key'] = defined('FLUENTMAIL_AWS_SECRET_ACCESS_KEY') ? FLUENTMAIL_AWS_SECRET_ACCESS_KEY '';
        }

        return 
$connection;
    }

    private function 
getSendersFromMappingsAndApi($connection)
    {
        
$validSenders $this->getValidSendingIdentities($connection);
        
$verifiedDomain Arr::get($validSenders'verified_domain''');
        if (
$verifiedDomain) {
            
$settings fluentMailGetSettings();
            
$mappings Arr::get($settings'mappings', []);

            
$mapKey md5($connection['sender_email']);
            
$mapSenders array_filter($mappings, function ($key) use ($mapKey) {
                return 
$key == $mapKey;
            });

            
$mapSenders[$connection['sender_email']] = true;

            foreach (
$validSenders['emails'] as $email) {
                
$mapSenders[$email] = $email;
            }

            
$mapSenders array_keys($mapSenders);

        } else {
            
$mapSenders $validSenders['emails'];
        }

        return [
            
'all_senders'      => $mapSenders,
            
'verified_senders' => $validSenders['emails'],
            
'verified_domain'  => $verifiedDomain
        
];
    }
}