-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmailersend.php
272 lines (245 loc) · 9.81 KB
/
mailersend.php
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
<?php
namespace Grav\Plugin;
use Composer\Autoload\ClassLoader;
use Grav\Common\Data\Data;
use Grav\Common\Data\ValidationException;
use Grav\Common\Plugin;
use Grav\Common\Utils;
use League\HTMLToMarkdown\HtmlConverter;
use MailerSend\Exceptions\MailerSendException;
use MailerSend\Helpers\Builder\EmailParams;
use MailerSend\Helpers\Builder\Recipient;
use MailerSend\Helpers\Builder\Variable;
use MailerSend\MailerSend;
use Psr\Http\Client\ClientExceptionInterface;
use RocketTheme\Toolbox\Event\Event;
use Symfony\Component\HttpClient\Exception\JsonException;
/**
* Class MailerSendPlugin
* @package Grav\Plugin
*/
class MailerSendPlugin extends Plugin
{
/**
* @return array
*
* The getSubscribedEvents() gives the core a list of events
* that the plugin wants to listen to. The key of each
* array section is the event that the plugin listens to
* and the value (in the form of an array) contains the
* callable (or function) as well as the priority. The
* higher the number the higher the priority.
*/
public static function getSubscribedEvents(): array
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', 0],
'onFormProcessed' => ['onFormProcessed', 0],
];
}
/**
* Composer autoload
*
* @return ClassLoader
*/
public function autoload(): ClassLoader
{
return require __DIR__ . '/vendor/autoload.php';
}
/**
* Initialize the plugin
*/
public function onPluginsInitialized(): void
{
// Don't proceed if we are in the admin plugin
if ($this->isAdmin()) {
return;
}
}
/**
* Process `mailersend` form action
*
* @param Event $event
* @return void
* @throws MailerSendException
* @throws \JsonException
* @throws \MailerSend\Exceptions\MailerSendAssertException
*/
public function onFormProcessed(Event $event): void
{
$form = $event['form'];
$action = $event['action'];
$params = $event['params'];
if ($action === 'mailersend') {
$vars = new Data([
'form' => $form,
'page' => $this->grav['page']
]);
$this->grav->fireEvent('onMailerSendVars', new Event(['vars' => $vars]));
$params = $this->processParams($params, $vars->toArray());
$api_token = $this->config->get('plugins.mailersend.api_token');
if (empty($api_token) || strlen($api_token) < 10) {
$message = "Invalid or missing Mailersend API token";
$this->grav->fireEvent('onFormValidationError', new Event([
'form' => $form,
'message' => $message
]));
$event->stopPropagation();
return;
}
$mailersend = new MailerSend(['api_key' => $api_token]);
$emailParams = new EmailParams();
try {
$recipients = $this->processRecipients('to', $params);
$emailParams->setRecipients($recipients);
$emailParams->setCc($this->processRecipients('cc', $params));
$emailParams->setBcc($this->processRecipients('bcc', $params));
$emailParams->setSubject($params['subject'] ?? $this->grav['page']->title() ?? $this->config->get('site.title'));
$from_all = $this->processRecipients('from', $params);
if (is_array($from_all)) {
$from = array_shift($from_all)->toArray();
$emailParams->setFrom($from['email'])
->setFromName($from['name']);
}
if (isset($params['reply_to'])) {
$reply_to = $this->createRecipient($params['reply_to'])->toArray();
$emailParams->setReplyTo($reply_to['email'])
->setReplyToName($reply_to['name']);
}
if (isset($params['template_id'])) {
$to = array_shift($recipients)->toArray();
$vars = $params['substitutions'] ?? [];
$variables = [new Variable($to['email'], $vars)];
$emailParams->setTemplateId($params['template_id'])->setVariables($variables);
} else {
$message = $params['body'] ?? $params['message'] ?? $form->value('message') ?? '';
$html = (bool) ($params['html'] ?? false);
if ($html) {
$converter = new HtmlConverter();
$html = html_entity_decode($message);
$text = $converter->convert($html);
$emailParams->setHtml($html);
$emailParams->setText($text);
} else {
$emailParams->setText($message);
}
}
$this->grav->fireEvent('onMailerSendBeforeSend', new Event(['mailersend' => $mailersend, 'params' => $emailParams]));
if ($this->config->get('plugins.mailersend.debug')) {
$data = [
'from' => $emailParams->getFrom(),
'from_name' => $emailParams->getFromName(),
'reply_to' => $emailParams->getReplyTo(),
'reply_to_name' => $emailParams->getReplyToName(),
'recipients' => $emailParams->getRecipients(),
'subject' => $emailParams->getSubject(),
'html' => $emailParams->getHtml(),
'text' => $emailParams->getText(),
];
$this->grav['log']->error("emailParams: " . json_encode($data));
} else {
$mailersend->email->send($emailParams);
}
} catch (\Exception $e) {
$this->grav->fireEvent('onFormValidationError', new Event([
'form' => $form,
'message' => $e->getMessage()
]));
$event->stopPropagation();
}
$this->grav->fireEvent('onMailerSendAfterSend', new Event(['mailersend' => $mailersend]));
}
}
/**
* Iterate over recipient types
*
* @param string $type to|from|reply_to|bcc|cc etc
* @param array $params params in the mailersend `process:` for definition
* @return array List of recipients
* @throws \MailerSend\Exceptions\MailerSendAssertException
*/
protected function processRecipients(string $type, array $params)
{
$recipients = $params[$type] ??
$this->config->get('plugins.mailersend.defaults.'.$type) ??
$this->config->get('plugins.email.'.$type) ??
[];
$list = [];
if (!empty($recipients)) {
if (is_array($recipients) && Utils::isAssoc($recipients)) {
$list[] = $this->createRecipient($recipients);
} else {
if (is_array($recipients[0])) {
foreach ($recipients as $recipient) {
$list[] = $this->createRecipient($recipient);
}
} else {
if (is_string($recipients) && Utils::contains($recipients, ',')) {
$recipients = array_map('trim', explode(',', $recipients));
foreach ($recipients as $recipient) {
$list[] = $this->createRecipient($recipient);
}
} else {
$list[] = $this->createRecipient($recipients);
}
}
}
}
return $list;
}
/**
* Creates a MailerSend recipient object and suppots the following formats:
*
* - ['[email protected]', 'Your Name'] # simple **array**
* - 'Your Name <[email protected]>' # name-addr spec **string**
* - ['[email protected]' => 'Your Name'] # basic associative **array**
* - ['email' => '[email protected]', 'name' => 'Your Name'] # full associative **array**
* - '[email protected]' # basic addr-spec **string**
* - '<[email protected]>' # basic angle-addr **string**
*
* @param $data
* @return Recipient
* @throws \MailerSend\Exceptions\MailerSendAssertException
*/
protected function createRecipient($data): Recipient
{
if (is_string($data)) {
preg_match('/^(.*)\<(.*)\>$/', $data, $matches);
if (isset($matches[2])) {
$email = trim($matches[2]);
$name = trim($matches[1]);
} else {
$email = $data;
$name = null;
}
} elseif (Utils::isAssoc($data)) {
$first_key = array_key_first($data);
if (filter_var($first_key, FILTER_VALIDATE_EMAIL)) {
$email = $first_key;
$name = $data[$first_key];
} else {
$email = $data['email'] ?? $data['mail'] ?? $data['address'] ?? null;
$name = $data['name'] ?? $data['fullname'] ?? null;
}
} else {
$email = $data[0] ?? null;
$name = $data[1] ?? null;
}
return new Recipient($email, $name);
}
/**
* Twig Process each item in the params array
*
* @param array $params
* @param array $vars
* @return array
*/
protected function processParams(array $params, array $vars = []): array
{
$twig = $this->grav['twig'];
array_walk_recursive($params, function(&$value) use ($twig, $vars) {
$value = $twig->processString($value, $vars);
});
return $params;
}
}