]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Campaigns/ProcessBouncedEmails.php
Release 6.4.0
[Github/sugarcrm.git] / modules / Campaigns / ProcessBouncedEmails.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description:
41  ********************************************************************************/
42 //find all mailboxes of type bounce.
43
44 /**
45  * Retrieve the attached error report for a bounced email if it exists.
46  *
47  * @param Email $email
48  * @return string
49  */
50 function retrieveErrorReportAttachment($email)
51 {
52     $contents = "";
53     $query = "SELECT description FROM notes WHERE file_mime_type = 'messsage/rfc822' AND parent_type='Emails' AND parent_id = '".$email->id."' AND deleted=0";
54     $rs = $GLOBALS['db']->query($query);
55     while ($row = $GLOBALS['db']->fetchByAssoc($rs)) 
56                 $contents .= $row['description'];
57
58     return $contents;
59 }
60
61 /**
62  * Create a bounced log campaign entry
63  *
64  * @param array $row
65  * @param Email $email
66  * @param string $email_description
67  * @return string
68  */
69 function createBouncedCampaignLogEntry($row,$email, $email_description)
70 {
71     $GLOBALS['log']->debug("Creating bounced email campaign log");
72     $bounce = new CampaignLog();
73     $bounce->campaign_id=$row['campaign_id'];
74     $bounce->target_tracker_key=$row['target_tracker_key'];
75     $bounce->target_id= $row['target_id'];
76     $bounce->target_type=$row['target_type'];
77     $bounce->list_id=$row['list_id'];
78     $bounce->marketing_id=$row['marketing_id'];
79
80     $bounce->activity_date=$email->date_created;
81     $bounce->related_type='Emails';
82     $bounce->related_id= $email->id;
83
84     //do we have the phrase permanent error in the email body.
85     if (preg_match('/permanent[ ]*error/',$email_description)) 
86         $bounce->activity_type='invalid email';
87     else 
88         $bounce->activity_type='send error';
89         
90     $return_id=$bounce->save();
91     return $return_id;
92 }
93
94 /**
95  * Get the existing campaign log entry by tracker key.
96  * 
97  * @param string Target Key
98  * @return array Campaign Log Row
99  */
100 function getExistingCampaignLogEntry($identifier)
101 {
102     $row = FALSE;
103     $targeted = new CampaignLog();
104     $where="campaign_log.activity_type='targeted' and campaign_log.target_tracker_key='{$identifier}'";
105     $query=$targeted->create_new_list_query('',$where);
106     $result=$targeted->db->query($query);
107     $row=$targeted->db->fetchByAssoc($result);
108     
109     return $row;
110 }
111
112 /**
113  * Scan the bounced email searching for a valid target identifier.
114  * 
115  * @param string Email Description
116  * @return array Results including matches and identifier
117  */
118 function checkBouncedEmailForIdentifier($email_description)
119 {
120     $matches = array();
121     $identifiers = array();
122     $found = FALSE;
123     //Check if the identifier is present in the header.
124     if(preg_match('/X-CampTrackID: [a-z0-9\-]*/',$email_description,$matches)) 
125     {
126         $identifiers = preg_split('/X-CampTrackID: /',$matches[0],-1,PREG_SPLIT_NO_EMPTY);
127         $found = TRUE;
128         $GLOBALS['log']->debug("Found campaign identifier in header of email");  
129     }
130     else if( preg_match('/index.php\?entryPoint=removeme&identifier=[a-z0-9\-]*/',$email_description, $matches) )
131     {
132         $identifiers = preg_split('/index.php\?entryPoint=removeme&identifier=/',$matches[0],-1,PREG_SPLIT_NO_EMPTY);
133         $found = TRUE;
134         $GLOBALS['log']->debug("Found campaign identifier in body of email");
135     }
136     
137     return array('found' => $found, 'matches' => $matches, 'identifiers' => $identifiers);
138 }
139
140 function campaign_process_bounced_emails(&$email, &$email_header) 
141 {
142         global $sugar_config;
143         $emailFromAddress = $email_header->fromaddress;
144         $email_description = $email->raw_source;
145         
146         //if raw_source is empty, try using the description instead
147         if (empty($email_description)){
148                 $email_description = $email->description;
149         }
150
151     $email_description .= retrieveErrorReportAttachment($email);
152
153         if (preg_match('/MAILER-DAEMON|POSTMASTER/i',$emailFromAddress)) 
154         {
155             $email_description=quoted_printable_decode($email_description);
156                 $matches=array();
157                 
158                 //do we have the identifier tag in the email?
159                 $identifierScanResults = checkBouncedEmailForIdentifier($email_description);
160                 
161                 if ( $identifierScanResults['found'] ) 
162                 {
163                         $matches = $identifierScanResults['matches'];
164                         $identifiers = $identifierScanResults['identifiers'];
165
166                         if (!empty($identifiers)) 
167                         {
168                                 //array should have only one element in it.
169                                 $identifier = trim($identifiers[0]);
170                                 $row = getExistingCampaignLogEntry($identifier);
171                                 
172                                 //Found entry
173                                 if (!empty($row)) 
174                                 {
175                                         //do not create another campaign_log record is we already have an
176                                         //invalid email or send error entry for this tracker key.
177                                         $query_log = "select * from campaign_log where target_tracker_key='{$row['target_tracker_key']}'"; 
178                                         $query_log .=" and (activity_type='invalid email' or activity_type='send error')";
179                     $targeted = new CampaignLog();
180                                         $result_log=$targeted->db->query($query_log);
181                                         $row_log=$targeted->db->fetchByAssoc($result_log);
182
183                                         if (empty($row_log)) 
184                                         {
185                                                 $return_id = createBouncedCampaignLogEntry($row, $email, $email_description);   
186                                                 return TRUE;
187                                         }                               
188                                         else 
189                                         {
190                                             $GLOBALS['log']->debug("Warning: campaign log entry already exists for identifier $identifier");
191                                             return FALSE;
192                                         }
193                                 } 
194                                 else 
195                                 {
196                                     $GLOBALS['log']->info("Warning: skipping bounced email with this tracker_key(identifier) in the message body: ".$identifier);
197                                         return FALSE;
198                                 }                       
199                 } 
200                 else 
201                 {
202                         //todo mark the email address as invalid. search for prospects/leads/contact associated
203                         //with this email address and set the invalid_email flag... also make email available.
204                         $GLOBALS['log']->info("Warning: Empty identifier for campaign log.");
205                         return FALSE;
206                 }
207         }  
208         else 
209         {
210             $GLOBALS['log']->info("Warning: skipping bounced email because it does not have the removeme link.");       
211                 return FALSE;   
212         }
213   } 
214   else 
215   {
216         $GLOBALS['log']->info("Warning: skipping bounced email because the sender is not MAILER-DAEMON.");
217         return FALSE;
218   }
219 }
220 ?>