-
Notifications
You must be signed in to change notification settings - Fork 3
/
EmbedImagesSender.php
312 lines (274 loc) · 10.9 KB
/
EmbedImagesSender.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
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
<?php
/*
*
* Nearly a 100% copy&paste from
* https://github.com/civicrm/org.civicrm.flexmailer/blob/master/src/Listener/DefaultSender.php
* except the function insert around line 49 to implement message composition with embedded images
*
*/
class CRM_WpCiviMosaico_EmbedImagesSender extends \Civi\FlexMailer\Listener\BaseListener
{
const BULK_MAIL_INSERT_COUNT = 10;
public function onSend(Civi\FlexMailer\Event\SendBatchEvent $e) {
static $smtpConnectionErrors = 0;
if (!$this->isActive()) {
return;
}
$e->stopPropagation();
$job = $e->getJob();
$mailing = $e->getMailing();
$job_date = \CRM_Utils_Date::isoToMysql($job->scheduled_date);
$mailer = \Civi::service('pear_mail');
$targetParams = $deliveredParams = array();
$count = 0;
$retryBatch = FALSE;
foreach ($e->getTasks() as $key => $task) {
/** @var \Civi\FlexMailer\FlexMailerTask $task */
/** @var \Mail_mime $message */
if (!$task->hasContent()) {
continue;
}
$message = \Civi\FlexMailer\MailParams::convertMailParamsToMime($task->getMailParams());
if (empty($message)) {
// lets keep the message in the queue
// most likely a permissions related issue with smarty templates
// or a bad contact id? CRM-9833
continue;
}
/* insert start */
$message = CRM_WpCiviMosaico_EmbedHTMLImages::doEmbed( $message );
/* insert end */
// disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
if ($job_date) {
$errorScope = \CRM_Core_TemporaryErrorScope::ignoreException();
}
$headers = $message->headers();
$result = $mailer->send($headers['To'], $message->headers(), $message->get());
if ($job_date) {
unset($errorScope);
}
if (is_a($result, 'PEAR_Error')) {
/** @var \PEAR_Error $result */
// CRM-9191
$message = $result->getMessage();
if ($this->isTemporaryError($result->getMessage())) {
// lets log this message and code
$code = $result->getCode();
\CRM_Core_Error::debug_log_message("SMTP Socket Error or failed to set sender error. Message: $message, Code: $code");
// these are socket write errors which most likely means smtp connection errors
// lets skip them and reconnect.
$smtpConnectionErrors++;
if ($smtpConnectionErrors <= 5) {
$mailer->disconnect();
$retryBatch = TRUE;
continue;
}
// seems like we have too many of them in a row, we should
// write stuff to disk and abort the cron job
$job->writeToDB($deliveredParams, $targetParams, $mailing, $job_date);
\CRM_Core_Error::debug_log_message("Too many SMTP Socket Errors. Exiting");
\CRM_Utils_System::civiExit();
}
else {
$this->recordBounce($job, $task, $result->getMessage());
}
}
else {
// Register the delivery event.
$deliveredParams[] = $task->getEventQueueId();
$targetParams[] = $task->getContactId();
$count++;
if ($count % self::BULK_MAIL_INSERT_COUNT == 0) {
$job->writeToDB($deliveredParams, $targetParams, $mailing, $job_date);
$count = 0;
// hack to stop mailing job at run time, CRM-4246.
// to avoid making too many DB calls for this rare case
// lets do it when we snapshot
$status = \CRM_Core_DAO::getFieldValue(
'CRM_Mailing_DAO_MailingJob',
$job->id,
'status',
'id',
TRUE
);
if ($status != 'Running') {
$e->setCompleted(FALSE);
return;
}
}
}
unset($result);
// seems like a successful delivery or bounce, lets decrement error count
// only if we have smtp connection errors
if ($smtpConnectionErrors > 0) {
$smtpConnectionErrors--;
}
// If we have enabled the Throttle option, this is the time to enforce it.
$mailThrottleTime = \CRM_Core_Config::singleton()->mailThrottleTime;
if (!empty($mailThrottleTime)) {
usleep((int) $mailThrottleTime);
}
}
$completed = $job->writeToDB(
$deliveredParams,
$targetParams,
$mailing,
$job_date
);
if ($retryBatch) {
$completed = FALSE;
}
$e->setCompleted($completed);
}
/**
* Determine if an SMTP error is temporary or permanent.
*
* @param string $message
* PEAR error message.
* @return bool
* TRUE - Temporary/retriable error
* FALSE - Permanent/non-retriable error
*/
protected function isTemporaryError($message) {
// SMTP response code is buried in the message.
$code = preg_match('/ \(code: (.+), response: /', $message, $matches) ? $matches[1] : '';
if (strpos($message, 'Failed to write to socket') !== FALSE) {
return TRUE;
}
// Register 5xx SMTP response code (permanent failure) as bounce.
if (isset($code{0}) && $code{0} === '5') {
return FALSE;
}
if (strpos($message, 'Failed to set sender') !== FALSE) {
return TRUE;
}
if (strpos($message, 'Failed to add recipient') !== FALSE) {
return TRUE;
}
if (strpos($message, 'Failed to send data') !== FALSE) {
return TRUE;
}
return FALSE;
}
/**
* @param \CRM_Mailing_BAO_MailingJob $job
* @param \Civi\FlexMailer\FlexMailerTask $task
* @param string $errorMessage
*/
protected function recordBounce($job, $task, $errorMessage) {
$params = array(
'event_queue_id' => $task->getEventQueueId(),
'job_id' => $job->id,
'hash' => $task->getHash(),
);
$params = array_merge($params,
\CRM_Mailing_BAO_BouncePattern::match($errorMessage)
);
\CRM_Mailing_Event_BAO_Bounce::create($params);
}
}
class CRM_WpCiviMosaico_EmbedHTMLImages
{
const TRACKER_PARTS = [
'/civicrm/extern/open.php',
'civicrm/mailing/open',
];
// compile a list of images in the HTML, replace in HTML with aliases,
// return an array of filename => alias
private static function scanHTMLforImages( &$html_body )
{
$result = [];
// supress warnings
libxml_use_internal_errors( true );
try
{
// convert HTML mail into DOM object
$html_DOM = \DOMDocument::loadHTML( $html_body, LIBXML_BIGLINES );
// simply return on error
if ( false === $html_DOM )
return $result;
// setup URL parts of our upload directory
$uploaddir = wp_get_upload_dir();
$uploaddir_parts = parse_url( $uploaddir[ 'baseurl' ] );
// search img tags
$images = $html_DOM->getElementsByTagName( 'img' );
foreach ( $images as $image )
{
// get src attribute
if ( $image->hasAttribute( 'src' ) )
{
$img_src = $image->getAttribute( 'src' );
// create image URL parts
$img_src_parts = parse_url( $img_src );
if ( $img_src_parts[ 'host' ] == $uploaddir_parts[ 'host' ] )
{
// file is and on our host
$query_array = [];
parse_str( $img_src, $query_array );
if ( ( array_key_exists( 'q', $query_array ) ) && ( 'civicrm/wp_civi_mosaico/img' == $query_array[ 'q' ] ) )
{
// our own image processor - src is image URL parameter
// create image URL parts
$img_src_parts = parse_url( $query_array[ 'src' ] );
}
$path_parts = explode( '.', $img_src_parts[ 'path' ] );
$suffix = end( $path_parts );
// ignore tracker pixels
$is_tracker = false;
foreach( self::TRACKER_PARTS as $tracker_part )
{
if ( ( false !== strpos( $img_src_parts[ 'path' ], $tracker_part ) ) || ( false !== strpos( $img_src_parts[ 'query' ], $tracker_part ) ) )
{
$is_tracker = true;
break;
}
}
if ( ( !$is_tracker ) && ( 0 != strcasecmp( 'php', $suffix ) ) && ( 0 == strpos( $img_src_parts[ 'path' ], $uploaddir_parts[ 'path' ] ) ) )
{
// file is not a php file in our upload directory
$img_file_alias = str_replace( $uploaddir_parts[ 'path' ], '', $img_src_parts[ 'path' ] );
$img_file_name = $uploaddir[ 'basedir' ] . $img_file_alias;
// replace
$image->setAttribute( 'src', $img_file_alias );
// push into result array
if ( !array_key_exists( $img_file_alias, $result ) )
$result[ $img_file_alias ] = $img_file_name;
}
}
}
}
// convert DOM back to HTML string
$html_body = $html_DOM->saveHTML();
}
catch ( \Exception $e )
{
CRM_WpCiviMosaico_Utils::logme( 'Error scanning for HTML images: ' . $e->getMessage() );
// todo: error message to frontend
}
libxml_clear_errors();
\CRM_WpCiviMosaico_Utils::logme( "Exiting scanHTMLforImages" );
return $result;
}
public static function doEmbed( $message )
{
$embedImages = CRM_Core_BAO_Setting::getItem( 'WP Civi Mosaico Preferences', 'wp_civi_mosaico_embed_images' );
if ( $embedImages )
{
$html_body = $message->getHTMLBody();
$image_array = self::scanHTMLforImages( $html_body );
if ( !empty( $image_array ) )
{
$message->setHTMLBody( $html_body );
foreach ( $image_array as $img_file_alias => $img_file_name )
{
$img_mime = mime_content_type( $img_file_name );
if ( false === $img_mime )
$img_mime = 'application/octet-stream';
$message->addHTMLImage( $img_file_name, $img_mime, $img_file_alias );
}
}
}
return $message;
}
}
?>