/
EmailMan.php
executable file
·1586 lines (1338 loc) · 61.8 KB
/
EmailMan.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
*
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
* Copyright (C) 2011 - 2018 SalesAgility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
*/
if (!defined('sugarEntry') || !sugarEntry) {
die('Not A Valid Entry Point');
}
#[\AllowDynamicProperties]
class EmailMan extends SugarBean
{
/** @var string */
public $id;
/** @var string */
public $deleted;
/** @var string */
public $date_created;
/** @var string */
public $date_modified;
/** @var string */
public $module;
/** @var string */
public $module_id;
/** @var string */
public $marketing_id;
/** @var string */
public $campaign_id;
/** @var string */
public $user_id;
/** @var string */
public $list_id;
/** @var string */
public $invalid_email;
/** @var string */
public $from_name;
/** @var string */
public $from_email;
/** @var string */
public $in_queue;
/** @var string */
public $in_queue_date;
/** @var string */
public $template_id;
/** @var string */
public $send_date_time;
/** @var string */
public $table_name = "emailman";
/** @var string */
public $object_name = "EmailMan";
/** @var string */
public $module_dir = "EmailMan";
/** @var string */
public $send_attempts;
/** @var string */
public $related_id;
/** @var string */
public $related_type;
/** @var EmailTemplate $current_emailtemplate */
public $current_emailtemplate;
/** @var bool $related_confirm_opt_in*/
public $related_confirm_opt_in;
/** @var bool $test*/
public $test = false;
/** @var array $notes_array*/
public $notes_array = array();
/** @var array $verified_email_marketing_ids */
public $verified_email_marketing_ids = array();
/** @var bool $new_schema */
public $new_schema = true;
/**
* last opt in warning stored
*
* @var bool
*/
protected $optInWarn;
/**
* @var string
*/
protected $targetId;
/**
* @return string
*/
public function toString()
{
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";
}
// This is used to retrieve related fields from form posts.
public $additional_column_fields = array();
/**
* EmailMan constructor.
*/
public function __construct()
{
parent::__construct();
}
/**
* @param string $order_by
* @param string $where
* @param array $filter
* @param array $params
* @param int $show_deleted
* @param string $join_type
* @param bool $return_array
* @param null $parentbean
* @param bool $singleSelect
* @param bool $ifListForExport
* @return array|string
*/
public function create_new_list_query(
$order_by,
$where,
$filter = array(),
$params = array(),
$show_deleted = 0,
$join_type = '',
$return_array = false,
$parentbean = null,
$singleSelect = false,
$ifListForExport = false
) {
$query = array('select' => '', 'from' => '', 'where' => '', 'order_by' => '');
$query['select'] =
'SELECT '
. $this->table_name
. '.* , '
. 'campaigns.name as campaign_name, '
. 'email_marketing.name as message_name, '
. '(CASE related_type '
. 'WHEN \'Contacts\' THEN '
. $this->db->concat('contacts', array('first_name', 'last_name'), ' ')
. ' '
. 'WHEN \'Leads\' THEN '
. $this->db->concat('leads', array('first_name', 'last_name'), ' ')
. ' '
. 'WHEN \'Accounts\' THEN accounts.name '
. 'WHEN \'Users\' THEN '
. $this->db->concat('users', array('first_name', 'last_name'), ' ') . ' '
. "WHEN 'Prospects' THEN "
. $this->db->concat('prospects', array('first_name', 'last_name'), ' ')
. ' '
. 'END) recipient_name';
$query['from'] =
' '
. 'FROM ' . $this->table_name .' '
. 'LEFT JOIN users ON users.id = '
. $this->table_name . '.related_id '
. 'and '
. $this->table_name . '.related_type =\'Users\' '
. 'LEFT JOIN contacts ON contacts.id = '
. $this->table_name .'.related_id '
. 'and '
. $this->table_name .'.related_type =\'Contacts\' '
. 'LEFT JOIN leads ON leads.id = '
. $this->table_name .'.related_id '
. 'and '
. $this->table_name .'.related_type =\'Leads\' '
. 'LEFT JOIN accounts ON accounts.id = '
. $this->table_name . '.related_id and '.$this->table_name.'.related_type =\'Accounts\' '
. 'LEFT JOIN prospects ON prospects.id = '.$this->table_name.'.related_id and '.$this->table_name.'.related_type =\'Prospects\' '
. 'LEFT JOIN prospect_lists ON prospect_lists.id = '.$this->table_name.'.list_id '
. '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 '
. 'LEFT JOIN campaigns ON campaigns.id = '.$this->table_name.'.campaign_id '
. 'LEFT JOIN email_marketing ON email_marketing.id = '.$this->table_name.'.marketing_id ';
$where_auto = " $this->table_name.deleted=0";
if (!empty($where)) {
$query['where'] = "WHERE $where AND " . $where_auto;
} else {
$query['where'] = "WHERE " . $where_auto;
}
if (isset($params['group_by'])) {
$query['group_by'] .= " GROUP BY {$params['group_by']}";
}
$order_by = $this->process_order_by($order_by);
if (!empty($order_by)) {
$query['order_by'] = ' ORDER BY ' . $order_by;
}
if ($return_array) {
return $query;
}
return $query['select'] . $query['from'] . $query['where'] . $query['order_by'];
}
// if
/**
* @param $order_by
* @param $where
* @param array $filter
* @param array $params
* @param int $show_deleted
* @param string $join_type
* @param bool $return_array
* @param null $parentbean
* @param bool $singleSelect
* @return string
*/
public function create_queue_items_query(
$order_by,
$where,
$filter = array(),
$params = array(),
$show_deleted = 0,
$join_type = '',
$return_array = false,
$parentbean = null,
$singleSelect = false
) {
if ($return_array) {
return parent::create_new_list_query(
$order_by,
$where,
$filter,
$params,
$show_deleted,
$join_type,
$return_array,
$parentbean,
$singleSelect
);
}
$query =
"SELECT $this->table_name.* , campaigns.name as campaign_name, email_marketing.name as message_name, (CASE related_type WHEN 'Contacts' THEN "
. $this->db->concat('contacts', array('first_name', 'last_name'), ' ') . " WHEN 'Leads' THEN "
. $this->db->concat('leads', array('first_name', 'last_name'), ' ') . " WHEN 'Accounts' THEN accounts.name WHEN 'Users' THEN "
. $this->db->concat('users', array('first_name', 'last_name'), ' ') . " WHEN 'Prospects' THEN "
. $this->db->concat('prospects', array('first_name', 'last_name'), ' ') . ' '
. "END) recipient_name";
$query .=
' FROM '. $this->table_name
. ' '
. 'LEFT JOIN users ON users.id = '. $this->table_name .'.related_id and '. $this->table_name .'.related_type =\'Users\' '
. 'LEFT JOIN contacts ON contacts.id = '. $this->table_name .'.related_id and '. $this->table_name .'.related_type =\'Contacts\' '
. 'LEFT JOIN leads ON leads.id = '. $this->table_name .'.related_id and '. $this->table_name .'.related_type =\'Leads\' '
. 'LEFT JOIN accounts ON accounts.id = '. $this->table_name .'.related_id and '. $this->table_name .'.related_type =\'Accounts\' '
. 'LEFT JOIN prospects ON prospects.id = '. $this->table_name .'.related_id and '. $this->table_name .'.related_type =\'Prospects\' '
. 'LEFT JOIN prospect_lists ON prospect_lists.id = '. $this->table_name .'.list_id '
. '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 '
. 'LEFT JOIN campaigns ON campaigns.id = '. $this->table_name .'.campaign_id '
. 'LEFT JOIN email_marketing ON email_marketing.id = '. $this->table_name .'.marketing_id ';
//B.F. #37943
if (isset($params['group_by'])) {
$group_by = str_replace("emailman", "em", (string) $params['group_by']);
$query .= "INNER JOIN (select min(id) as id from emailman em GROUP BY $group_by) secondary on {$this->table_name}.id = secondary.id ";
}
$where_auto = " $this->table_name.deleted=0";
if ($where != "") {
$query .= "WHERE $where AND " . $where_auto;
} else {
$query .= "WHERE " . $where_auto;
}
$order_by = $this->process_order_by($order_by);
if (!empty($order_by)) {
$query .= ' ORDER BY ' . $order_by;
}
return $query;
}
/**
* @param $order_by
* @param $where
* @param int $show_deleted
* @return string
*/
public function create_list_query($order_by, $where, $show_deleted = 0)
{
$query =
"SELECT $this->table_name.* ,campaigns.name as campaign_name,email_marketing.name as message_name,(CASE related_type WHEN 'Contacts' THEN "
. $this->db->concat('contacts', array('first_name', 'last_name'), ' ')
. "WHEN 'Leads' THEN "
. $this->db->concat('leads', array('first_name', 'last_name'), ' ')
. "WHEN 'Accounts' THEN accounts.name WHEN 'Users' THEN "
. $this->db->concat('users', array('first_name', 'last_name'), ' ')
. "WHEN 'Prospects' THEN "
. $this->db->concat('prospects', array('first_name', 'last_name'), ' ')
. "END) recipient_name";
$query .= ' FROM '.$this->table_name.' '
. 'LEFT JOIN users ON users.id = '.$this->table_name.'.related_id and '.$this->table_name.'.related_type =\'Users\' '
. 'LEFT JOIN contacts ON contacts.id = '.$this->table_name.'.related_id and '.$this->table_name.'.related_type =\'Contacts\' '
. 'LEFT JOIN leads ON leads.id = '.$this->table_name.'.related_id and '.$this->table_name.'.related_type =\'Leads\' '
. 'LEFT JOIN accounts ON accounts.id = '.$this->table_name.'.related_id and '.$this->table_name.'.related_type =\'Accounts\' '
. 'LEFT JOIN prospects ON prospects.id = '.$this->table_name.'.related_id and '.$this->table_name.'.related_type =\'Prospects\' '
. 'LEFT JOIN prospect_lists ON prospect_lists.id = '.$this->table_name.'.list_id '
. '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 '
. 'LEFT JOIN campaigns ON campaigns.id = '.$this->table_name.'.campaign_id '
. 'LEFT JOIN email_marketing ON email_marketing.id = '.$this->table_name.'.marketing_id';
$where_auto = " $this->table_name.deleted=0";
if ($where != "") {
$query .= "where $where AND " . $where_auto;
} else {
$query .= "where " . $where_auto;
}
$order_by = $this->process_order_by($order_by);
if (!empty($order_by)) {
$query .= ' ORDER BY ' . $order_by;
}
return $query;
}
/**
* @return array
*/
public function get_list_view_data()
{
global $locale, $current_user;
$temp_array = parent::get_list_view_array();
$related_type = isset($temp_array['RELATED_TYPE']) ? $temp_array['RELATED_TYPE'] : null;
if (!isset($temp_array['RELATED_ID'])) {
LoggerManager::getLogger()->warn('EmailMan List view array has not related id for list view data');
$tempArrayRelatedId = null;
} else {
$tempArrayRelatedId = $temp_array['RELATED_ID'];
}
$related_id = $tempArrayRelatedId;
$is_person = SugarModule::get($related_type)->moduleImplements('Person');
if ($is_person) {
$query = "SELECT first_name, last_name FROM " . strtolower($related_type) . " WHERE id ='" . $related_id . "'";
} else {
$query = "SELECT name FROM " . strtolower($related_type) . " WHERE id ='" . $related_id . "'";
}
$result = $this->db->query($query);
$row = $this->db->fetchByAssoc($result);
if ($row) {
$temp_array['RECIPIENT_NAME'] = $is_person ? $locale->getLocaleFormattedName(
$row['first_name'],
$row['last_name'],
''
) : $row['name'];
}
//also store the recipient_email address
$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'";
$result = $this->db->query($query);
$row = $this->db->fetchByAssoc($result);
if ($row) {
$temp_array['RECIPIENT_EMAIL'] = $row['email_address'];
}
if (!isset($temp_array['RECIPIENT_EMAIL'])) {
LoggerManager::getLogger()->warn('EmailMan List view array has not recipient email for list view data');
$temArrayRecipientEmail = null;
} else {
$temArrayRecipientEmail = $temp_array['RECIPIENT_EMAIL'];
}
$this->email1 = $temArrayRecipientEmail;
$temp_array['EMAIL1_LINK'] = $current_user->getEmailLink('email1', $this, '', '', 'ListView');
return $temp_array;
}
/**
* @param $email_address
* @param bool $delete
* @param null $email_id
* @param null $email_type
* @param null $activity_type
* @param null $resend_type
*/
public function set_as_sent(
$email_address,
$delete = true,
$email_id = null,
$email_type = null,
$activity_type = null,
$resend_type = null
) {
global $timedate;
$this->send_attempts++;
$this->id = (int)$this->id;
if ($delete || $this->send_attempts > 5) {
//create new campaign log record.
$campaign_log = BeanFactory::newBean('CampaignLog');
$campaign_log->campaign_id = $this->campaign_id;
$campaign_log->target_tracker_key = $this->getTargetId();
$campaign_log->target_id = $this->related_id;
$campaign_log->target_type = $this->related_type;
$campaign_log->marketing_id = $this->marketing_id;
// if test suppress duplicate email address checking.
if (!$this->test) {
$campaign_log->more_information = $email_address;
}
$campaign_log->activity_type = $activity_type;
$campaign_log->activity_date = $timedate->now();
$campaign_log->list_id = $this->list_id;
$campaign_log->related_id = $email_id;
$campaign_log->related_type = $email_type;
$campaign_log->resend_type = $resend_type;
$campaign_log->save();
$query = "DELETE FROM emailman WHERE id = $this->id";
$this->db->query($query);
} else {
// try to send the email again a day later.
$query = 'UPDATE ' . $this->table_name . " SET in_queue='1', send_attempts='$this->send_attempts', in_queue_date=" . $this->db->now() . " WHERE id = $this->id";
$this->db->query($query);
}
}
/**
* Function finds the reference email for the campaign. Since a campaign can have multiple email templates
* the reference email has same id as the marketing id.
* this function will create an email if one does not exist. also the function will load these relationships leads, accounts, contacts
* users and targets
*
* @param varchar marketing_id message id
* @param string $subject email subject
* @param string $body_text Email Body Text
* @param string $body_html Email Body HTML
* @param string $campaign_name Campaign Name
* @param string from_address Email address of the sender, usually email address of the configured inbox.
* @param string sender_id If of the user sending the campaign.
* @param array macro_nv array of name value pair, one row for each replacable macro in email template text.
* @param string from_address_name The from address eg markeing <marketing@sugar.net>
* @return
*/
public function create_ref_email(
$marketing_id,
$subject,
$body_text,
$body_html,
$campagin_name,
$from_address,
$sender_id,
$notes,
$macro_nv,
$newmessage,
$from_address_name
) {
global $mod_strings, $timedate;
$upd_ref_email = false;
if ($newmessage || empty($this->ref_email->id)) {
$this->ref_email = BeanFactory::newBean('Emails');
$this->ref_email->retrieve($marketing_id, true, false);
//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
//switches back to test mode.
//this is to account for changes to email template.
$upd_ref_email = (!empty($this->ref_email->id) && $this->ref_email->parent_type == 'test' && $this->ref_email->parent_id == 'test');
//following condition is for switching back to test mode.
if (!$upd_ref_email) {
$upd_ref_email = ($this->test && !empty($this->ref_email->id) && empty($this->ref_email->parent_type) && empty($this->ref_email->parent_id));
}
if (empty($this->ref_email->id) || $upd_ref_email) {
//create email record.
$this->ref_email->id = $marketing_id;
$this->ref_email->date_sent_received = '';
if ($upd_ref_email == false) {
$this->ref_email->new_with_id = true;
}
$this->ref_email->to_addrs = '';
$this->ref_email->to_addrs_ids = '';
$this->ref_email->to_addrs_names = '';
$this->ref_email->to_addrs_emails = '';
$this->ref_email->type = 'campaign';
$this->ref_email->deleted = '0';
$this->ref_email->name = $campagin_name . ': ' . $subject;
$this->ref_email->description_html = $body_html;
$this->ref_email->description = $body_text;
$this->ref_email->from_addr = $from_address;
isValidEmailAddress($this->ref_email->from_addr);
$this->ref_email->from_addr_name = $from_address_name;
$this->ref_email->assigned_user_id = $sender_id;
if ($this->test) {
$this->ref_email->parent_type = 'test';
$this->ref_email->parent_id = 'test';
} else {
$this->ref_email->parent_type = '';
$this->ref_email->parent_id = '';
}
$this->ref_email->date_start = $timedate->nowDate();
$this->ref_email->time_start = $timedate->asUserTime($timedate->getNow(true));
$this->ref_email->status = 'sent';
$retId = $this->ref_email->save();
foreach ((array)$notes as $note) {
if (!is_object($note)) {
LoggerManager::getLogger()->warn('EmailMan create a reference email but given note is not an object. Type of note was: "' . gettype($note) . '"');
} else {
if ($note->object_name == 'Note') {
if (!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) {
$file_location = $note->file->temp_file_location;
$filename = $note->file->original_file_name;
$mime_type = $note->file->mime_type;
} else {
$file_location = "upload://{$note->id}";
$filename = $note->id . $note->filename;
$mime_type = $note->file_mime_type;
}
} elseif ($note->object_name == 'DocumentRevision') { // from Documents
$filename = $note->id . $note->filename;
$file_location = "upload://$filename";
$mime_type = $note->file_mime_type;
}
}
$noteAudit = BeanFactory::newBean('Notes');
$noteAudit->parent_id = $retId;
$noteAudit->parent_type = $this->ref_email->module_dir;
if (!isset($note->filename)) {
LoggerManager::getLogger()->warn('EmailMan create ref email error: Note filename is undefined.');
$noteFilename = null;
} else {
$noteFilename = $note->filename ;
}
$noteAudit->description = "[" . $noteFilename . "] " . $mod_strings['LBL_ATTACHMENT_AUDIT'];
if (!isset($filename)) {
LoggerManager::getLogger()->warn('EmailMan create ref email error: Filename is undefined.');
$filename = null;
}
$noteAudit->filename = $filename;
if (!isset($mime_type)) {
LoggerManager::getLogger()->warn('EmailMan create ref email error: Mime Type is undefined.');
$mime_type = null;
}
$noteAudit->file_mime_type = $mime_type;
$noteAudit_id = $noteAudit->save();
if (!isset($note->id)) {
LoggerManager::getLogger()->warn('EmailMan create ref email but Note ID is undefined.');
$noteId = null;
} else {
$noteId = $note->id;
}
UploadFile::duplicate_file($noteId, $noteAudit_id, $filename);
}
}
//load relationships.
$this->ref_email->load_relationship('users');
$this->ref_email->load_relationship('prospects');
$this->ref_email->load_relationship('contacts');
$this->ref_email->load_relationship('leads');
$this->ref_email->load_relationship('accounts');
}
$rel_name = '';
if (!empty($this->related_id) && !empty($this->related_type)) {
//save relationships.
switch ($this->related_type) {
case 'Users':
$rel_name = "users";
break;
case 'Prospects':
$rel_name = "prospects";
break;
case 'Contacts':
$rel_name = "contacts";
break;
case 'Leads':
$rel_name = "leads";
break;
case 'Accounts':
$rel_name = "accounts";
break;
}
//serialize data to be passed into Link2->add() function
$campaignData = serialize($macro_nv);
//required for one email per campaign per marketing message.
$this->ref_email->$rel_name->add(
$this->related_id,
array('campaign_data' => $this->db->quote($campaignData))
);
}
return $this->ref_email->id;
}
/**
* The function creates a copy of email send to each target.
* @param $module
* @param $mail
* @return string
*/
public function create_indiv_email($module, $mail)
{
global $locale, $timedate;
$email = BeanFactory::newBean('Emails');
$email->to_addrs = $module->name . '<' . $module->email1 . '>';
$email->to_addrs_ids = $module->id . ';';
$email->to_addrs_names = $module->name . ';';
$email->to_addrs_emails = $module->email1 . ';';
$email->type = 'archived';
$email->deleted = '0';
if (!isset($this->current_campaign)) {
LoggerManager::getLogger()->warn('EmailMan has not current campaign for create individual email.');
$currentCampaignNameMailSubject = null;
} else {
$currentCampaignNameMailSubject = $this->current_campaign->name . ': ' . $mail->Subject;
}
$email->name = $currentCampaignNameMailSubject;
if (!isset($mail->ContentType)) {
LoggerManager::getLogger()->warn('EmailMan given an mail for creating individual email but there is not content type.');
$mail->ContentType = null;
}
if ($mail->ContentType == "text/plain") {
$email->description = $mail->Body;
$email->description_html = null;
} else {
$email->description_html = $mail->Body;
$email->description = $mail->AltBody;
}
$email->from_addr = $mail->From;
isValidEmailAddress($email->from_addr);
$email->assigned_user_id = $this->user_id;
$email->parent_type = $this->related_type;
$email->parent_id = $this->related_id;
$email->date_start = $timedate->nowDbDate();
$email->time_start = $timedate->asDbTime($timedate->getNow());
$email->status = 'sent';
$retId = $email->save();
foreach ($this->notes_array as $note) {
// create "audit" email without duping off the file to save on disk space
$noteAudit = BeanFactory::newBean('Notes');
$noteAudit->parent_id = $retId;
$noteAudit->parent_type = $email->module_dir;
$noteAudit->description = "[" . $note->filename . "] " . $mod_strings['LBL_ATTACHMENT_AUDIT'];
$noteAudit->save();
}
if (!empty($this->related_id) && !empty($this->related_type)) {
//save relationships.
switch ($this->related_type) {
case 'Users':
$rel_name = "users";
break;
case 'Prospects':
$rel_name = "prospects";
break;
case 'Contacts':
$rel_name = "contacts";
break;
case 'Leads':
$rel_name = "leads";
break;
case 'Accounts':
$rel_name = "accounts";
break;
}
if (!empty($rel_name)) {
$email->load_relationship($rel_name);
$email->$rel_name->add($this->related_id);
}
}
return $email->id;
}
/**
* Call this function to verify the email_marketing message and email_template configured
* for the campaign. If issues are found a fatal error will be logged but processing will not stop.
* @param $marketing_id
* @return bool Returns true if all campaign parameters are set correctly
*/
public function verify_campaign($marketing_id)
{
if (!isset($this->verified_email_marketing_ids[$marketing_id])) {
$email_marketing = BeanFactory::newBean('EmailMarketing');
$ret = $email_marketing->retrieve($marketing_id);
if (empty($ret)) {
$GLOBALS['log']->fatal('Error retrieving marketing message for the email campaign. marketing_id = ' . $marketing_id);
return false;
}
//verify the email template.
if (empty($email_marketing->template_id)) {
$GLOBALS['log']->fatal('Error retrieving template for the email campaign. marketing_id = ' . $marketing_id);
return false;
}
$emailtemplate = BeanFactory::newBean('EmailTemplates');
$ret = $emailtemplate->retrieve($email_marketing->template_id);
if (empty($ret)) {
$GLOBALS['log']->fatal('Error retrieving template for the email campaign. template_id = ' . $email_marketing->template_id);
return false;
}
if (empty($emailtemplate->subject) && empty($emailtemplate->body) && empty($emailtemplate->body_html)) {
$GLOBALS['log']->fatal('Email template is empty. email_template_id=' . $email_marketing->template_id);
return false;
}
}
$this->verified_email_marketing_ids[$marketing_id] = 1;
return true;
}
/**
* @global array $beanList ;
* @global array $beanFiles ;
* @global Configurator|array $sugar_config ;
* @global array $mod_strings ;
* @global Localization $locale ;
* @param SugarPHPMailer $mail
* @param int $save_emails
* @param bool $testmode
* @return bool
*/
public function sendEmail(SugarPHPMailer $mail, $save_emails = 1, $testmode = false)
{
global $beanList;
global $beanFiles;
global $sugar_config;
global $mod_strings;
global $locale;
global $layout_def;
$tracker_url = '';
$tracker_text = '';
$parent = '';
$this->test = $testmode;
$OBCharset = $locale->getPrecedentPreference('default_email_charset');
$mod_strings = return_module_language($sugar_config['default_language'], 'EmailMan');
//get tracking entities locations.
if (!isset($this->tracking_url)) {
$admin = BeanFactory::newBean('Administration');
$admin->retrieveSettings('massemailer'); //retrieve all admin settings.
if (isset($admin->settings['massemailer_tracking_entities_location_type']) && $admin->settings['massemailer_tracking_entities_location_type'] == '2' && isset($admin->settings['massemailer_tracking_entities_location'])) {
$this->tracking_url = $admin->settings['massemailer_tracking_entities_location'];
} else {
$this->tracking_url = $sugar_config['site_url'];
}
}
//make sure tracking url ends with '/' character
$strLen = strlen((string) $this->tracking_url);
if ($this->tracking_url[$strLen - 1] != '/') {
$this->tracking_url .= '/';
}
if (!isset($beanList[$this->related_type])) {
return false;
}
$class = $beanList[$this->related_type];
if (!class_exists($class)) {
require_once($beanFiles[$class]);
}
$this->setTargetId(create_guid());
$module = new $class();
$module->retrieve($this->related_id);
$module->emailAddress->handleLegacyRetrieve($module);
//check to see if bean has a primary email address
if (!$this->is_primary_email_address($module)) {
//no primary email address designated, do not send out email, create campaign log
//of type send error to denote that this user was not emailed
$this->set_as_sent($module->email1, true, null, null, 'send error');
//create fatal logging for easy review of cause.
$GLOBALS['log']->fatal('Email Address provided is not Primary Address for email with id ' . $module->email1 . "' Emailman id=$this->id");
return true;
}
if (!$this->valid_email_address($module->email1)) {
$this->set_as_sent($module->email1, true, null, null, 'invalid email');
$GLOBALS['log']->fatal('Encountered invalid email address: ' . $module->email1 . " Emailman id=$this->id");
return true;
}
if ($this->shouldBlockEmail($module)) {
$GLOBALS['log']->warn('Email Address was sent due to not being confirm opt in' . $module->email1);
// block sending campaign email
$this->set_as_sent($module->email1, true, null, null, 'blocked');
return true;
}
$email_id = null;
if (
(
!isset($module->email_opt_out)
|| (
$module->email_opt_out !== 'on'
&& $module->email_opt_out !== 1
&& $module->email_opt_out !== '1'
)
)
&& (
!isset($module->invalid_email)
|| ($module->invalid_email !== 'on' && $module->invalid_email !== 1 && $module->invalid_email !== '1')
)) {
// If email address is not opted out or the email is valid
$lower_email_address = strtolower($module->email1);
//test against restricted domains
$at_pos = strrpos($lower_email_address, '@');
if ($at_pos !== false) {
foreach ($this->restricted_domains as $domain => $value) {
$pos = strrpos($lower_email_address, (string) $domain);
if ($pos !== false && $pos > $at_pos) {
//found
$this->set_as_sent($lower_email_address, true, null, null, 'blocked');
return true;
}
}
}
if (isset($this->restricted_addresses[$lower_email_address])) {
$this->set_as_sent($lower_email_address, true, null, null, 'blocked');
return true;
}
//test for duplicate email address by marketing id.
$dup_query = "select id from campaign_log where more_information='" . $this->db->quote($module->email1) . "' and marketing_id='" . $this->marketing_id . "'";
$dup = $this->db->query($dup_query);
$dup_row = $this->db->fetchByAssoc($dup);
if (!empty($dup_row)) {
//we have seen this email address before
$this->set_as_sent($module->email1, true, null, null, 'blocked');
return true;
}
//fetch email marketing.
if (empty($this->current_emailmarketing) || ! isset($this->current_emailmarketing)) {
$this->current_emailmarketing = BeanFactory::newBean('EmailMarketing');
}
if (empty($this->current_emailmarketing->id) || $this->current_emailmarketing->id !== $this->marketing_id) {
$this->current_emailmarketing->retrieve($this->marketing_id);
$this->newmessage = true;
}
//fetch email template associate with the marketing message.
if (empty($this->current_emailtemplate) || $this->current_emailtemplate->id !== $this->current_emailmarketing->template_id) {
$this->current_emailtemplate = BeanFactory::newBean('EmailTemplates');
if (isset($this->resend_type) && $this->resend_type == 'Reminder') {
$this->current_emailtemplate->retrieve($sugar_config['survey_reminder_template']);
} else {
$this->current_emailtemplate->retrieve($this->current_emailmarketing->template_id);
}
//escape email template contents.
$this->current_emailtemplate->subject = from_html($this->current_emailtemplate->subject);
$this->current_emailtemplate->body_html = from_html($this->current_emailtemplate->body_html);
$this->current_emailtemplate->body = from_html($this->current_emailtemplate->body);
$q = "SELECT * FROM notes WHERE parent_id = '" . $this->current_emailtemplate->id . "' AND deleted = 0";
$r = $this->db->query($q);
// cn: bug 4684 - initialize the notes array, else old data is still around for the next round
$this->notes_array = array();
if (!class_exists('Note')) {
require_once('modules/Notes/Note.php');
}
while ($a = $this->db->fetchByAssoc($r)) {
$noteTemplate = BeanFactory::newBean('Notes');
$noteTemplate->retrieve($a['id']);
$this->notes_array[] = $noteTemplate;
}
}