]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/EmailMan/EmailManDelivery.php
Release 6.5.11
[Github/sugarcrm.git] / modules / EmailMan / EmailManDelivery.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-2013 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 require_once('include/SugarPHPMailer.php');
40
41 $test=false;
42 if (isset($_REQUEST['mode']) && $_REQUEST['mode']=='test') {
43         $test=true;
44 }
45 if (isset($_REQUEST['send_all']) && $_REQUEST['send_all']== true) {
46         $send_all= true;
47 }
48 else  {
49         $send_all=false; //if set to true email delivery will continue..to run until all email have been delivered.
50 }
51
52 if(!isset($GLOBALS['log']))
53 {
54     $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
55 }
56
57 $mail = new SugarPHPMailer();
58 $admin = new Administration();
59 $admin->retrieveSettings();
60 if (isset($admin->settings['massemailer_campaign_emails_per_run'])) {
61         $max_emails_per_run=$admin->settings['massemailer_campaign_emails_per_run'];
62 }
63 if (empty($max_emails_per_run)) {
64         $max_emails_per_run=500;//default
65 }
66 //save email copies?
67 $massemailer_email_copy=0;  //default: save copies of the email.
68 if (isset($admin->settings['massemailer_email_copy'])) {
69     $massemailer_email_copy=$admin->settings['massemailer_email_copy'];
70 }
71
72 $emailsPerSecond = 10;
73
74 $mail->setMailerForSystem();
75 $mail->From     = "no-reply@example.com";
76 $mail->FromName = "no-reply";
77 $mail->ContentType="text/html";
78
79 $campaign_id=null;
80 if (isset($_REQUEST['campaign_id']) && !empty($_REQUEST['campaign_id'])) {
81         $campaign_id=$_REQUEST['campaign_id'];
82 }
83
84 $db = DBManagerFactory::getInstance();
85 $timedate = TimeDate::getInstance();
86 $emailman = new EmailMan();
87
88     if($test){
89         //if this is in test mode, then
90         //find all the message that meet the following criteria.
91         //1. scheduled send date time is now
92         //2. campaign matches the current campaign
93         //3. recipient belongs to a prospect list of type test, attached to this campaign
94
95         $select_query =" SELECT em.* FROM emailman em";
96         $select_query.=" join prospect_list_campaigns plc on em.campaign_id = plc.campaign_id";
97         $select_query.=" join prospect_lists pl on pl.id = plc.prospect_list_id ";
98         $select_query.=" WHERE em.list_id = pl.id and pl.list_type = 'test'";
99         $select_query.=" AND em.send_date_time <= ". $db->now();
100         $select_query.=" AND (em.in_queue ='0' OR em.in_queue IS NULL OR (em.in_queue ='1' AND em.in_queue_date <= " .$db->convert($db->quoted($timedate->fromString("-1 day")->asDb()),"datetime")."))";
101         $select_query.=" AND em.campaign_id='{$campaign_id}'";
102         $select_query.=" ORDER BY em.send_date_time ASC, em.user_id, em.list_id";
103     }else{
104         //this is not a test..
105         //find all the message that meet the following criteria.
106         //1. scheduled send date time is now
107         //2. were never processed or last attempt was 24 hours ago
108         $select_query =" SELECT *";
109         $select_query.=" FROM $emailman->table_name";
110         $select_query.=" WHERE send_date_time <= ". $db->now();
111         $select_query.=" AND (in_queue ='0' OR in_queue IS NULL OR ( in_queue ='1' AND in_queue_date <= " .$db->convert($db->quoted($timedate->fromString("-1 day")->asDb()),"datetime")."))";
112
113         if (!empty($campaign_id)) {
114             $select_query.=" AND campaign_id='{$campaign_id}'";
115         }
116         $select_query.=" ORDER BY send_date_time ASC,user_id, list_id";
117
118     }
119
120 //bug 26926 fix start
121 DBManager::setQueryLimit(0);
122 //end bug fix
123
124 do {
125
126         $no_items_in_queue=true;
127
128         $result = $db->limitQuery($select_query,0,$max_emails_per_run);
129         global $current_user;
130         if(isset($current_user)){
131                 $temp_user = $current_user;
132         }
133         $current_user = new User();
134         $startTime = microtime(true);
135
136         while(($row = $db->fetchByAssoc($result))!= null){
137
138         //verify the queue item before further processing.
139         //we have found cases where users have taken away access to email templates while them message is in queue.
140         if (empty($row['campaign_id'])) {
141             $GLOBALS['log']->fatal('Skipping emailman entry with empty campaign id' . print_r($row,true));
142             continue;
143         }
144         if (empty($row['marketing_id'])) {
145             $GLOBALS['log']->fatal('Skipping emailman entry with empty marketing id' . print_r($row,true));
146             continue;  //do not process this row .
147         }
148
149         //fetch user that scheduled the campaign.
150         if(empty($current_user) or $row['user_id'] != $current_user->id){
151             $current_user->retrieve($row['user_id']);
152         }
153
154         if (!$emailman->verify_campaign($row['marketing_id'])) {
155             $GLOBALS['log']->fatal('Error verifying templates for the campaign, exiting');
156             continue;
157         }
158
159
160         //verify the email template too..
161         //find the template associated with marketing message. make sure that template has a subject and
162         //a non-empty body
163         if (!isset($template_status[$row['marketing_id']])) {
164             if (!class_exists('EmailMarketing')) {
165
166             }
167             $current_emailmarketing=new EmailMarketing();
168             $current_emailmarketing->retrieve($row['marketing_id']);
169
170             if (!class_exists('EmailTemplate')) {
171
172             }
173             $current_emailtemplate= new EmailTemplate();
174             $current_emailtemplate->retrieve($current_emailmarketing->template_id);
175
176         }
177
178                 //acquire a lock.
179                 //if the database does not support repeatable read isolation by default, we might get data that does not meet
180         //the criteria in the original query, and we care most about the in_queue_date and process_date_time,
181         //if they are null or in past(older than 24 horus) then we are okay.
182
183                 $lock_query="UPDATE emailman SET in_queue=1, in_queue_date=". $db->now()." WHERE id = ".intval($row['id']);
184                 $lock_query.=" AND (in_queue ='0' OR in_queue IS NULL OR ( in_queue ='1' AND in_queue_date <= " .$db->convert($db->quoted($timedate->fromString("-1 day")->asDb()),"datetime")."))";
185
186                 //if the query fails to execute.. terminate campaign email process.
187                 $lock_result=$db->query($lock_query,true,'Error acquiring a lock for emailman entry.');
188                 $lock_count=$db->getAffectedRowCount($lock_result);
189
190                 //do not process the message if unable to acquire lock.
191                 if ($lock_count!= 1) {
192                         $GLOBALS['log']->fatal("Error acquiring lock for the emailman entry, skipping email delivery. lock status=$lock_count " . print_r($row,true));
193                         continue;  //do not process this row we will examine it after 24 hrs. the email address based dupe check is in place too.
194                 }
195
196                 $no_items_in_queue=false;
197
198
199                 foreach($row as $name=>$value){
200                         $emailman->$name = $value;
201                 }
202
203                 //for the campaign process the suppression lists.
204                 if (!isset($current_campaign_id) or empty($current_campaign_id) or $current_campaign_id != $row['campaign_id']) {
205                         $current_campaign_id= $row['campaign_id'];
206
207                         //is this email address suppressed?
208                         $plc_query= " SELECT prospect_list_id, prospect_lists.list_type,prospect_lists.domain_name FROM prospect_list_campaigns ";
209                         $plc_query.=" LEFT JOIN prospect_lists on prospect_lists.id = prospect_list_campaigns.prospect_list_id";
210                         $plc_query.=" WHERE ";
211                         $plc_query.=" campaign_id='{$current_campaign_id}' ";
212                         $plc_query.=" AND prospect_lists.list_type in ('exempt_address','exempt_domain')";
213                         $plc_query.=" AND prospect_list_campaigns.deleted=0";
214                         $plc_query.=" AND prospect_lists.deleted=0";
215
216                         $emailman->restricted_domains=array();
217                         $emailman->restricted_addresses=array();
218
219                         $result1=$db->query($plc_query);
220                         while($row1 = $db->fetchByAssoc($result1)){
221                                 if ($row1['list_type']=='exempt_domain') {
222                                         $emailman->restricted_domains[strtolower($row1['domain_name'])]=1;
223                                 } else {
224                                     //find email address of targets in this prospect list.
225                                         $email_query = "SELECT email_address FROM email_addresses ea JOIN email_addr_bean_rel eabr ON ea.id = eabr.email_address_id JOIN prospect_lists_prospects plp ON eabr.bean_id = plp.related_id AND eabr.bean_module = plp.related_type AND plp.prospect_list_id = '{$row1['prospect_list_id']}' and plp.deleted = 0";
226                                         $email_query_result=$db->query($email_query);
227
228                                         while($email_address = $db->fetchByAssoc($email_query_result)){
229                                                 //ignore empty email addresses;
230                                                 if (!empty($email_address['email_address'])) {
231                             $emailman->restricted_addresses[strtolower($email_address['email_address'])]=1;
232                                                 }
233                                         }
234                                 }
235                         }
236                 }
237
238                 if(!$emailman->sendEmail($mail,$massemailer_email_copy,$test)){
239                         $GLOBALS['log']->fatal("Email delivery FAILURE:" . print_r($row,true));
240                 } else {
241                         $GLOBALS['log']->debug("Email delivery SUCCESS:" . print_r($row,true));
242                 }
243                 if($mail->isError()){
244                         $GLOBALS['log']->fatal("Email delivery error:" . print_r($row,true). $mail->ErrorInfo);
245                 }
246         }
247
248         $send_all=$send_all?!$no_items_in_queue:$send_all;
249
250 }while ($send_all == true);
251
252 if ($admin->settings['mail_sendtype'] == "SMTP") {
253         $mail->SMTPClose();
254 }
255 if(isset($temp_user)){
256         $current_user = $temp_user;
257 }
258 if (isset($_REQUEST['return_module']) && isset($_REQUEST['return_action']) && isset($_REQUEST['return_id'])) {
259     $from_wiz=' ';
260     if(isset($_REQUEST['from_wiz'])&& $_REQUEST['from_wiz']==true){
261         header("Location: index.php?module={$_REQUEST['return_module']}&action={$_REQUEST['return_action']}&record={$_REQUEST['return_id']}&from=test");
262     }else{
263                 header("Location: index.php?module={$_REQUEST['return_module']}&action={$_REQUEST['return_action']}&record={$_REQUEST['return_id']}");
264     }
265 } else {
266         /* this will be triggered when manually sending off Email campaigns from the
267          * Mass Email Queue Manager.
268         */
269         if(isset($_POST['manual'])) {
270                 header("Location: index.php?module=EmailMan&action=index");
271         }
272 }
273 ?>