Completed
Push — master ( 73cc3b...b43b98 )
by Loz
16:42 queued 11:31
created

Mailer::setMailgunClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 3
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Kinglozzer\SilverStripeMailgunner;
4
5
use Debug;
6
use Exception;
7
use Mailer as SilverstripeMailer;
8
use Mailgun\Mailgun;
9
use Mailgun\Messages\BatchMessage;
10
use Mailgun\Messages\MessageBuilder;
11
use SS_Log;
12
13
class Mailer extends SilverstripeMailer
14
{
15
    /**
16
     * @var string
17
     * @config
18
     */
19
    private static $api_domain = '';
20
21
    /**
22
     * @var string
23
     * @config
24
     */
25
    private static $api_key = '';
26
27
    /**
28
     * @var boolean
29
     * @config
30
     */
31
    private static $api_ssl = true;
32
33
    /**
34
     * @var string
35
     * @config
36
     */
37
    private static $api_version = 'v3';
38
39
    /**
40
     * An array of temporary file handles opened to store attachments
41
     * @var array
42
     */
43
    protected $tempFileHandles = [];
44
45
    /**
46
     * @var Mailgun
47
     */
48
    protected $mailgunClient;
49
50
    /**
51
     * {@inheritdoc}
52
     */
53 12
    public function __construct()
54
    {
55 12
        $config = $this->config();
56 12
        $this->setMailgunClient(Mailgun::create($config->api_key));
57
58
        // @todo - Remove, these are deprecated
59
        $this->mailgunClient->setApiVersion($config->api_version);
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Mailgun::setApiVersion() has been deprecated with message: Will be removed in 3.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
60
        $this->mailgunClient->setSslEnabled($config->api_ssl);
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Mailgun::setSslEnabled() has been deprecated with message: This will be removed in 3.0. Mailgun does not support non-secure connections to their API.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
61
    }
62
63
    /**
64
     * @param Mailgun $client
65
     * @return self
66
     */
67
    public function setMailgunClient(Mailgun $client)
68
    {
69
        $this->mailgunClient = $client;
70
        return $this;
71
    }
72
73
    /**
74
     * @return Mailgun
75
     */
76
    public function getMailgunClient()
77
    {
78
        return $this->mailgunClient;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function sendPlain($to, $from, $subject, $plainContent, $attachments = [], $headers = [])
85
    {
86
        return $this->sendMessage($to, $from, $subject, $htmlContent = '', $plainContent, $attachments, $headers);
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92
    public function sendHTML($to, $from, $subject, $htmlContent, $attachments = [], $headers = [], $plainContent = '')
93
    {
94
        return $this->sendMessage($to, $from, $subject, $htmlContent, $plainContent, $attachments, $headers);
95
    }
96
97
    /**
98
     * @param string $to
99
     * @param string $from
100
     * @param string $subject
101
     * @param string $content
102
     * @param string $plainContent
103
     * @param array $attachments
104
     * @param array $headers
105
     */
106 1
    protected function sendMessage($to, $from, $subject, $content, $plainContent, $attachments, $headers)
107
    {
108
        $domain = $this->config()->api_domain;
109
        $client = $this->getMailgunClient();
110
        $attachments = $this->prepareAttachments($attachments);
111
112 1
        if (isset($headers['X-Mailgunner-Batch-Message'])) {
113
            $builder = $client->BatchMessage($domain);
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Mailgun::BatchMessage() has been deprecated with message: Will be removed in 3.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
114
            unset($headers['X-Mailgunner-Batch-Message']);
115
        } else {
116
            $builder = $client->MessageBuilder();
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Mailgun::MessageBuilder() has been deprecated with message: Will be removed in 3.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
117
        }
118
119
        try {
120
            $this->buildMessage($builder, $to, $from, $subject, $content, $plainContent, $attachments, $headers);
121
122
            if ($builder instanceof BatchMessage) {
123
                $builder->finalize();
124
            } else {
125
                $client->sendMessage($domain, $builder->getMessage(), $builder->getFiles());
0 ignored issues
show
Deprecated Code introduced by
The method Mailgun\Mailgun::sendMessage() has been deprecated with message: Use Mailgun->message() instead. Will be removed in 3.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
126
            }
127
        } catch (Exception $e) {
128
            // Close and remove any temp files created for attachments
129
            $this->closeTempFileHandles();
130
            // Throwing the exception would break SilverStripe's Email API expectations, so we log
131
            // errors and show a message (which is hidden in live mode)
132
            SS_Log::log('Mailgun error: ' . $e->getMessage(), SS_Log::ERR);
133
            Debug::message('Mailgun error: ' . $e->getMessage());
134
135
            return false;
136
        }
137
138
        $this->closeTempFileHandles();
139
140
        // This is a stupid API :(
141
        return array($to, $subject, $content, $headers, '');
142
    }
143
144
    /**
145
     * @param MessageBuilder $builder
146
     * @param string $to
147
     * @param string $from
148
     * @param string $subject
149
     * @param string $content
150
     * @param string $plainContent
151
     * @param array $attachments
152
     * @param array $headers
153
     */
154
    protected function buildMessage(
155
        MessageBuilder $builder,
156
        $to,
157
        $from,
158
        $subject,
159
        $content,
160
        $plainContent,
161
        array $attachments,
162
        array $headers
163
    ) {
164
        // Add base info
165
        $parsedFrom = $this->parseAddresses($from);
166
        foreach ($parsedFrom as $email => $name) {
167
            $builder->setFromAddress($email, ['full_name' => $name]);
168
        }
169
170
        $builder->setSubject($subject);
171
        $builder->setHtmlBody($content);
172
        $builder->setTextBody($plainContent);
173
174
        // Add attachments
175
        foreach ($attachments as $attachment) {
176
            $builder->addAttachment($attachment['filePath'], $attachment['remoteName']);
177
        }
178
179
        // Parse Cc & Bcc headers out if they're set
180
        $ccAddresses = isset($headers['Cc']) ? $headers['Cc'] : '';
181
        $bccAddresses = isset($headers['Bcc']) ? $headers['Bcc'] : '';
182
183
        // We handle these ourselves, so can remove them from the list of headers
184
        unset($headers['Cc']);
185
        unset($headers['Bcc']);
186
187
        // Add remaining custom headers
188
        foreach ($headers as $name => $data) {
189
            $builder->addCustomHeader($name, $data);
190
        }
191
192
        // Add recipients. This is done last as the 'BatchMessage' message builder
193
        // will trigger sends for every 1000 addresses
194
        $to = $this->parseAddresses($to);
195
        foreach ($to as $email => $name) {
196
            $builder->addToRecipient($email, ['full_name' => $name]);
197
        }
198
199
        $ccAddresses = $this->parseAddresses($ccAddresses);
200
        foreach ($ccAddresses as $email => $name) {
201
            $builder->addCcRecipient($email, ['full_name' => $name]);
202
        }
203
204
        $bccAddresses = $this->parseAddresses($bccAddresses);
205
        foreach ($bccAddresses as $email => $name) {
206
            $builder->addBccRecipient($email, ['full_name' => $name]);
207
        }
208
    }
209
210
    /**
211
     * @todo This can't deal with mismatched quotes, or commas in names.
212
     *       E.g. "Smith, John" <[email protected]> or "John O'smith" <[email protected]>
213
     * @param string
214
     * @return array
215
     */
216
    protected function parseAddresses($addresses)
217
    {
218
        $parsed = [];
219
220
        $expr = '/\s*["\']?([^><,;"\']+)["\']?\s*((?:<[^><,]+>)?)\s*/';
221
        if (preg_match_all($expr, $addresses, $matches, PREG_SET_ORDER) > 0) {
222
            foreach ($matches as $result) {
223
                if (empty($result[2])) {
224
                    // If we couldn't parse out a name
225
                    $parsed[$result[1]] = '';
226
                } else {
227
                    $email = trim($result[2], '<>');
228
                    $parsed[$email] = trim($result[1]);
229
                }
230
            }
231
        }
232
233
        return $parsed;
234
    }
235
236
    /**
237
     * Prepare attachments for sending. SilverStripe extracts the content and
238
     * passes that to the mailer, so to save encoding it we just write them all
239
     * to individual files and let Mailgun deal with the rest.
240
     *
241
     * @todo Can we handle this better?
242
     * @param array $attachments
243
     * @return array
244
     */
245
    protected function prepareAttachments(array $attachments)
246
    {
247
        $prepared = [];
248
249
        foreach ($attachments as $attachment) {
250
            $tempFile = $this->writeToTempFile($attachment['contents']);
251
252
            $prepared[] = [
253
                'filePath' => $tempFile,
254
                'remoteName' => $attachment['filename']
255
            ];
256
        }
257
258
        return $prepared;
259
    }
260
261
    /**
262
     * @param string $contents
263
     * @return string
264
     */
265
    protected function writeToTempFile($contents)
266
    {
267
        $tempFile = tempnam(sys_get_temp_dir(), 'SS_MG_TMP');
268
        $fileHandle = fopen($tempFile, 'r+');
269
        fwrite($fileHandle, $contents);
270
271
        $this->tempFileHandles[] = [
272
            'handle' => $fileHandle,
273
            'path' => $tempFile
274
        ];
275
276
        return $tempFile;
277
    }
278
279
    /**
280
     * @return void
281
     */
282
    protected function closeTempFileHandles()
283
    {
284
        foreach ($this->tempFileHandles as $key => $data) {
285
            fclose($data['handle']);
286
            unlink($data['path']);
287
            unset($this->tempFileHandles[$key]);
288
        }
289
    }
290
}
291