This repository has been archived by the owner on Jun 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathWireMailMailgun.module
executable file
·702 lines (619 loc) · 17.4 KB
/
WireMailMailgun.module
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
<?php
/**
* Class WireMailMailgun
*
* @property string apiKey The API key set in config
* @property string publicApiKey The public API key set in config
* @property string domain The domain for the API key
* @property bool batchMode True by default. See setBatchMode() method of this class for more info.
*/
class WireMailMailgun extends WireMail implements Module, ConfigurableModule
{
private $apiUrl = 'https://api.mailgun.net/v3/';
private $batchMode = true;
private $tags = [];
private $recipientsVariables = [];
public static function getModuleInfo()
{
return array(
'title' => 'WireMail Mailgun',
'version' => '0.4.2',
'summary' => "Mailgun for ProcessWire",
'href' => 'https://github.com/plauclair/WireMailMailgun',
'author' => 'plauclair',
'singular' => false,
'autoload' => false
);
}
/**
*
*/
public function ___send()
{
$request = curl_init();
$postFields = [
'from' => $this->getFrom(),
'to' => $this->getToRecipients(),
'subject' => $this->mail['subject'],
'o:testmode' => $this->isTestMode(),
];
// Batch mode variables
if ($this->batchMode === true) {
$postFields['recipient-variables'] = $this->getToRecipientsVariables();
}
// Set CC recipients
if ($this->getCCRecipients() !== false) {
$postFields['cc'] = $this->getCCRecipients();
}
// Set BCC recipients
if ($this->getBCCRecipients() !== false) {
$postFields['bcc'] = $this->getBCCRecipients();
}
// Set body
if (!empty($this->mail['bodyHTML'])) {
$postFields['html'] = $this->mail['bodyHTML'];
// TODO: Replace the next line with something that
// will output better plain text (break to newline especially)
$postFields['text'] = (!empty($this->mail['body'])) ? $this->mail['body'] : strip_tags($this->mail['bodyHTML']);
} else {
$postFields['text'] = $this->mail['body'];
}
// Email Open Tracking
$postFields['o:tracking-clicks'] = ($this->clickTracking() === true) ? 'yes' : 'no';
// Email Click tracking
$postFields['o:tracking-opens'] = ($this->openTracking() === true) ? 'yes' : 'no';
// Attachments
if ($this->getAttachments() !== false) {
$attachmentIndex = 0;
foreach ($this->getAttachments() as $attachment) {
if (function_exists('curl_file_create')) {
// PHP >= 5.5.0
$postFields["attachment[$attachmentIndex]"] = curl_file_create($attachment);
} else {
// PHP < 5.5.0
$postFields["attachment[$attachmentIndex]"] = "@{$attachment}";
}
$attachmentIndex += 1;
}
}
// Headers
if ($this->getHeaders() !== false) {
foreach ($this->getHeaders() as $header => $value) {
$postFields["h:{$header}"] = $value;
}
}
// Tags
if ($this->getTags() !== false) {
$tagIndex = 0;
foreach ($this->getTags() as $tag) {
$postFields["o:tag[$tagIndex]"] = $tag;
$tagIndex += 1;
}
}
$options = array(
CURLOPT_USERPWD => "api:{$this->apiKey}",
CURLOPT_URL => "{$this->apiUrl}{$this->domain}/messages",
CURLOPT_HEADER => false,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_SSL_VERIFYPEER => $this->sslCheck(),
);
curl_setopt_array($request, $options);
$response = curl_exec($request);
if ($response === false) {
// If an error occurred in cURL
$this->log()->save('mailgun', 'cURL Error: ' . curl_error($request));
curl_close($request);
return 0;
} else {
$response = json_decode($response);
$info = curl_getinfo($request);
curl_close($request);
switch ($info['http_code']) {
case 200:
return true; // Can't set int for number sent, since Mailgun doesn't return that data
break;
case 400:
$this->log()->save('mailgun', "Code 400: Bad Request - {$response->message}.");
return 0;
break;
case 401:
$usedKey = (!empty($this->apiKey)) ? "API Key: {$this->apiKey}." : 'NO KEY SET.';
$this->log()->save('mailgun', "Code 401: Unauthorized - No valid API key provided. {$usedKey}");
return 0;
break;
case 402:
// TODO: Improve this later
$this->log()->save('mailgun', "Code 402: Request Failed - Parameters were valid but request failed.");
return 0;
break;
case 404:
$this->log()->save('mailgun', "Code 404: Not Found - The requested item doesn’t exist.");
return 0;
break;
case 500:
$this->log()->save('mailgun', "Code 500: Mailgun Server Error.");
return 0;
break;
case 502:
$this->log()->save('mailgun', "Code 502: Mailgun Server Error.");
return 0;
break;
case 503:
$this->log()->save('mailgun', "Code 503: Mailgun Server Error.");
return 0;
break;
case 504:
$this->log()->save('mailgun', "Code 504: Mailgun Server Error.");
return 0;
break;
}
}
}
/**
* Handles send() when new WireMail() is used instead
* of calling wireMail() directly
*/
public function send()
{
return $this->___send();
}
/**
* Overrides the Mailgun API Key setting in config
*
* @param string $apiKey
*/
public function setApiKey($apiKey)
{
$this->apiKey = $apiKey;
}
/**
* Overrides the Domain Name setting in config
*
* @param string $domainName
*/
public function setDomainName($domainName)
{
$this->domain = $domainName;
}
/**
* Overrides the Test Mode setting in config
*
* @param bool $bool
*/
public function setTestMode($bool)
{
if (is_bool($bool)) {
$this->testMode = ($bool === true) ? 'testMode' : false;
}
}
/**
* Returns if the current instance is used in Test Mode
*
* @return bool
*/
private function isTestMode()
{
return ($this->testMode == 'testMode') ? true : false;
}
/**
* Returns if the current instance disables SSH check
*
* This can sometimes be needed on some testing environments,
* preferably don't use in production
*
* @return bool
*/
private function sslCheck()
{
return ($this->disableSslCheck == 'disableSslCheck') ? false : true;
}
/**
* Get the recipients of the To field in the proper format
*
* @return string|false
*/
private function getToRecipients()
{
$recipients = $this->mail['toName'];
$to = [];
foreach ($recipients as $email => $name) {
$to[] = (empty($name)) ? $email : "{$name} <{$email}>";
}
return (!empty($to)) ? implode(',', $to) : false;
}
/**
* Get the recipient variables
*
* For now, this is used to emulate the default to()
* method behavior. Mailgun hard limit on this calling
* style is 1000 recipients per request
*/
private function getToRecipientsVariables()
{
$recipients = $this->mail['toName'];
$i = 1;
foreach ($recipients as $email => $name) {
if (! array_key_exists($email, $this->recipientsVariables)) {
$this->recipientsVariables[$email] = [];
}
$this->recipientsVariables[$email]['id'] = $i;
$this->recipientsVariables[$email]['name'] = $name;
$i += 1;
}
return json_encode($this->recipientsVariables);
}
/**
* Set the recipient variables
*
* Add variables for a batch email.
*
* @param array $recipientVariables
*/
public function setToRecipientsVariables(array $recipientVariables)
{
$this->recipientsVariables = $recipientVariables;
return $this;
}
/**
* Enables or disables batch mode
*
* This is on by default, meaning that all emails in the To field won't see the other recipients.
*/
public function setBatchMode($bool)
{
if (is_bool($bool)) {
$this->batchMode = $bool;
}
}
/**
* Will allow merging an array of emails with
* their recipients variables
*/
public function mergeToRecipientsVariables()
{
// THIS IS A STUB
// TODO: Implement this..
}
/**
* Set the email CC address
*
* Each added email addresses appends to any addresses already supplied, unless
* you specify NULL as the email address, in which case it clears them all.
*
* @param string|array|null $email Specify any ONE of the following:
* 1. Single email address or "User Name <[email protected]>" string.
* 2. CSV string of #1.
* 3. Non-associative array of #1.
* 4. Associative array of (email => name)
* 5. NULL (default value, to clear out any previously set values)
* @param string $name Optionally provide a FROM name, applicable
* only when specifying #1 (single email) for the first argument.
* @return WireMail this
* @throws WireException if any provided emails were invalid
*
*/
public function cc($email = null, $name = null)
{
if (is_null($email)) {
// clear existing values
$this->mail['cc'] = array();
$this->mail['ccName'] = array();
return $this;
}
$emails = is_array($email) ? $email : explode(',', $email);
foreach ($emails as $key => $value) {
$ccName = '';
if (is_string($key)) {
// associative array
// email provided as $key, and $ccName as value
$ccEmail = $key;
$ccName = $value;
} else if (strpos($value, '<') !== false && strpos($value, '>') !== false) {
// ccName supplied as: "User Name <[email protected]"
list($ccEmail, $ccName) = $this->extractEmailAndName($value);
} else {
// just an email address, possibly with name as a function arg
$ccEmail = $value;
}
if (empty($ccName)) $ccName = $name; // use function arg if not overwritten
$ccEmail = $this->sanitizeEmail($ccEmail);
$this->mail['cc'][$ccEmail] = $ccEmail;
$this->mail['ccName'][$ccEmail] = $this->sanitizeHeader($ccName);
}
return $this;
}
/**
* Get the recipients of the CC field in the proper format
*
* @return string|false
*/
private function getCCRecipients()
{
if (!empty($this->mail['ccName'])) {
$recipients = $this->mail['ccName'];
$cc = [];
foreach ($recipients as $email => $name) {
$cc[] = (empty($name)) ? $email : "{$name} <{$email}>";
}
return (!empty($cc)) ? implode(', ', $cc) : false;
} else {
return false;
}
}
/**
* Set the email BCC address
*
* Each added email addresses appends to any addresses already supplied, unless
* you specify NULL as the email address, in which case it clears them all.
*
* @param string|array|null $email Specify any ONE of the following:
* 1. Single email address or "User Name <[email protected]>" string.
* 2. CSV string of #1.
* 3. Non-associative array of #1.
* 4. Associative array of (email => name)
* 5. NULL (default value, to clear out any previously set values)
* @param string $name Optionally provide a FROM name, applicable
* only when specifying #1 (single email) for the first argument.
* @return WireMail this
* @throws WireException if any provided emails were invalid
*
*/
public function bcc($email = null, $name = null)
{
if (is_null($email)) {
// clear existing values
$this->mail['bcc'] = array();
$this->mail['bccName'] = array();
return $this;
}
$emails = is_array($email) ? $email : explode(',', $email);
foreach ($emails as $key => $value) {
$bccName = '';
if (is_string($key)) {
// associative array
// email provided as $key, and $bccName as value
$bccEmail = $key;
$bccName = $value;
} else if (strpos($value, '<') !== false && strpos($value, '>') !== false) {
// bccName supplied as: "User Name <[email protected]"
list($bccEmail, $bccName) = $this->extractEmailAndName($value);
} else {
// just an email address, possibly with name as a function arg
$bccEmail = $value;
}
if (empty($bccName)) $bccName = $name; // use function arg if not overwritten
$bccEmail = $this->sanitizeEmail($bccEmail);
$this->mail['bcc'][$bccEmail] = $bccEmail;
$this->mail['bccName'][$bccEmail] = $this->sanitizeHeader($bccName);
}
return $this;
}
/**
* Get the recipients of the BCC field in the proper format
*
* @return string|false
*/
private function getBCCRecipients()
{
if (!empty($this->mail['bccName'])) {
$recipients = $this->mail['bccName'];
$bcc = [];
foreach ($recipients as $email => $name) {
$bcc[] = (empty($name)) ? $email : "{$name} <{$email}>";
}
return (!empty($bcc)) ? implode(', ', $bcc) : false;
} else {
return false;
}
}
/**
* Get the From field in the proper format
*
* Will use WireMail()->from() if set first,
* module settings second and
* revert to default if nothing else is set
*
* @return string|false
*/
private function getFrom()
{
$fromEmail = $this->fromEmail;
$fromName = $this->fromName;
if (!empty($this->mail['from'])) {
// Set manually
return (empty($this->mail['fromName'])) ? $this->mail['from'] : "{$this->mail['fromName']} <{$this->mail['from']}>";
} else if (!empty($fromEmail)) {
// Set in settings
return (empty($fromName)) ? "ProcessWire <{$fromEmail}>" : "{$fromName} <{$fromEmail}>";
} else {
// Default
return "ProcessWire <processwire@{$this->domain}>";
}
}
/**
* Overrides "click tracking" module settings on a per-email basis
*
* Note: per Mailgun constraints, click tracking will
* only work on HTML emails
*
* @param bool $bool
*/
public function setClickTracking($bool)
{
if ($bool === true) {
$this->trackClicks = 'trackClicks';
} else if ($bool === false) {
$this->trackClicks = null;
}
}
/**
* Returns whether the current email has click tracking
* enabled or not
*
* @return bool
*/
private function clickTracking()
{
return ($this->trackClicks == 'trackClicks') ? true : false;
}
/**
* Overrides "open tracking module" settings on a per-email basis
*
* Note: per Mailgun constraints, open tracking will
* only work on HTML emails
*
* @param bool $bool
*/
public function setOpenTracking($bool)
{
if ($bool === true) {
$this->trackOpens = 'trackOpens';
} else if ($bool === false) {
$this->trackOpens = null;
}
}
/**
* Returns whether the current email has open tracking
* enabled or not
*
* @return bool
*/
private function openTracking()
{
return ($this->trackOpens == 'trackOpens') ? true : false;
}
/**
* Adds an attachment to the email using a file path
*
* @param string $filePath
*/
public function addAttachment($filePath)
{
if (realpath($filePath) !== false) {
$this->mail['attachments'][] = realpath($filePath);
return true;
} else {
return false;
}
}
/**
* Gets attachments, or return false if there are none
*
* @return array|false
*/
private function getAttachments()
{
if (isset($this->mail['attachments']) and !empty($this->mail['attachments'])) {
return $this->mail['attachments'];
} else {
return false;
}
}
/**
* Returns an array of the custom-defined headers
*
* @return array
*/
private function getHeaders()
{
if (isset($this->mail['header']) and !empty($this->mail['header'])) {
return $this->mail['header'];
} else {
return false;
}
}
/**
* Adds a tag to the email
*
* Will add up to 3 tags. Any string passed to this
* function will be converted to ASCII and trimmed to
* be 128 characters long.
*
* It is STRONGLY recommended that you enable
* the PHP 'intl' module if you want correct
* UTF-8 to ASCII conversion
*
* See https://documentation.mailgun.com/user_manual.html#tagging
*
* @param string $tag
*/
public function addTag($tag)
{
// check if transliterator_transliterate exists and translit ID is valid on current system
$transId = 'Any-Latin; Latin-ASCII; [\u0080-\u7fff] remove';
if (function_exists('transliterator_transliterate') and ($transliterator = \Transliterator::create($transId))) {
// convert to ASCII
$transString = $transliterator->transliterate($tag);
} else {
// basic fallback to iconv... might be unreliable but kind of works
$tag = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $tag);
}
$tag = trim($tag);
$tag = substr($tag, 0, 128);
if (!empty($tag) and count($this->tags) <= 3) {
$this->tags[] = $tag;
} else if (count($this->tags) > 3) {
$this->log()->save('mailgun', "Tags: Tried to use more than 3 tags. Mailgun supports a maximum of 3 at a time.");
}
}
/**
* Gets tags, or return false if there are none
*
* @return array|false
*/
private function getTags()
{
if (isset($this->tags) and !empty($this->tags)) {
return $this->tags;
} else {
return false;
}
}
/**
* Validates a single address using Mailgun's address validation service
*
* For more information on what this method returns,
* visit https://documentation.mailgun.com/api-email-validation.html#email-validation
*
* return object|false Returns an array of validation data from Mailgun
* @param string $email
* @return object|false
*/
public function validateEmail($email)
{
// if public API key isn't set, log that
if (empty($this->publicApiKey)) {
$this->log()->save('mailgun', 'The Public API Key must be set when using the email validation feature.');
return false;
}
$email = filter_var($email, FILTER_SANITIZE_STRING);
// if it fails basic string validation, stop
if ($email == false){
return false;
}
$email = urlencode($email);
$request = curl_init();
$options = array(
CURLOPT_USERPWD => "api:{$this->publicApiKey}",
CURLOPT_URL => "{$this->apiUrl}address/validate?address={$email}",
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => $this->sslCheck(),
);
curl_setopt_array($request, $options);
$response = curl_exec($request);
if ($response === false) {
// If an error occurred in cURL
$this->log()->save('mailgun', 'cURL Error: ' . curl_error($request));
curl_close($request);
return false;
} else {
$response = json_decode($response);
$info = curl_getinfo($request);
curl_close($request);
return $response;
}
}
}