Completed
Push — master ( 60adb1...73cc3b )
by Loz
17:57 queued 13:05
created

Mailer::sendPlain()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 6
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_endpoint = 'api.mailgun.net';
26
27
    /**
28
     * @var string
29
     * @config
30
     */
31
    private static $api_key = '';
32
33
    /**
34
     * @var boolean
35
     * @config
36
     */
37
    private static $api_ssl = true;
38
39
    /**
40
     * @var string
41
     * @config
42
     */
43
    private static $api_version = 'v3';
44
45
    /**
46
     * An array of temporary file handles opened to store attachments
47
     * @var array
48
     */
49
    protected $tempFileHandles = [];
50
51
    /**
52
     * @var Mailgun
53
     */
54
    protected $mailgunClient;
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 12
    public function __construct()
60
    {
61 12
        $config = $this->config();
62 12
        $this->setMailgunClient(new Mailgun(
63 12
            $config->api_key,
64 12
            $config->api_endpoint,
65 12
            $config->api_version,
66 12
            $config->api_ssl
67 12
        ));
68
    }
69
70
    /**
71
     * @param Mailgun $client
72
     * @return self
73
     */
74 12
    public function setMailgunClient(Mailgun $client)
75 12
    {
76
        $this->mailgunClient = $client;
77
        return $this;
78
    }
79
80
    /**
81
     * @return Mailgun
82
     */
83
    public function getMailgunClient()
84
    {
85
        return $this->mailgunClient;
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    public function sendPlain($to, $from, $subject, $plainContent, $attachments = [], $headers = [])
92
    {
93
        return $this->sendMessage($to, $from, $subject, $htmlContent = '', $plainContent, $attachments, $headers);
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99
    public function sendHTML($to, $from, $subject, $htmlContent, $attachments = [], $headers = [], $plainContent = '')
100
    {
101
        return $this->sendMessage($to, $from, $subject, $htmlContent, $plainContent, $attachments, $headers);
102
    }
103
104
    /**
105
     * @param string $to
106
     * @param string $from
107
     * @param string $subject
108
     * @param string $content
109
     * @param string $plainContent
110
     * @param array $attachments
111
     * @param array $headers
112
     */
113
    protected function sendMessage($to, $from, $subject, $content, $plainContent, $attachments, $headers)
114
    {
115
        $domain = $this->config()->api_domain;
116
        $client = $this->getMailgunClient();
117
        $attachments = $this->prepareAttachments($attachments);
118
119
        if (isset($headers['X-Mailgunner-Batch-Message'])) {
120
            $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...
121
            unset($headers['X-Mailgunner-Batch-Message']);
122
        } else {
123
            $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...
124
        }
125
126
        try {
127
            $this->buildMessage($builder, $to, $from, $subject, $content, $plainContent, $attachments, $headers);
128
129
            if ($builder instanceof BatchMessage) {
130
                $builder->finalize();
131
            } else {
132
                $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...
133
            }
134
        } catch (Exception $e) {
135
            // Close and remove any temp files created for attachments
136
            $this->closeTempFileHandles();
137
            // Throwing the exception would break SilverStripe's Email API expectations, so we log
138
            // errors and show a message (which is hidden in live mode)
139
            SS_Log::log('Mailgun error: ' . $e->getMessage(), SS_Log::ERR);
140
            Debug::message('Mailgun error: ' . $e->getMessage());
141
142
            return false;
143
        }
144
145
        $this->closeTempFileHandles();
146
147
        // This is a stupid API :(
148
        return array($to, $subject, $content, $headers, '');
149
    }
150
151
    /**
152
     * @param MessageBuilder $builder
153
     * @param string $to
154
     * @param string $from
155
     * @param string $subject
156
     * @param string $content
157
     * @param string $plainContent
158
     * @param array $attachments
159
     * @param array $headers
160
     */
161
    protected function buildMessage(
162
        MessageBuilder $builder,
163
        $to,
164
        $from,
165
        $subject,
166
        $content,
167
        $plainContent,
168
        array $attachments,
169
        array $headers
170
    ) {
171
        // Add base info
172
        $parsedFrom = $this->parseAddresses($from);
173
        foreach ($parsedFrom as $email => $name) {
174
            $builder->setFromAddress($email, ['full_name' => $name]);
175
        }
176
177
        $builder->setSubject($subject);
178
        $builder->setHtmlBody($content);
179
        $builder->setTextBody($plainContent);
180
181
        // Add attachments
182
        foreach ($attachments as $attachment) {
183
            $builder->addAttachment($attachment['filePath'], $attachment['remoteName']);
184
        }
185
186
        // Parse Cc & Bcc headers out if they're set
187
        $ccAddresses = isset($headers['Cc']) ? $headers['Cc'] : '';
188
        $bccAddresses = isset($headers['Bcc']) ? $headers['Bcc'] : '';
189
190
        // We handle these ourselves, so can remove them from the list of headers
191
        unset($headers['Cc']);
192
        unset($headers['Bcc']);
193
194
        // Add remaining custom headers
195
        foreach ($headers as $name => $data) {
196
            $builder->addCustomHeader($name, $data);
197
        }
198
199
        // Add recipients. This is done last as the 'BatchMessage' message builder
200
        // will trigger sends for every 1000 addresses
201
        $to = $this->parseAddresses($to);
202
        foreach ($to as $email => $name) {
203
            $builder->addToRecipient($email, ['full_name' => $name]);
204
        }
205
206
        $ccAddresses = $this->parseAddresses($ccAddresses);
207
        foreach ($ccAddresses as $email => $name) {
208
            $builder->addCcRecipient($email, ['full_name' => $name]);
209
        }
210
211
        $bccAddresses = $this->parseAddresses($bccAddresses);
212
        foreach ($bccAddresses as $email => $name) {
213
            $builder->addBccRecipient($email, ['full_name' => $name]);
214
        }
215
    }
216
217
    /**
218
     * @todo This can't deal with mismatched quotes, or commas in names.
219
     *       E.g. "Smith, John" <[email protected]> or "John O'smith" <[email protected]>
220
     * @param string
221
     * @return array
222
     */
223
    protected function parseAddresses($addresses)
224
    {
225
        $parsed = [];
226
227
        $expr = '/\s*["\']?([^><,;"\']+)["\']?\s*((?:<[^><,]+>)?)\s*/';
228
        if (preg_match_all($expr, $addresses, $matches, PREG_SET_ORDER) > 0) {
229
            foreach ($matches as $result) {
230
                if (empty($result[2])) {
231
                    // If we couldn't parse out a name
232
                    $parsed[$result[1]] = '';
233
                } else {
234
                    $email = trim($result[2], '<>');
235
                    $parsed[$email] = trim($result[1]);
236
                }
237
            }
238
        }
239
240
        return $parsed;
241
    }
242
243
    /**
244
     * Prepare attachments for sending. SilverStripe extracts the content and
245
     * passes that to the mailer, so to save encoding it we just write them all
246
     * to individual files and let Mailgun deal with the rest.
247
     *
248
     * @todo Can we handle this better?
249
     * @param array $attachments
250
     * @return array
251
     */
252
    protected function prepareAttachments(array $attachments)
253
    {
254
        $prepared = [];
255
256
        foreach ($attachments as $attachment) {
257
            $tempFile = $this->writeToTempFile($attachment['contents']);
258
259
            $prepared[] = [
260
                'filePath' => $tempFile,
261
                'remoteName' => $attachment['filename']
262
            ];
263
        }
264
265
        return $prepared;
266
    }
267
268
    /**
269
     * @param string $contents
270
     * @return string
271
     */
272
    protected function writeToTempFile($contents)
273
    {
274
        $tempFile = tempnam(sys_get_temp_dir(), 'SS_MG_TMP');
275
        $fileHandle = fopen($tempFile, 'r+');
276
        fwrite($fileHandle, $contents);
277
278
        $this->tempFileHandles[] = [
279
            'handle' => $fileHandle,
280
            'path' => $tempFile
281
        ];
282
283
        return $tempFile;
284
    }
285
286
    /**
287
     * @return void
288
     */
289
    protected function closeTempFileHandles()
290
    {
291
        foreach ($this->tempFileHandles as $key => $data) {
292
            fclose($data['handle']);
293
            unlink($data['path']);
294
            unset($this->tempFileHandles[$key]);
295
        }
296
    }
297
}
298