Completed
Push — master ( b43b98...d4fde7 )
by Loz
22:09 queued 14:16
created

Mailer::parseAddresses()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 13
cts 13
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 11
nc 2
nop 1
crap 4
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 12
        $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 12
        $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 12
    }
62
63
    /**
64
     * @param Mailgun $client
65
     * @return self
66
     */
67 12
    public function setMailgunClient(Mailgun $client)
68
    {
69 12
        $this->mailgunClient = $client;
70 12
        return $this;
71
    }
72
73
    /**
74
     * @return Mailgun
75
     */
76 1
    public function getMailgunClient()
77
    {
78 1
        return $this->mailgunClient;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84 1
    public function sendPlain($to, $from, $subject, $plainContent, $attachments = [], $headers = [])
85
    {
86 1
        return $this->sendMessage($to, $from, $subject, $htmlContent = '', $plainContent, $attachments, $headers);
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92 1
    public function sendHTML($to, $from, $subject, $htmlContent, $attachments = [], $headers = [], $plainContent = '')
93
    {
94 1
        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 4
    protected function sendMessage($to, $from, $subject, $content, $plainContent, $attachments, $headers)
107
    {
108 3
        $domain = $this->config()->api_domain;
109 3
        $client = $this->getMailgunClient();
110 3
        $attachments = $this->prepareAttachments($attachments);
111
112 4
        if (isset($headers['X-Mailgunner-Batch-Message'])) {
113 1
            $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 1
            unset($headers['X-Mailgunner-Batch-Message']);
115 1
        } else {
116 2
            $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 3
            $this->buildMessage($builder, $to, $from, $subject, $content, $plainContent, $attachments, $headers);
121
122 3
            if ($builder instanceof BatchMessage) {
123 1
                $builder->finalize();
124 1
            } else {
125 2
                $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 3
        } catch (Exception $e) {
128
            // Close and remove any temp files created for attachments
129 1
            $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 1
            SS_Log::log('Mailgun error: ' . $e->getMessage(), SS_Log::ERR);
133 1
            Debug::message('Mailgun error: ' . $e->getMessage());
134
135 1
            return false;
136
        }
137
138 2
        $this->closeTempFileHandles();
139
140
        // This is a stupid API :(
141 2
        return array($to, $subject, $content, $headers, '');
142 1
    }
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 2
    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 2
        $parsedFrom = $this->parseAddresses($from);
166 2
        foreach ($parsedFrom as $email => $name) {
167 2
            $builder->setFromAddress($email, ['full_name' => $name]);
168 2
        }
169
170 2
        $builder->setSubject($subject);
171 2
        $builder->setHtmlBody($content);
172 2
        $builder->setTextBody($plainContent);
173
174
        // Add attachments
175 2
        foreach ($attachments as $attachment) {
176 2
            $builder->addAttachment($attachment['filePath'], $attachment['remoteName']);
177 2
        }
178
179
        // Parse Cc & Bcc headers out if they're set
180 2
        $ccAddresses = isset($headers['Cc']) ? $headers['Cc'] : '';
181 2
        $bccAddresses = isset($headers['Bcc']) ? $headers['Bcc'] : '';
182
183
        // We handle these ourselves, so can remove them from the list of headers
184 2
        unset($headers['Cc']);
185 2
        unset($headers['Bcc']);
186
187
        // Add remaining custom headers
188 2
        foreach ($headers as $name => $data) {
189 2
            $builder->addCustomHeader($name, $data);
190 2
        }
191
192
        // Add recipients. This is done last as the 'BatchMessage' message builder
193
        // will trigger sends for every 1000 addresses
194 2
        $to = $this->parseAddresses($to);
195 2
        foreach ($to as $email => $name) {
196 2
            $builder->addToRecipient($email, ['full_name' => $name]);
197 2
        }
198
199 2
        $ccAddresses = $this->parseAddresses($ccAddresses);
200 2
        foreach ($ccAddresses as $email => $name) {
201 2
            $builder->addCcRecipient($email, ['full_name' => $name]);
202 2
        }
203
204 2
        $bccAddresses = $this->parseAddresses($bccAddresses);
205 2
        foreach ($bccAddresses as $email => $name) {
206 2
            $builder->addBccRecipient($email, ['full_name' => $name]);
207 2
        }
208 2
    }
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 3
    protected function parseAddresses($addresses)
217
    {
218 3
        $parsed = [];
219
220 3
        $expr = '/\s*["\']?([^><,;"\']+)["\']?\s*((?:<[^><,]+>)?)\s*/';
221 3
        if (preg_match_all($expr, $addresses, $matches, PREG_SET_ORDER) > 0) {
222 3
            foreach ($matches as $result) {
223 3
                if (empty($result[2])) {
224
                    // If we couldn't parse out a name
225 3
                    $parsed[$result[1]] = '';
226 3
                } else {
227 3
                    $email = trim($result[2], '<>');
228 3
                    $parsed[$email] = trim($result[1]);
229
                }
230 3
            }
231 3
        }
232
233 3
        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 2
    protected function prepareAttachments(array $attachments)
246
    {
247 2
        $prepared = [];
248
249 2
        foreach ($attachments as $attachment) {
250 2
            $tempFile = $this->writeToTempFile($attachment['contents']);
251
252 2
            $prepared[] = [
253 2
                'filePath' => $tempFile,
254 2
                'remoteName' => $attachment['filename']
255 2
            ];
256 2
        }
257
258 2
        return $prepared;
259
    }
260
261
    /**
262
     * @param string $contents
263
     * @return string
264
     */
265 2
    protected function writeToTempFile($contents)
266
    {
267 2
        $tempFile = tempnam(sys_get_temp_dir(), 'SS_MG_TMP');
268 2
        $fileHandle = fopen($tempFile, 'r+');
269 2
        fwrite($fileHandle, $contents);
270
271 2
        $this->tempFileHandles[] = [
272 2
            'handle' => $fileHandle,
273
            'path' => $tempFile
274 2
        ];
275
276 2
        return $tempFile;
277
    }
278
279
    /**
280
     * @return void
281
     */
282 1
    protected function closeTempFileHandles()
283
    {
284 1
        foreach ($this->tempFileHandles as $key => $data) {
285 1
            fclose($data['handle']);
286 1
            unlink($data['path']);
287 1
            unset($this->tempFileHandles[$key]);
288 1
        }
289 1
    }
290
}
291