-
Notifications
You must be signed in to change notification settings - Fork 1
/
WireMailSwiftMailer.module
487 lines (438 loc) · 18.8 KB
/
WireMailSwiftMailer.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
<?php
/**
* Swift Mailer WireMail module
*
* This module extends WireMail base class, integrating the Swift Mailer mailing
* library into ProcessWire.
*
* @copyright 2013-2022 Teppo Koivula
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License, version 2
*/
class WireMailSwiftMailer extends WireMail implements Module, ConfigurableModule, WireMailInterface {
/**
* Container for Swift Mailer instance
*
*/
protected $swiftMailer;
/**
* Container for connection exception
*
*/
protected $exception;
/**
* getModuleInfo is a module required by all modules to tell ProcessWire about them
*
* @return array
*/
public static function getModuleInfo() {
return array(
'title' => 'Swift Mailer',
'summary' => __('WireMail module providing Swift Mailer integration'),
'href' => 'http://modules.processwire.com/modules/wire-mail-swift-mailer/',
'author' => 'Teppo Koivula',
'version' => '0.3.0',
);
}
/**
* Default configuration for this module
*
* The point of putting this in it's own function is so that you don't have to specify
* these defaults more than once.
*
* @return array
*/
static public function getDefaultData() {
return array(
'transport' => 'Smtp',
'SMTPPort' => '25',
'defaultFrom' => 'processwire@' . wire('config')->httpHost,
'defaultFromName' => 'ProcessWire',
);
}
/**
* Populate the default config data
*
* ProcessWire will automatically overwrite it with anything the user has specifically configured.
* This is done in construct() rather than init() because ProcessWire populates config data after
* construct(), but before init().
*
*/
public function __construct() {
foreach(self::getDefaultData() as $key => $value) {
$this->$key = $value;
}
}
/**
* Module configuration
*
* @param array $data
* @return InputfieldWrapper
*/
static public function getModuleConfigInputfields(array $data) {
$testSubject = null;
$testBody = null;
$testTo = null;
if (wire('input')->post->_testSubject || wire('input')->post->_testBody || wire('input')->post->_testTo) {
$testSubject = wire('input')->post->_testSubject;
$testBody = wire('input')->post->_testBody;
$testTo = wire('input')->post->_testTo;
if ($testSubject && $testBody && $testTo) {
$testToArray = strpos($testTo, ",") ? explode(",", $testTo) : array($testTo);
$swiftMailer = wire('modules')->get('WireMailSwiftMailer');
if ($swiftMailer->swiftMailer) {
$num = $swiftMailer->swiftMailerSend($testToArray, $testSubject, $testBody, null, $data['defaultFrom']);
wire()->message(sprintf(__("A test message was just sent to %d recipients"), $num));
} else {
$num = $swiftMailer->wireMailSend($testToArray, $testSubject, $testBody, null, $data['defaultFrom']);
wire()->warning(sprintf(__("A test message was just sent to %d recipients, but using WireMail, since SwiftMailer is not properly configured"), $num));
}
} else {
wire()->error(__("In order to send a test message you need to fill in subject, body and recipient!"));
}
}
if (wire('input')->post->_checkConnection) {
// make sure that module config data is up to date
$configData = wire('modules')->getModuleConfigData(__CLASS__);
$configDataChanged = false;
foreach (wire('input')->post as $key => $value) {
if (array_key_exists($key, $configData) && $configData[$key] != $value) {
$configData[$key] = $value;
$configDataChanged = true;
}
}
if ($configDataChanged) {
wire('modules')->saveModuleConfigData(__CLASS__, $configData);
}
// check connection and alert the user if there's a problem
$swiftMailer = wire('modules')->get('WireMailSwiftMailer');
$result = $swiftMailer->checkConnection();
if ($result) {
wire()->message(__("Connection checked and everything seems to be working just fine. You're good to go."));
} else {
$exception = $swiftMailer->getException();
if ($exception) wire()->error($exception->getMessage());
wire()->error(__("Connection problem detected, please check your settings or select another method of transport. ProcessWire may not be able to send email at the moment."));
}
// store timestamp and result of this check to module config
$configData['connectionStatus'] = (int) $result . "|" . time();
wire('modules')->saveModuleConfigData(__CLASS__, $configData);
wire('session')->redirect('./edit?name=' . __CLASS__, false);
}
// this is a container for fields, basically like a fieldset
$fields = new InputfieldWrapper();
// since this is a static function, we can't use $this->modules, so get them from the global wire() function
$modules = wire('modules');
// merge default config settings (custom values overwrite defaults)
$defaults = self::getDefaultData();
$data = array_merge($defaults, $data);
// special handling for SMTP password
if (isset($data['SMTPPassword2']) && $data['SMTPPassword2']) {
$data['SMTPPassword'] = $data['SMTPPassword2'];
unset($data['SMTPPassword2'], $data['clearSMTPPassword']);
wire('modules')->saveModuleConfigData(__CLASS__, $data);
} else if (isset($data['clearSMTPPassword']) && $data['clearSMTPPassword']) {
unset($data['SMTPPassword'], $data['SMTPPassword2'], $data['clearSMTPPassword']);
wire('modules')->saveModuleConfigData(__CLASS__, $data);
} else {
unset($data['SMTPPassword2'], $data['clearSMTPPassword']);
wire('modules')->saveModuleConfigData(__CLASS__, $data);
}
// sender address
$field = $modules->get("InputfieldText");
$field->name = "defaultFrom";
$field->label = __("Sender Address");
$field->required = true;
if (isset($data[$field->name])) $field->value = $data[$field->name];
$fields->add($field);
// sender name
$field = $modules->get("InputfieldText");
$field->name = "defaultFromName";
$field->label = __("Sender Name");
if (isset($data[$field->name])) $field->value = $data[$field->name];
$fields->add($field);
// transport
$field = $modules->get("InputfieldSelect");
$field->name = "transport";
$field->label = __("Transport");
$field->notes = __("See [Swift Mailer Documentation](https://swiftmailer.symfony.com/docs/sending.html#transport-types) for detailed description for each individual Transport.");
$field->required = true;
$field->addOptions(array(
'Smtp' => 'SMTP',
'Sendmail' => 'Sendmail',
));
if (isset($data[$field->name])) $field->value = $data[$field->name];
if ($field->value == 'Mail') {
wire()->error("Mail transport setting is no longer supported by SwiftMailer, please use SMTP or Sendmail instead. Falling back to PHP mail().");
}
$fields->add($field);
// common container (fieldset) for SMTP settings
$fieldset = $modules->get("InputfieldFieldset");
$fieldset->showIf = "transport=Smtp";
$fieldset->label = __("SMTP Transport Settings");
$fields->add($fieldset);
// SMTP server name
$field = $modules->get("InputfieldText");
$field->name = "SMTPServer";
$field->label = __("SMTP server name");
$field->required = true;
$field->requiredIf = "transport=Smtp";
if (isset($data[$field->name])) $field->value = $data[$field->name];
$fieldset->add($field);
// SMTP server port
$field = $modules->get("InputfieldText");
$field->name = "SMTPPort";
$field->label = __("SMTP server port");
$field->required = true;
$field->requiredIf = "transport=Smtp";
if (isset($data[$field->name])) $field->value = $data[$field->name];
$fieldset->add($field);
// SMTP encryption
$field = $modules->get("InputfieldSelect");
$field->name = "SMTPEncryption";
$field->label = __("SMTP encryption");
$field->addOptions(array(
__('None'),
'ssl' => 'SSL',
'tls' => 'TLS',
));
if (isset($data[$field->name])) $field->value = $data[$field->name];
$fieldset->add($field);
// SMTP username
$field = $modules->get("InputfieldText");
$field->name = "SMTPUsername";
$field->label = __("SMTP username");
if (isset($data[$field->name])) $field->value = $data[$field->name];
$fieldset->add($field);
// SMTP password
$field = $modules->get("InputfieldText");
$field->collapsed = true;
$field->type = "password";
$field->name = "SMTPPassword2";
$field->label = __("SMTP password");
$field->notes = __("Note: password is stored as plain text in database. THIS IS NOT SECURE. Don't use this setting unless you're fully aware of it's consequences!");
$field->columnWidth = 75;
$fieldset->add($field);
// clear SMTP password?
$field = $modules->get("InputfieldCheckbox");
$field->collapsed = true;
$field->name = "clearSMTPPassword";
$field->label = __("Clear password?");
$field->notes = __("Check and save form to clear stored password.");
$field->columnWidth = 25;
$fieldset->add($field);
// Sendmail command
$field = $modules->get("InputfieldText");
$field->showIf = "transport=Sendmail";
$field->name = "SendmailCommand";
$field->label = __("Sendmail command");
$field->notes = __("Default value when left blank is /usr/sbin/sendmail -bs");
if (isset($data[$field->name])) $field->value = $data[$field->name];
$fields->add($field);
// common container (fieldset) for testing tools
$fieldset = $modules->get("InputfieldFieldset");
$fieldset->label = __("Check connection");
$fieldset->icon = "bolt";
$fields->add($fieldset);
// check connection
$field = $modules->get("InputfieldCheckbox");
$field->name = "_checkConnection";
$field->label = " ";
$field->label2 = __("Check connection now");
$field->description = __("Check this field if you want to run connection test after module settings are submitted. This will check if connection is functioning properly (i.e. SMTP server can be connected to and accepts defined credentials), but only way to know for sure that sending emails is possible is by sending a test message.");
if (isset($data['connectionStatus'])) {
$status = explode("|", $data['connectionStatus']);
$status_texts = array(
0 => __("Previous check performed %s was a failure."),
1 => __("Previous check performed %s was a success."),
);
$field->notes = sprintf($status_texts[$status[0]], date("j.n.Y H:i", $status[1]));
}
$fieldset->add($field);
// common container (form) for test message
$form = $modules->get("InputfieldForm");
$form->label = __("Send a test message");
$form->collapsed = ($testSubject || $testBody || $testTo) ? false : true;
$form->icon = "envelope";
$fieldset->add($form);
// help text for test message
$field = $modules->get("InputfieldMarkup");
$field->description = __("Using this tool you can send a test message using current settings. Please fill in all the fields. Note that submitting this form will clear all unsaved values from current config screen, so remember to save your changes before sending a test message!");
$form->add($field);
// subject for test message
$field = $modules->get("InputfieldText");
$field->name = "_testSubject";
$field->label = __("Message subject");
if ($testSubject) $field->value = $testSubject;
else if (!$form->collapsed) $field->error(__("Missing required value"));
$form->add($field);
// body for test message
$field = $modules->get("InputfieldTextarea");
$field->name = "_testBody";
$field->label = __("Message body");
if ($testBody) $field->value = $testBody;
else if (!$form->collapsed) $field->error(__("Missing required value"));
$form->add($field);
// recipient(s) for test message
$field = $modules->get("InputfieldText");
$field->name = "_testTo";
$field->label = __("Recipient(s)");
$field->notes = __("One or more recipients. Multiple recipients should be separated by commas.");
if ($testTo) $field->value = $testTo;
else if (!$form->collapsed) $field->error(__("Missing required value"));
$form->add($field);
// submit button for test message
$field = $modules->get("InputfieldSubmit");
$field->value = __("Send test message");
$form->add($field);
return $fields;
}
/**
* Initialize the module
*
* ProcessWire calls this when the module is loaded. For 'autoload' modules, this will be called
* when ProcessWire's API is ready. As a result, this is a good place to attach hooks.
*
* @throws WireException if unrecognized (invalid) transport setting was defined
*/
public function init() {
// init and configure Swift Mailer
require_once(dirname(__FILE__) . "/vendor/autoload.php");
$transport = null;
switch ($this->transport) {
case "Smtp":
$transport = new \Swift_SmtpTransport($this->SMTPServer, $this->SMTPPort, $this->SMTPEncryption ?: null);
if ($this->SMTPUsername) $transport->setUsername($this->SMTPUsername);
if ($this->SMTPPassword) $transport->setPassword($this->SMTPPassword);
break;
case "Sendmail":
$transport = new \Swift_SendmailTransport($this->SendmailCommand);
break;
case "Mail":
$this->error("Mail transport setting is no longer supported by SwiftMailer, please use SMTP or Sendmail instead");
break;
default:
throw new WireException("Transport setting not recognized");
}
$this->swiftMailer = $transport === null ? null : new \Swift_Mailer($transport);
}
/**
* Send email using Swift Mailer send() function
*
* @return int number of recipients accepted for delivery
*/
public function ___send() {
if ($this->swiftMailer) {
return $this->swiftMailerSend(
$this->to,
$this->subject,
$this->body,
$this->bodyHTML,
$this->from,
$this->fromName,
$this->header
);
}
// fall back to native PHP mail() via WireMail
return $this->wireMailSend(
$this->to,
$this->subject,
$this->body,
$this->bodyHTML,
$this->from,
$this->fromName,
$this->header
);
}
/**
* Send message via Swift Mailer
*
* @param string|array $to
* @param string $subject
* @param string|null $body
* @param string|null $bodyHTML
* @param string|null $from
* @param string|null $fromName
* @param array|null $header
* @return int
*
* @internal
*/
public function swiftMailerSend($to, $subject, $body = null, $bodyHTML = null, $from = null, $fromName = null, $header = null) {
// create the message
$message = (new \Swift_Message($subject, $body ?: $bodyHTML, !$body && $bodyHTML ? 'text/html' : null))
->setTo($to);
// set additional HTML body
if ($body && $bodyHTML) {
$message->addPart($bodyHTML, "text/html");
}
// set the From address with an associative array
$from = $this->from ? $this->from : $this->defaultFrom;
$fromName = $this->fromName ? $this->fromName : $this->defaultFromName;
$message->setFrom($fromName ? array($from => $fromName) : array($from));
// set extra headers
if ($this->header) {
$headers = $message->getHeaders();
foreach ($this->header as $name => $value) {
$headers->addTextHeader($name, $value);
}
}
return $this->swiftMailer->send($message);
}
/**
* Send message via WireMail
*
* @param string|array $to
* @param string $subject
* @param string|null $body
* @param string|null $bodyHTML
* @param string|null $from
* @param string|null $fromName
* @param array|null $header
* @return int
*
* @internal
*/
public function wireMailSend($to, $subject, $body = null, $bodyHTML = null, $from = null, $fromName = null, $header = null) {
$wireMail = ($this->wire(new WireMail()));
$wireMail->to($to);
$wireMail->from($from);
$wireMail->subject($subject);
$wireMail->body($body);
if ($bodyHTML) {
$wireMail->bodyHTML($bodyHTML);
}
if ($header) {
$wireMail->header($header);
}
return $wireMail->send();
}
/**
* Check if SMTP connection is available
*
* This is mostly useful for SMTP, but can also be used to check if Swift
* Mailer has been properly loaded and instantiated. If an SMTP connection
* fails, you can get the caught exception with getException().
*
* @return bool TRUE if connection is OK, FALSE if not
*/
public function checkConnection() {
if (!$this->swiftMailer) return false;
if ($this->transport == "Smtp") {
try {
$this->swiftMailer->getTransport()->start();
} catch (Swift_TransportException $e) {
$this->exception = $e;
return false;
}
}
return true;
}
/**
* Return SMTP connection exception (if exists)
*
* @return null|Swift_TransportException
*/
public function getException() {
return $this->exception;
}
}