2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
39 require_once('include/SugarPHPMailer.php');
42 if (isset($_REQUEST['mode']) && $_REQUEST['mode']=='test') {
45 if (isset($_REQUEST['send_all']) && $_REQUEST['send_all']== true) {
49 $send_all=false; //if set to true email delivery will continue..to run until all email have been delivered.
51 $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
52 $mail = new SugarPHPMailer();
53 $admin = new Administration();
54 $admin->retrieveSettings();
55 if (isset($admin->settings['massemailer_campaign_emails_per_run'])) {
56 $max_emails_per_run=$admin->settings['massemailer_campaign_emails_per_run'];
58 if (empty($max_emails_per_run)) {
59 $max_emails_per_run=500;//default
62 $massemailer_email_copy=0; //default: save copies of the email.
63 if (isset($admin->settings['massemailer_email_copy'])) {
64 $massemailer_email_copy=$admin->settings['massemailer_email_copy'];
67 $emailsPerSecond = 10;
69 $mail->setMailerForSystem();
70 $mail->From = "no-reply@example.com";
71 $mail->FromName = "no-reply";
72 $mail->ContentType="text/html";
75 if (isset($_REQUEST['campaign_id']) && !empty($_REQUEST['campaign_id'])) {
76 $campaign_id=$_REQUEST['campaign_id'];
79 $db = DBManagerFactory::getInstance();
80 $emailman = new EmailMan();
83 //if this is in test mode, then
84 //find all the message that meet the following criteria.
85 //1. scheduled send date time is now
86 //2. campaign matches the current campaign
87 //3. recipient belongs to a propsect list of type test, attached to this campaign
89 $select_query =" SELECT em.* FROM emailman em";
90 $select_query.=" join prospect_list_campaigns plc on em.campaign_id = plc.campaign_id";
91 $select_query.=" join prospect_lists pl on pl.id = plc.prospect_list_id ";
92 $select_query.=" WHERE em.list_id = pl.id and pl.list_type = 'test'";
93 $select_query.=" AND em.send_date_time <= ". db_convert("'".gmdate($GLOBALS['timedate']->get_db_date_time_format())."'" ,"datetime");
94 $select_query.=" AND (em.in_queue ='0' OR ( em.in_queue ='1' AND em.in_queue_date <= " .db_convert("'". gmdate($GLOBALS['timedate']->get_db_date_time_format(), strtotime("-1 day")) ."'" ,"datetime")."))";
95 $select_query.=" AND em.campaign_id='{$campaign_id}'";
96 $select_query.=" ORDER BY em.send_date_time ASC, em.user_id, em.list_id";
98 //this is not a test..
99 //find all the message that meet the following criteria.
100 //1. scheduled send date time is now
101 //2. were never processed or last attempt was 24 hours ago
102 $select_query =" SELECT *";
103 $select_query.=" FROM $emailman->table_name";
104 $select_query.=" WHERE send_date_time <= ". db_convert("'".gmdate($GLOBALS['timedate']->get_db_date_time_format())."'" ,"datetime");
105 $select_query.=" AND (in_queue ='0' OR ( in_queue ='1' AND in_queue_date <= " .db_convert("'". gmdate($GLOBALS['timedate']->get_db_date_time_format(), strtotime("-1 day")) ."'" ,"datetime")."))";
107 if (!empty($campaign_id)) {
108 $select_query.=" AND campaign_id='{$campaign_id}'";
110 $select_query.=" ORDER BY send_date_time ASC,user_id, list_id";
116 $no_items_in_queue=true;
118 $result = $db->limitQuery($select_query,0,$max_emails_per_run);
119 global $current_user;
120 if(isset($current_user)){
121 $temp_user = $current_user;
123 $current_user = new User();
124 $startTime = microtime(true);
126 while(($row = $db->fetchByAssoc($result))!= null){
128 //verify the queue item before further processing.
129 //we have found cases where users have taken away access to email templates while them message is in queue.
130 if (empty($row['campaign_id'])) {
131 $GLOBALS['log']->fatal('Skipping emailman entry with empty campaign id' . print_r($row,true));
134 if (empty($row['marketing_id'])) {
135 $GLOBALS['log']->fatal('Skipping emailman entry with empty marketing id' . print_r($row,true));
136 continue; //do not process this row .
139 //fetch user that scheduled the campaign.
140 if(empty($current_user) or $row['user_id'] != $current_user->id){
141 $current_user->retrieve($row['user_id']);
144 if (!$emailman->verify_campaign($row['marketing_id'])) {
145 $GLOBALS['log']->fatal('Error verifying templates for the campaign, exiting');
150 //verify the email template too..
151 //find the template associated with marketing message. make sure that template has a subject and
153 if (!isset($template_status[$row['marketing_id']])) {
154 if (!class_exists('EmailMarketing')) {
157 $current_emailmarketing=new EmailMarketing();
158 $current_emailmarketing->retrieve($row['marketing_id']);
160 if (!class_exists('EmailTemplate')) {
163 $current_emailtemplate= new EmailTemplate();
164 $current_emailtemplate->retrieve($current_emailmarketing->template_id);
169 //if the database does not support repeatable read isolation by default, we might get data that does not meet
170 //the criteria in the original query, and we care most about the in_queue_date and process_date_time,
171 //if they are null or in past(older than 24 horus) then we are okay.
172 $lock_query="UPDATE emailman SET in_queue=1, in_queue_date='". gmdate($GLOBALS['timedate']->get_db_date_time_format()) ."' WHERE id = '${row['id']}'";
173 $lock_query.=" AND (in_queue ='0' OR ( in_queue ='1' AND in_queue_date <= " .db_convert("'". gmdate($GLOBALS['timedate']->get_db_date_time_format(), strtotime("-1 day")) ."'" ,"datetime")."))";
175 //if the query fails to execute.. terminate campaign email process.
176 $lock_result=$db->query($lock_query,true,'Error acquiring a lock for emailman entry.');
177 if ($db->dbType=='oci8') {
179 $lock_count=$db->getAffectedRowCount();
182 //do not process the message if unable to acquire lock.
183 if ($lock_count!= 1) {
184 $GLOBALS['log']->fatal("Error acquiring lock for the emailman entry, skipping email delivery. lock status=$lock_count " . print_r($row,true));
185 continue; //do not process this row we will examine it after 24 hrs. the email address based dupe check is in place too.
188 $no_items_in_queue=false;
191 foreach($row as $name=>$value){
192 $emailman->$name = $value;
195 //for the campaign process the supression lists.
196 if (!isset($current_campaign_id) or empty($current_campaign_id) or $current_campaign_id != $row['campaign_id']) {
197 $current_campaign_id= $row['campaign_id'];
199 //is this email address suppressed?
200 $plc_query= " SELECT prospect_list_id, prospect_lists.list_type,prospect_lists.domain_name FROM prospect_list_campaigns ";
201 $plc_query.=" LEFT JOIN prospect_lists on prospect_lists.id = prospect_list_campaigns.prospect_list_id";
202 $plc_query.=" WHERE ";
203 $plc_query.=" campaign_id='{$current_campaign_id}' ";
204 $plc_query.=" AND prospect_lists.list_type in ('exempt_address','exempt_domain')";
205 $plc_query.=" AND prospect_list_campaigns.deleted=0";
206 $plc_query.=" AND prospect_lists.deleted=0";
208 $emailman->restricted_domains=array();
209 $emailman->restricted_addresses=array();
211 $result1=$db->query($plc_query);
212 while($row1 = $db->fetchByAssoc($result1)){
213 if ($row1['list_type']=='exempt_domain') {
214 $emailman->restricted_domains[strtolower($row1['domain_name'])]=1;
216 //find email address of targets in this prospect list.
217 $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";
218 $email_query_result=$db->query($email_query);
220 while($email_address = $db->fetchByAssoc($email_query_result)){
221 //ignore empty email addresses;
222 if (!empty($email_address['email_address'])) {
223 $emailman->restricted_addresses[strtolower($email_address['email_address'])]=1;
230 if(!$emailman->sendEmail($mail,$massemailer_email_copy,$test)){
231 $GLOBALS['log']->fatal("Email delivery FAILURE:" . print_r($row,true));
233 $GLOBALS['log']->debug("Email delivery SUCCESS:" . print_r($row,true));
235 if($mail->isError()){
236 $GLOBALS['log']->fatal("Email delivery error:" . print_r($row,true). $mail->ErrorInfo);
240 $send_all=$send_all?!$no_items_in_queue:$send_all;
242 }while ($send_all == true);
244 if ($admin->settings['mail_sendtype'] == "SMTP") {
247 if(isset($temp_user)){
248 $current_user = $temp_user;
250 if (isset($_REQUEST['return_module']) && isset($_REQUEST['return_action']) && isset($_REQUEST['return_id'])) {
252 if(isset($_REQUEST['from_wiz'])&& $_REQUEST['from_wiz']==true){
253 header("Location: index.php?module={$_REQUEST['return_module']}&action={$_REQUEST['return_action']}&record={$_REQUEST['return_id']}&from=test");
255 header("Location: index.php?module={$_REQUEST['return_module']}&action={$_REQUEST['return_action']}&record={$_REQUEST['return_id']}");
258 /* this will be triggered when manually sending off Email campaigns from the
259 * Mass Email Queue Manager.
261 if(isset($_POST['manual'])) {
262 header("Location: index.php?module=EmailMan&action=index");