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-2012 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 ********************************************************************************/
40 class EmailMan extends SugarBean{
58 var $table_name = "emailman";
59 var $object_name = "EmailMan";
60 var $module_dir = "EmailMan";
65 var $notes_array = array();
66 var $verified_email_marketing_ids = array();
68 return "EmailMan:\nid = $this->id ,user_id= $this->user_id module = $this->module , related_id = $this->related_id , related_type = $this->related_type ,list_id = $this->list_id, send_date_time= $this->send_date_time\n";
71 // This is used to retrieve related fields from form posts.
72 var $additional_column_fields = array();
79 var $new_schema = true;
81 function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false) {
82 $query = array('select' => '', 'from' => '', 'where' => '', 'order_by' => '');
86 $query['select'] = "SELECT $this->table_name.* ,
87 campaigns.name as campaign_name,
88 email_marketing.name as message_name,
90 WHEN 'Contacts' THEN ".$this->db->concat('contacts', array('first_name', 'last_name'), ' ')."
91 WHEN 'Leads' THEN ".$this->db->concat('leads', array('first_name', 'last_name'), ' ')."
92 WHEN 'Accounts' THEN accounts.name
93 WHEN 'Users' THEN ".$this->db->concat('users', array('first_name', 'last_name'), ' ')."
94 WHEN 'Prospects' THEN ".$this->db->concat('prospects', array('first_name', 'last_name'), ' ')."
96 $query['from'] = " FROM $this->table_name
97 LEFT JOIN users ON users.id = $this->table_name.related_id and $this->table_name.related_type ='Users'
98 LEFT JOIN contacts ON contacts.id = $this->table_name.related_id and $this->table_name.related_type ='Contacts'
99 LEFT JOIN leads ON leads.id = $this->table_name.related_id and $this->table_name.related_type ='Leads'
100 LEFT JOIN accounts ON accounts.id = $this->table_name.related_id and $this->table_name.related_type ='Accounts'
101 LEFT JOIN prospects ON prospects.id = $this->table_name.related_id and $this->table_name.related_type ='Prospects'
102 LEFT JOIN prospect_lists ON prospect_lists.id = $this->table_name.list_id
103 LEFT JOIN email_addr_bean_rel ON email_addr_bean_rel.bean_id = $this->table_name.related_id and $this->table_name.related_type = email_addr_bean_rel.bean_module and email_addr_bean_rel.primary_address = 1 and email_addr_bean_rel.deleted=0
104 LEFT JOIN campaigns ON campaigns.id = $this->table_name.campaign_id
105 LEFT JOIN email_marketing ON email_marketing.id = $this->table_name.marketing_id ";
107 $where_auto = " $this->table_name.deleted=0";
110 $query['where'] = "WHERE $where AND ".$where_auto;
112 $query['where'] = "WHERE ".$where_auto;
114 if(isset($params['group_by'])) {
115 $query['order_by'] .= " GROUP BY {$params['group_by']}";
120 $query['order_by'] = ' ORDER BY ' . $this->process_order_by($order_by, null);
127 return $query['select'] . $query['from'] . $query['where']. $query['order_by'];
131 function create_queue_items_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean=null, $singleSelect = false) {
134 return parent::create_new_list_query($order_by, $where,$filter,$params, $show_deleted,$join_type, $return_array,$parentbean, $singleSelect);
137 $query = "SELECT $this->table_name.* ,
138 campaigns.name as campaign_name,
139 email_marketing.name as message_name,
141 WHEN 'Contacts' THEN ".$this->db->concat('contacts', array('first_name', 'last_name'), ' ')."
142 WHEN 'Leads' THEN ".$this->db->concat('leads', array('first_name', 'last_name'), ' ')."
143 WHEN 'Accounts' THEN accounts.name
144 WHEN 'Users' THEN ".$this->db->concat('users', array('first_name', 'last_name'), ' ')."
145 WHEN 'Prospects' THEN ".$this->db->concat('prospects', array('first_name', 'last_name'), ' ')."
146 END) recipient_name";
148 $query .= " FROM $this->table_name
149 LEFT JOIN users ON users.id = $this->table_name.related_id and $this->table_name.related_type ='Users'
150 LEFT JOIN contacts ON contacts.id = $this->table_name.related_id and $this->table_name.related_type ='Contacts'
151 LEFT JOIN leads ON leads.id = $this->table_name.related_id and $this->table_name.related_type ='Leads'
152 LEFT JOIN accounts ON accounts.id = $this->table_name.related_id and $this->table_name.related_type ='Accounts'
153 LEFT JOIN prospects ON prospects.id = $this->table_name.related_id and $this->table_name.related_type ='Prospects'
154 LEFT JOIN prospect_lists ON prospect_lists.id = $this->table_name.list_id
155 LEFT JOIN email_addr_bean_rel ON email_addr_bean_rel.bean_id = $this->table_name.related_id and $this->table_name.related_type = email_addr_bean_rel.bean_module and email_addr_bean_rel.primary_address = 1 and email_addr_bean_rel.deleted=0
156 LEFT JOIN campaigns ON campaigns.id = $this->table_name.campaign_id
157 LEFT JOIN email_marketing ON email_marketing.id = $this->table_name.marketing_id ";
160 if( isset($params['group_by']) )
162 $group_by = str_replace("emailman", "em", $params['group_by']);
163 $query .= "INNER JOIN (select min(id) as id from emailman em GROUP BY $group_by ) secondary
164 on {$this->table_name}.id = secondary.id ";
167 $where_auto = " $this->table_name.deleted=0";
170 $query .= "WHERE $where AND ".$where_auto;
172 $query .= "WHERE ".$where_auto;
177 $query .= ' ORDER BY ' . $this->process_order_by($order_by, null);
184 function create_list_query($order_by, $where, $show_deleted = 0){
186 $query = "SELECT $this->table_name.* ,
187 campaigns.name as campaign_name,
188 email_marketing.name as message_name,
190 WHEN 'Contacts' THEN ".$this->db->concat('contacts', array('first_name', 'last_name'), ' ')."
191 WHEN 'Leads' THEN ".$this->db->concat('leads', array('first_name', 'last_name'), ' ')."
192 WHEN 'Accounts' THEN accounts.name
193 WHEN 'Users' THEN ".$this->db->concat('users', array('first_name', 'last_name'), ' ')."
194 WHEN 'Prospects' THEN ".$this->db->concat('prospects', array('first_name', 'last_name'), ' ')."
195 END) recipient_name";
196 $query .= " FROM $this->table_name
197 LEFT JOIN users ON users.id = $this->table_name.related_id and $this->table_name.related_type ='Users'
198 LEFT JOIN contacts ON contacts.id = $this->table_name.related_id and $this->table_name.related_type ='Contacts'
199 LEFT JOIN leads ON leads.id = $this->table_name.related_id and $this->table_name.related_type ='Leads'
200 LEFT JOIN accounts ON accounts.id = $this->table_name.related_id and $this->table_name.related_type ='Accounts'
201 LEFT JOIN prospects ON prospects.id = $this->table_name.related_id and $this->table_name.related_type ='Prospects'
202 LEFT JOIN prospect_lists ON prospect_lists.id = $this->table_name.list_id
203 LEFT JOIN email_addr_bean_rel ON email_addr_bean_rel.bean_id = $this->table_name.related_id and $this->table_name.related_type = email_addr_bean_rel.bean_module and email_addr_bean_rel.primary_address = 1 and email_addr_bean_rel.deleted=0
204 LEFT JOIN campaigns ON campaigns.id = $this->table_name.campaign_id
205 LEFT JOIN email_marketing ON email_marketing.id = $this->table_name.marketing_id ";
207 $where_auto = " $this->table_name.deleted=0";
210 $query .= "where $where AND ".$where_auto;
212 $query .= "where ".$where_auto;
216 $query .= ' ORDER BY ' . $this->process_order_by($order_by, null);
221 function get_list_view_data()
223 global $locale, $current_user;
224 $temp_array = parent::get_list_view_array();
226 $related_type = $temp_array['RELATED_TYPE'];
227 $related_id = $temp_array['RELATED_ID'];
228 $is_person = SugarModule::get($related_type)->moduleImplements('Person');
232 $query = "SELECT first_name, last_name FROM ". strtolower($related_type) ." WHERE id ='". $related_id ."'";
234 $query = "SELECT name FROM ". strtolower($related_type) ." WHERE id ='". $related_id ."'";
237 $result=$this->db->query($query);
238 $row=$this->db->fetchByAssoc($result);
242 $temp_array['RECIPIENT_NAME'] = $is_person ? $locale->getLocaleFormattedName($row['first_name'], $row['last_name'], '') : $row['name'];
245 //also store the recipient_email address
246 $query = "SELECT addr.email_address FROM email_addresses addr,email_addr_bean_rel eb WHERE eb.deleted=0 AND addr.id=eb.email_address_id AND bean_id ='". $related_id ."' AND primary_address = '1'";
248 $result=$this->db->query($query);
249 $row=$this->db->fetchByAssoc($result);
252 $temp_array['RECIPIENT_EMAIL']=$row['email_address'];
255 $this->email1 = $temp_array['RECIPIENT_EMAIL'];
256 $temp_array['EMAIL1_LINK'] = $current_user->getEmailLink('email1', $this, '', '', 'ListView');
262 function set_as_sent($email_address, $delete= true,$email_id=null, $email_type=null,$activity_type=null){
266 $this->send_attempts++;
267 $this->id = (int)$this->id;
268 if($delete || $this->send_attempts > 5){
270 //create new campaign log record.
272 $campaign_log = new CampaignLog();
273 $campaign_log->campaign_id=$this->campaign_id;
274 $campaign_log->target_tracker_key=$this->target_tracker_key;
275 $campaign_log->target_id= $this->related_id;
276 $campaign_log->target_type=$this->related_type;
277 $campaign_log->marketing_id=$this->marketing_id;
278 //if test suppress duplicate email address checking.
280 $campaign_log->more_information=$email_address;
282 $campaign_log->activity_type=$activity_type;
283 $campaign_log->activity_date=$timedate->now();
284 $campaign_log->list_id=$this->list_id;
285 $campaign_log->related_id= $email_id;
286 $campaign_log->related_type=$email_type;
287 $campaign_log->save();
289 $query = "DELETE FROM emailman WHERE id = $this->id";
290 $this->db->query($query);
292 //try to send the email again a day later.
293 $query = 'UPDATE ' . $this->table_name . " SET in_queue='1', send_attempts='$this->send_attempts', in_queue_date=". $this->db->now() ." WHERE id = $this->id";
294 $this->db->query($query);
299 * Function finds the reference email for the campaign. Since a campaign can have multiple email templates
300 * the reference email has same id as the marketing id.
301 * this function will create an email if one does not exist. also the function will load these relationships leads, accounts, contacts
304 * @param varchar marketing_id message id
305 * @param string $subject email subject
306 * @param string $body_text Email Body Text
307 * @param string $body_html Email Body HTML
308 * @param string $campaign_name Campaign Name
309 * @param string from_address Email address of the sender, usually email address of the configured inbox.
310 * @param string sender_id If of the user sending the campaign.
311 * @param array macro_nv array of name value pair, one row for each replacable macro in email template text.
314 function create_ref_email($marketing_id,$subject,$body_text,$body_html,$campagin_name,$from_address,$sender_id,$notes,$macro_nv,$newmessage) {
316 global $mod_Strings, $timedate;
317 $upd_ref_email=false;
318 if ($newmessage or empty($this->ref_email->id)) {
319 $this->ref_email = new Email();
320 $this->ref_email->retrieve($marketing_id, true, false);
322 //the reference email should be updated when user swithces from test mode to regular mode,and, for every run in test mode, and is user
323 //switches back to test mode.
324 //this is to account for changes to email template.
325 $upd_ref_email=(!empty($this->ref_email->id) and $this->ref_email->parent_type=='test' and $this->ref_email->parent_id=='test');
326 //following condition is for switching back to test mode.
327 if (!$upd_ref_email) $upd_ref_email=($this->test and !empty($this->ref_email->id) and empty($this->ref_email->parent_type) and empty($this->ref_email->parent_id));
328 if (empty($this->ref_email->id) or $upd_ref_email) {
329 //create email record.
330 $this->ref_email->id=$marketing_id;
331 $this->ref_email->date_sent = '';
333 if ($upd_ref_email==false) {
334 $this->ref_email->new_with_id=true;
337 $this->ref_email->to_addrs= '';
338 $this->ref_email->to_addrs_ids = '';
339 $this->ref_email->to_addrs_names = '';
340 $this->ref_email->to_addrs_emails ='';
341 $this->ref_email->type= 'campaign';
342 $this->ref_email->deleted = '0';
343 $this->ref_email->name = $campagin_name.': '.$subject ;
344 $this->ref_email->description_html = $body_html;
345 $this->ref_email->description = $body_text;
346 $this->ref_email->from_addr = $from_address;
347 $this->ref_email->assigned_user_id = $sender_id;
349 $this->ref_email->parent_type = 'test';
350 $this->ref_email->parent_id = 'test';
352 $this->ref_email->parent_type = '';
353 $this->ref_email->parent_id = '';
355 $this->ref_email->date_start = $timedate->nowDate();
356 $this->ref_email->time_start = $timedate->asUserTime($timedate->getNow(true));
358 $this->ref_email->status='sent';
359 $retId = $this->ref_email->save();
361 foreach($notes as $note) {
362 if($note->object_name == 'Note') {
363 if (! empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) {
364 $file_location = $note->file->temp_file_location;
365 $filename = $note->file->original_file_name;
366 $mime_type = $note->file->mime_type;
368 $file_location = "upload://{$note->id}";
369 $filename = $note->id.$note->filename;
370 $mime_type = $note->file_mime_type;
372 } elseif($note->object_name == 'DocumentRevision') { // from Documents
373 $filename = $note->id.$note->filename;
374 $file_location = "upload://$filename";
375 $mime_type = $note->file_mime_type;
378 $noteAudit = new Note();
379 $noteAudit->parent_id = $retId;
380 $noteAudit->parent_type = $this->ref_email->module_dir;
381 $noteAudit->description = "[".$note->filename."] ".$mod_strings['LBL_ATTACHMENT_AUDIT'];
382 $noteAudit->filename=$filename;
383 $noteAudit->file_mime_type=$mime_type;
384 $noteAudit_id=$noteAudit->save();
386 UploadFile::duplicate_file($note->id, $noteAudit_id, $filename);
390 //load relationships.
391 $this->ref_email->load_relationship('users');
392 $this->ref_email->load_relationship('prospects');
393 $this->ref_email->load_relationship('contacts');
394 $this->ref_email->load_relationship('leads');
395 $this->ref_email->load_relationship('accounts');
398 if (!empty($this->related_id ) && !empty($this->related_type)) {
400 //save relationships.
401 switch ($this->related_type) {
407 $rel_name="prospects";
411 $rel_name="contacts";
419 $rel_name="accounts";
423 //required for one email per campaign per marketing message.
424 $this->ref_email->$rel_name->add($this->related_id,array('campaign_data'=>serialize($macro_nv)));
426 return $this->ref_email->id;
430 * The function creates a copy of email send to each target.
432 function create_indiv_email($module,$mail) {
434 global $locale, $timedate;
435 $email = new Email();
436 $email->to_addrs= $module->name . '<'.$module->email1.'>';
437 $email->to_addrs_ids = $module->id .';';
438 $email->to_addrs_names = $module->name . ';';
439 $email->to_addrs_emails = $module->email1 . ';';
440 $email->type= 'archived';
441 $email->deleted = '0';
442 $email->name = $this->current_campaign->name.': '.$mail->Subject ;
443 if ($mail->ContentType == "text/plain") {
444 $email->description = $mail->Body;
445 $email->description_html =null;
447 $email->description_html = $mail->Body;
448 $email->description = $mail->AltBody;
450 $email->from_addr = $mail->From;
451 $email->assigned_user_id = $this->user_id;
452 $email->parent_type = $this->related_type;
453 $email->parent_id = $this->related_id ;
455 $email->date_start = $timedate->nowDbDate();
456 $email->time_start = $timedate->asDbTime($timedate->getNow());
457 $email->status='sent';
458 $retId = $email->save();
460 foreach($this->notes_array as $note) {
461 if(!class_exists('Note')) {
464 // create "audit" email without duping off the file to save on disk space
465 $noteAudit = new Note();
466 $noteAudit->parent_id = $retId;
467 $noteAudit->parent_type = $email->module_dir;
468 $noteAudit->description = "[".$note->filename."] ".$mod_strings['LBL_ATTACHMENT_AUDIT'];
472 if (!empty($this->related_id ) && !empty($this->related_type)) {
474 //save relationships.
475 switch ($this->related_type) {
481 $rel_name="prospects";
485 $rel_name="contacts";
493 $rel_name="accounts";
497 if (!empty($rel_name)) {
498 $email->load_relationship($rel_name);
499 $email->$rel_name->add($this->related_id);
505 * Call this function to verify the email_marketing message and email_template configured
506 * for the campaign. If issues are found a fatal error will be logged but processing will not stop.
507 * @return Boolean Returns true if all campaign parameters are set correctly
509 function verify_campaign($marketing_id) {
511 if (!isset($this->verified_email_marketing_ids[$marketing_id])) {
512 if (!class_exists('EmailMarketing')) {
515 $email_marketing = new EmailMarketing();
516 $ret=$email_marketing->retrieve($marketing_id);
518 $GLOBALS['log']->fatal('Error retrieving marketing message for the email campaign. marketing_id = ' .$marketing_id);
522 //verify the email template.
523 if (empty($email_marketing->template_id)) {
524 $GLOBALS['log']->fatal('Error retrieving template for the email campaign. marketing_id = ' .$marketing_id);
528 if (!class_exists('EmailTemplate')) {
531 $emailtemplate= new EmailTemplate();
533 $ret=$emailtemplate->retrieve($email_marketing->template_id);
535 $GLOBALS['log']->fatal('Error retrieving template for the email campaign. template_id = ' .$email_marketing->template_id);
539 if (empty($emailtemplate->subject) and empty($emailtemplate->body) and empty($emailtemplate->body_html)) {
540 $GLOBALS['log']->fatal('Email template is empty. email_template_id=' .$email_marketing->template_id);
545 $this->verified_email_marketing_ids[$marketing_id]=1;
549 function sendEmail($mail,$save_emails=1,$testmode=false){
550 $this->test=$testmode;
552 global $beanList, $beanFiles, $sugar_config;
555 $OBCharset = $locale->getPrecedentPreference('default_email_charset');
556 $mod_strings = return_module_language( $sugar_config['default_language'], 'EmailMan');
558 //get tracking entities locations.
559 if (!isset($this->tracking_url)) {
560 if (!class_exists('Administration')) {
563 $admin=new Administration();
564 $admin->retrieveSettings('massemailer'); //retrieve all admin settings.
565 if (isset($admin->settings['massemailer_tracking_entities_location_type']) and $admin->settings['massemailer_tracking_entities_location_type']=='2' and isset($admin->settings['massemailer_tracking_entities_location']) ) {
566 $this->tracking_url=$admin->settings['massemailer_tracking_entities_location'];
568 $this->tracking_url=$sugar_config['site_url'];
572 //make sure tracking url ends with '/' character
573 $strLen = strlen($this->tracking_url);
574 if($this->tracking_url{$strLen-1} !='/'){
575 $this->tracking_url .='/';
578 if(!isset($beanList[$this->related_type])){
581 $class = $beanList[$this->related_type];
582 if (!class_exists($class)) {
583 require_once($beanFiles[$class]);
586 if (!class_exists('Email')) {
590 $module = new $class();
591 $module->retrieve($this->related_id);
592 $module->emailAddress->handleLegacyRetrieve($module);
594 //check to see if bean has a primary email address
595 if (!$this->is_primary_email_address($module)) {
596 //no primary email address designated, do not send out email, create campaign log
597 //of type send error to denote that this user was not emailed
598 $this->set_as_sent($module->email1, true,null,null,'send error');
599 //create fatal logging for easy review of cause.
600 $GLOBALS['log']->fatal('Email Address provided is not Primary Address for email with id ' . $module->email1 . "' Emailman id=$this->id");
604 if (!$this->valid_email_address($module->email1)) {
605 $this->set_as_sent($module->email1, true,null,null,'invalid email');
606 $GLOBALS['log']->fatal('Encountered invalid email address' . $module->email1 . " Emailman id=$this->id");
610 if ((!isset($module->email_opt_out)
611 || ($module->email_opt_out !== 'on'
612 && $module->email_opt_out !== 1
613 && $module->email_opt_out !== '1'))
614 && (!isset($module->invalid_email)
615 || ($module->invalid_email !== 'on'
616 && $module->invalid_email !== 1
617 && $module->invalid_email !== '1'))){
618 $lower_email_address=strtolower($module->email1);
619 //test against indivdual address.
620 if (isset($this->restricted_addresses) and isset($this->restricted_addresses[$lower_email_address])) {
621 $this->set_as_sent($lower_email_address, true,null,null,'blocked');
624 //test against restricted domains
625 $at_pos=strrpos($lower_email_address,'@');
626 if ($at_pos !== false) {
627 foreach ($this->restricted_domains as $domain=>$value) {
628 $pos=strrpos($lower_email_address,$domain);
629 if ($pos !== false && $pos > $at_pos) {
631 $this->set_as_sent($lower_email_address, true,null,null,'blocked');
637 //test for duplicate email address by marketing id.
638 $dup_query="select id from campaign_log where more_information='".$module->email1."' and marketing_id='".$this->marketing_id."'";
639 $dup=$this->db->query($dup_query);
640 $dup_row=$this->db->fetchByAssoc($dup);
641 if (!empty($dup_row)) {
642 //we have seen this email address before
643 $this->set_as_sent($module->email1,true,null,null,'blocked');
647 $this->target_tracker_key=create_guid();
649 //fetch email marketing.
650 if (empty($this->current_emailmarketing) or !isset($this->current_emailmarketing)) {
651 if (!class_exists('EmailMarketing')) {
655 $this->current_emailmarketing=new EmailMarketing();
658 if (empty($this->current_emailmarketing->id) or $this->current_emailmarketing->id !== $this->marketing_id) {
659 $this->current_emailmarketing->retrieve($this->marketing_id);
661 $this->newmessage = true;
663 //fetch email template associate with the marketing message.
664 if (empty($this->current_emailtemplate) or $this->current_emailtemplate->id !== $this->current_emailmarketing->template_id) {
665 if (!class_exists('EmailTemplate')) {
668 $this->current_emailtemplate= new EmailTemplate();
670 $this->current_emailtemplate->retrieve($this->current_emailmarketing->template_id);
672 //escape email template contents.
673 $this->current_emailtemplate->subject=from_html($this->current_emailtemplate->subject);
674 $this->current_emailtemplate->body_html=from_html($this->current_emailtemplate->body_html);
675 $this->current_emailtemplate->body=from_html($this->current_emailtemplate->body);
677 $q = "SELECT * FROM notes WHERE parent_id = '".$this->current_emailtemplate->id."' AND deleted = 0";
678 $r = $this->db->query($q);
680 // cn: bug 4684 - initialize the notes array, else old data is still around for the next round
681 $this->notes_array = array();
682 if (!class_exists('Note')){
683 require_once('modules/Notes/Note.php');
685 while($a = $this->db->fetchByAssoc($r)) {
686 $noteTemplate = new Note();
687 $noteTemplate->retrieve($a['id']);
688 $this->notes_array[] = $noteTemplate;
692 // fetch mailbox details..
693 if(empty($this->current_mailbox)) {
694 if (!class_exists('InboundEmail')) {
697 $this->current_mailbox= new InboundEmail();
699 if (empty($this->current_mailbox->id) or $this->current_mailbox->id !== $this->current_emailmarketing->inbound_email_id) {
700 $this->current_mailbox->retrieve($this->current_emailmarketing->inbound_email_id);
701 //extract the email address.
702 $this->mailbox_from_addr=$this->current_mailbox->get_stored_options('from_addr','nobody@example.com',null);
705 // fetch campaign details..
706 if (empty($this->current_campaign)) {
707 if (!class_exists('Campaign')) {
710 $this->current_campaign= new Campaign();
712 if (empty($this->current_campaign->id) or $this->current_campaign->id !== $this->current_emailmarketing->campaign_id) {
713 $this->current_campaign->retrieve($this->current_emailmarketing->campaign_id);
715 //load defined tracked_urls
716 $this->current_campaign->load_relationship('tracked_urls');
717 $query_array=$this->current_campaign->tracked_urls->getQuery(true);
718 $query_array['select']="SELECT tracker_name, tracker_key, id, is_optout ";
719 $result=$this->current_campaign->db->query(implode(' ',$query_array));
721 $this->has_optout_links=false;
722 $this->tracker_urls=array();
723 while (($row=$this->current_campaign->db->fetchByAssoc($result)) != null) {
724 $this->tracker_urls['{'.$row['tracker_name'].'}']=$row;
725 //has the user defined opt-out links for the campaign.
726 if ($row['is_optout']==1) {
727 $this->has_optout_links=true;
732 $mail->ClearAllRecipients();
733 $mail->ClearReplyTos();
734 $mail->Sender = $this->mailbox_from_addr;
735 $mail->From = $this->mailbox_from_addr;
736 $mail->FromName = $this->current_emailmarketing->from_name;
737 $mail->ClearCustomHeaders();
738 $mail->AddCustomHeader('X-CampTrackID:'.$this->target_tracker_key);
739 //CL - Bug 25256 Check if we have a reply_to_name/reply_to_addr value from the email marketing table. If so use email marketing entry; otherwise current mailbox (inbound email) entry
740 $replyToName = empty($this->current_emailmarketing->reply_to_name) ? $this->current_mailbox->get_stored_options('reply_to_name',$mail->FromName,null) : $this->current_emailmarketing->reply_to_name;
741 $replyToAddr = empty($this->current_emailmarketing->reply_to_addr) ? $this->current_mailbox->get_stored_options('reply_to_addr',$mail->From,null) : $this->current_emailmarketing->reply_to_addr;
743 $mail->AddReplyTo($replyToAddr,$locale->translateCharsetMIME(trim($replyToName), 'UTF-8', $OBCharset));
745 //parse and replace bean variables.
747 $focus_name = 'Contacts';
748 if($module->module_dir == 'Accounts')
750 $focus_name = 'Accounts';
754 $template_data= $this->current_emailtemplate->parse_email_template(array('subject'=>$this->current_emailtemplate->subject,
755 'body_html'=>$this->current_emailtemplate->body_html,
756 'body'=>$this->current_emailtemplate->body,
758 ,$focus_name, $module
761 //add email address to this list.
762 $macro_nv['sugar_to_email_address']=$module->email1;
763 $macro_nv['email_template_id']=$this->current_emailmarketing->template_id;
765 //parse and replace urls.
766 //this is new style of adding tracked urls to a campaign.
767 $tracker_url_template= $this->tracking_url . 'index.php?entryPoint=campaign_trackerv2&track=%s'.'&identifier='.$this->target_tracker_key;
768 $removeme_url_template=$this->tracking_url . 'index.php?entryPoint=removeme&identifier='.$this->target_tracker_key;
769 $template_data= $this->current_emailtemplate->parse_tracker_urls($template_data,$tracker_url_template,$this->tracker_urls,$removeme_url_template);
770 $mail->AddAddress($module->email1,$locale->translateCharsetMIME(trim($module->name), 'UTF-8', $OBCharset) );
772 //refetch strings in case they have been changed by creation of email templates or other beans.
773 $mod_strings = return_module_language( $sugar_config['default_language'], 'EmailMan');
776 $mail->Subject = $mod_strings['LBL_PREPEND_TEST'] . $template_data['subject'];
778 $mail->Subject = $template_data['subject'];
781 //check if this template is meant to be used as "text only"
783 if(isset($this->current_emailtemplate->text_only) && $this->current_emailtemplate->text_only){$text_only =true;}
784 //if this template is textonly, then just send text body. Do not add tracker, opt out,
785 //or perform other processing as it will not show up in text only email
787 $this->description_html = '';
788 $mail->IsHTML(false);
789 $mail->Body = $template_data['body'];
792 $mail->Body = wordwrap($template_data['body_html'], 900);
793 //BEGIN:this code will trigger for only campaigns pending before upgrade to 4.2.0.
794 //will be removed for the next release.
795 if(!isset($btracker)) $btracker=false;
797 $mail->Body .= "<br /><br /><a href='". $tracker_url ."'>" . $tracker_text . "</a><br /><br />";
799 if (!empty($tracker_url)) {
800 $mail->Body = str_replace('TRACKER_URL_START', "<a href='" . $tracker_url ."'>", $mail->Body);
801 $mail->Body = str_replace('TRACKER_URL_END', "</a>", $mail->Body);
802 $mail->AltBody = str_replace('TRACKER_URL_START', "<a href='" . $tracker_url ."'>", $mail->AltBody);
803 $mail->AltBody = str_replace('TRACKER_URL_END', "</a>", $mail->AltBody);
808 //do not add the default remove me link if the campaign has a trackerurl of the opotout link
809 if ($this->has_optout_links==false) {
810 $mail->Body .= "<br /><span style='font-size:0.8em'>{$mod_strings['TXT_REMOVE_ME']} <a href='". $this->tracking_url . "index.php?entryPoint=removeme&identifier={$this->target_tracker_key}'>{$mod_strings['TXT_REMOVE_ME_CLICK']}</a></span>";
812 // cn: bug 11979 - adding single quote to comform with HTML email RFC
813 $mail->Body .= "<br /><img alt='' height='1' width='1' src='{$this->tracking_url}index.php?entryPoint=image&identifier={$this->target_tracker_key}' />";
815 $mail->AltBody = $template_data['body'];
817 $mail->AltBody .="\n". $tracker_url;
819 if ($this->has_optout_links==false) {
820 $mail->AltBody .="\n\n\n{$mod_strings['TXT_REMOVE_ME_ALT']} ". $this->tracking_url . "index.php?entryPoint=removeme&identifier=$this->target_tracker_key";
825 // cn: bug 4684, handle attachments in email templates.
826 $mail->handleAttachments($this->notes_array);
827 $tmp_Subject = $mail->Subject;
828 $mail->prepForOutbound();
830 $success = $mail->Send();
831 //Do not save the encoded subject.
832 $mail->Subject = $tmp_Subject;
835 if ($save_emails==1) {
836 $email_id=$this->create_indiv_email($module,$mail);
838 //find/create reference email record. all campaign targets reveiving this message will be linked with this message.
839 $email_id=$this->create_ref_email($this->marketing_id,
840 $this->current_emailtemplate->subject,
841 $this->current_emailtemplate->body,
842 $this->current_emailtemplate->body_html,
843 $this->current_campaign->name,
844 $this->mailbox_from_addr,
850 $this->newmessage = false;
855 $this->set_as_sent($module->email1, true, $email_id, 'Emails', 'targeted');
858 if(!empty($layout_def['parent_id'])) {
859 if (isset($layout_def['fields'][strtoupper($layout_def['parent_id'])])) {
860 $parent.="&parent_id=".$layout_def['fields'][strtoupper($layout_def['parent_id'])];
863 if(!empty($layout_def['parent_module'])) {
864 if (isset($layout_def['fields'][strtoupper($layout_def['parent_module'])])) {
865 $parent.="&parent_module=".$layout_def['fields'][strtoupper($layout_def['parent_module'])];
868 //log send error. save for next attempt after 24hrs. no campaign log entry will be created.
869 $this->set_as_sent($module->email1,false,null,null,'send error');
873 $this->target_tracker_key=create_guid();
875 if (isset($module->email_opt_out) && ($module->email_opt_out === 'on' || $module->email_opt_out == '1' || $module->email_opt_out == 1)) {
876 $this->set_as_sent($module->email1,true,null,null,'removed');
878 if (isset($module->invalid_email) && ($module->invalid_email == 1 || $module->invalid_email == '1')) {
879 $this->set_as_sent($module->email1,true,null,null,'invalid email');
881 $this->set_as_sent($module->email1,true, null,null,'send error');
890 * Validates the passed email address.
891 * Limitations of this algorithm: does not validate email addressess that end with .meuseum
894 function valid_email_address($email_address) {
896 $email_address=trim($email_address);
897 if (empty($email_address)) {
901 $pattern='/[A-Z0-9\._%-]+@[A-Z0-9\.-]+\.[A-Za-z]{2,}$/i';
902 $ret=preg_match($pattern, $email_address);
904 if ($ret===false or $ret==0) {
911 * This function takes in the given bean and searches for a related email address
912 * that has been designated as primary. If one is found, true is returned
913 * If no primary email address is found, then false is returned
916 function is_primary_email_address($bean){
917 $email_address=trim($bean->email1);
919 if (empty($email_address)) {
922 //query for this email address rel and see if this is primary address
923 $primary_qry = "select email_address_id from email_addr_bean_rel where bean_id = '".$bean->id."' and email_addr_bean_rel.primary_address=1 and deleted=0";
924 $res = $bean->db->query($primary_qry);
925 $prim_row=$this->db->fetchByAssoc($res);
926 //return true if this is primary
927 if (!empty($prim_row)) {
934 function create_export_query(&$order_by, &$where) {
935 $custom_join = $this->custom_fields->getJOIN(true, true,$where);
936 $query = "SELECT emailman.*";
938 $query .= $custom_join['select'];
941 $query .= " FROM emailman ";
944 $query .= $custom_join['join'];
947 $where_auto = "( emailman.deleted IS NULL OR emailman.deleted=0 )";
950 $query .= "where ($where) AND ".$where_auto;
952 $query .= "where ".$where_auto;
954 if(!empty($order_by))
956 $query .= ' ORDER BY '. $this->process_order_by($order_by, null);
963 * Actuall deletes the emailman record
966 public function mark_deleted($id)
968 $this->db->query("DELETE FROM {$this->table_name} WHERE id=".intval($id));