3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
34 // we should consider moving these to the settings table
35 // before the 4.1 release
36 define('EMAIL_ACTIVITY_TYPE_ID', NULL);
37 define('MAIL_BATCH_SIZE', 50);
40 * Class CRM_Utils_Mail_EmailProcessor.
42 class CRM_Utils_Mail_EmailProcessor
{
45 * Process the default mailbox (ie. that is used by civiMail for the bounce)
48 * Always returns true (for the api). at a later stage we should
49 * fix this to return true on success / false on failure etc.
51 public static function processBounces() {
52 $dao = new CRM_Core_DAO_MailSettings();
53 $dao->domain_id
= CRM_Core_Config
::domainID();
54 $dao->is_default
= TRUE;
57 while ($dao->fetch()) {
58 self
::_process(TRUE, $dao);
61 // always returns true, i.e. never fails :)
66 * Delete old files from a given directory (recursively).
69 * Directory to cleanup.
71 * Files older than this many seconds will be deleted (default: 60 days).
73 public static function cleanupDir($dir, $age = 5184000) {
74 // return early if we can’t read/write the dir
75 if (!is_writable($dir) or !is_readable($dir) or !is_dir($dir)) {
79 foreach (scandir($dir) as $file) {
81 // don’t go up the directory stack and skip new files/dirs
82 if ($file == '.' or $file == '..') {
85 if (filemtime("$dir/$file") > time() - $age) {
89 // it’s an old file/dir, so delete/recurse
90 is_dir("$dir/$file") ? self
::cleanupDir("$dir/$file", $age) : unlink("$dir/$file");
95 * Process the mailboxes that aren't default (ie. that aren't used by civiMail for the bounce).
97 public static function processActivities() {
98 $dao = new CRM_Core_DAO_MailSettings();
99 $dao->domain_id
= CRM_Core_Config
::domainID();
100 $dao->is_default
= FALSE;
103 while ($dao->fetch()) {
105 self
::_process(FALSE, $dao);
108 CRM_Core_Error
::fatal(ts('No mailboxes have been configured for Email to Activity Processing'));
114 * Process the mailbox for all the settings from civicrm_mail_settings.
116 * @param bool|string $civiMail if true, processing is done in CiviMail context, or Activities otherwise.
118 public static function process($civiMail = TRUE) {
119 $dao = new CRM_Core_DAO_MailSettings();
120 $dao->domain_id
= CRM_Core_Config
::domainID();
123 while ($dao->fetch()) {
124 self
::_process($civiMail, $dao);
130 * @param CRM_Core_DAO $dao
134 public static function _process($civiMail, $dao) {
135 // 0 = activities; 1 = bounce;
136 $usedfor = $dao->is_default
;
139 = (defined('EMAIL_ACTIVITY_TYPE_ID') && EMAIL_ACTIVITY_TYPE_ID
) ? EMAIL_ACTIVITY_TYPE_ID
: CRM_Core_OptionGroup
::getValue(
145 if (!$emailActivityTypeId) {
146 CRM_Core_Error
::fatal(ts('Could not find a valid Activity Type ID for Inbound Email'));
149 $config = CRM_Core_Config
::singleton();
150 $verpSeperator = preg_quote($config->verpSeparator
);
151 $twoDigitStringMin = $verpSeperator . '(\d+)' . $verpSeperator . '(\d+)';
152 $twoDigitString = $twoDigitStringMin . $verpSeperator;
153 $threeDigitString = $twoDigitString . '(\d+)' . $verpSeperator;
155 // FIXME: legacy regexen to handle CiviCRM 2.1 address patterns, with domain id and possible VERP part
156 $commonRegex = '/^' . preg_quote($dao->localpart
) . '(b|bounce|c|confirm|o|optOut|r|reply|re|e|resubscribe|u|unsubscribe)' . $threeDigitString . '([0-9a-f]{16})(-.*)?@' . preg_quote($dao->domain
) . '$/';
157 $subscrRegex = '/^' . preg_quote($dao->localpart
) . '(s|subscribe)' . $twoDigitStringMin . '@' . preg_quote($dao->domain
) . '$/';
159 // a common-for-all-actions regex to handle CiviCRM 2.2 address patterns
160 $regex = '/^' . preg_quote($dao->localpart
) . '(b|c|e|o|r|u)' . $twoDigitString . '([0-9a-f]{16})@' . preg_quote($dao->domain
) . '$/';
162 // a tighter regex for finding bounce info in soft bounces’ mail bodies
163 $rpRegex = '/Return-Path: ' . preg_quote($dao->localpart
) . '(b)' . $twoDigitString . '([0-9a-f]{16})@' . preg_quote($dao->domain
) . '/';
165 // a regex for finding bound info X-Header
166 $rpXheaderRegex = '/X-CiviMail-Bounce: ' . preg_quote($dao->localpart
) . '(b)' . $twoDigitString . '([0-9a-f]{16})@' . preg_quote($dao->domain
) . '/i';
167 // CiviMail in regex and Civimail in header !!!
169 // retrieve the emails
171 $store = CRM_Mailing_MailStore
::getStore($dao->name
);
173 catch (Exception
$e) {
174 $message = ts('Could not connect to MailStore for ') . $dao->username
. '@' . $dao->server
. '<p>';
175 $message .= ts('Error message: ');
176 $message .= '<pre>' . $e->getMessage() . '</pre><p>';
177 CRM_Core_Error
::fatal($message);
180 // process fifty at a time, CRM-4002
181 while ($mails = $store->fetchNext(MAIL_BATCH_SIZE
)) {
182 foreach ($mails as $key => $mail) {
184 // for every addressee: match address elements if it's to CiviMail
189 foreach ($mail->to
as $address) {
190 if (preg_match($regex, $address->email
, $matches)) {
191 list($match, $action, $job, $queue, $hash) = $matches;
193 // FIXME: the below elseifs should be dropped when we drop legacy support
195 elseif (preg_match($commonRegex, $address->email
, $matches)) {
196 list($match, $action, $_, $job, $queue, $hash) = $matches;
199 elseif (preg_match($subscrRegex, $address->email
, $matches)) {
200 list($match, $action, $_, $job) = $matches;
205 // CRM-5471: if $matches is empty, it still might be a soft bounce sent
206 // to another address, so scan the body for ‘Return-Path: …bounce-pattern…’
207 if (!$matches and preg_match($rpRegex, $mail->generateBody(), $matches)) {
208 list($match, $action, $job, $queue, $hash) = $matches;
211 // if $matches is still empty, look for the X-CiviMail-Bounce header
213 if (!$matches and preg_match($rpXheaderRegex, $mail->generateBody(), $matches)) {
214 list($match, $action, $job, $queue, $hash) = $matches;
216 // With Mandrilla, the X-CiviMail-Bounce header is produced by generateBody
220 $all_parts = $mail->fetchParts();
221 foreach ($all_parts as $k_part => $v_part) {
222 if ($v_part instanceof ezcMailFile
) {
223 $p_file = $v_part->__get('fileName');
224 $c_file = file_get_contents($p_file);
225 if (preg_match($rpXheaderRegex, $c_file, $matches)) {
226 list($match, $action, $job, $queue, $hash) = $matches;
232 // if all else fails, check Delivered-To for possible pattern
233 if (!$matches and preg_match($regex, $mail->getHeader('Delivered-To'), $matches)) {
234 list($match, $action, $job, $queue, $hash) = $matches;
238 // preseve backward compatibility
239 if ($usedfor == 0 ||
!$civiMail) {
240 // if its the activities that needs to be processed ..
242 $mailParams = CRM_Utils_Mail_Incoming
::parseMailingObject($mail);
244 catch (Exception
$e) {
245 echo $e->getMessage();
246 $store->markIgnored($key);
250 require_once 'CRM/Utils/DeprecatedUtils.php';
251 $params = _civicrm_api3_deprecated_activity_buildmailparams($mailParams, $emailActivityTypeId);
253 $params['version'] = 3;
254 $result = civicrm_api('activity', 'create', $params);
256 if ($result['is_error']) {
258 echo "Failed Processing: {$mail->subject}. Reason: {$result['error_message']}\n";
262 echo "Processed as Activity: {$mail->subject}\n";
265 CRM_Utils_Hook
::emailProcessor('activity', $params, $mail, $result);
268 // if $matches is empty, this email is not CiviMail-bound
270 $store->markIgnored($key);
274 // get $replyTo from either the Reply-To header or from From
275 // FIXME: make sure it works with Reply-Tos containing non-email stuff
276 $replyTo = $mail->getHeader('Reply-To') ?
$mail->getHeader('Reply-To') : $mail->from
->email
;
278 // handle the action by passing it to the proper API call
279 // FIXME: leave only one-letter cases when dropping legacy support
280 if (!empty($action)) {
287 if ($mail->body
instanceof ezcMailText
) {
288 $text = $mail->body
->text
;
290 elseif ($mail->body
instanceof ezcMailMultipart
) {
291 if ($mail->body
instanceof ezcMailMultipartReport
) {
292 $part = $mail->body
->getMachinePart();
293 if ($part instanceof ezcMailDeliveryStatus
) {
294 foreach ($part->recipients
as $rec) {
295 if (isset($rec["Diagnostic-Code"])) {
296 $text = $rec["Diagnostic-Code"];
299 elseif (isset($rec["Description"])) {
300 $text = $rec["Description"];
303 // no diagnostic info present - try getting the human readable part
304 elseif (isset($rec["Status"])) {
305 $text = $rec["Status"];
306 $textpart = $mail->body
->getReadablePart();
307 if ($textpart != NULL and isset($textpart->text
)) {
308 $text .= " " . $textpart->text
;
311 $text .= " Delivery failed but no diagnostic code or description.";
317 elseif ($part != NULL and isset($part->text
)) {
320 elseif (($part = $mail->body
->getReadablePart()) != NULL) {
324 elseif ($mail->body
instanceof ezcMailMultipartRelated
) {
325 foreach ($mail->body
->getRelatedParts() as $part) {
326 if (isset($part->subType
) and $part->subType
== 'plain') {
333 foreach ($mail->body
->getParts() as $part) {
334 if (isset($part->subType
) and $part->subType
== 'plain') {
344 $mail->subject
== "Delivery Status Notification (Failure)"
346 // Exchange error - CRM-9361
347 foreach ($mail->body
->getParts() as $part) {
348 if ($part instanceof ezcMailDeliveryStatus
) {
349 foreach ($part->recipients
as $rec) {
350 if ($rec["Status"] == "5.1.1") {
351 if (isset($rec["Description"])) {
352 $text = $rec["Description"];
355 $text = $rec["Status"] . " Delivery to the following recipients failed";
365 // If bounce processing fails, just take the raw body. Cf. CRM-11046
366 $text = $mail->generateBody();
368 // if text is still empty, lets fudge a blank text so the api call below will succeed
370 $text = ts('We could not extract the mail body from this bounce message.');
376 'event_queue_id' => $queue,
381 $result = civicrm_api('Mailing', 'event_bounce', $params);
388 'contact_id' => $job,
389 'subscribe_id' => $queue,
393 $result = civicrm_api('Mailing', 'event_confirm', $params);
400 'event_queue_id' => $queue,
404 $result = civicrm_api('MailingGroup', 'event_domain_unsubscribe', $params);
409 // instead of text and HTML parts (4th and 6th params) send the whole email as the last param
412 'event_queue_id' => $queue,
415 'replyTo' => $replyTo,
417 'fullEmail' => $mail->generate(),
420 $result = civicrm_api('Mailing', 'event_reply', $params);
428 'event_queue_id' => $queue,
432 $result = civicrm_api('MailingGroup', 'event_resubscribe', $params);
438 'email' => $mail->from
->email
,
442 $result = civicrm_api('MailingGroup', 'event_subscribe', $params);
449 'event_queue_id' => $queue,
453 $result = civicrm_api('MailingGroup', 'event_unsubscribe', $params);
457 if ($result['is_error']) {
458 echo "Failed Processing: {$mail->subject}, Action: $action, Job ID: $job, Queue ID: $queue, Hash: $hash. Reason: {$result['error_message']}\n";
461 CRM_Utils_Hook
::emailProcessor('mailing', $params, $mail, $result, $action);
465 $store->markProcessed($key);
467 // CRM-7356 – used by IMAP only