-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathMailing.php
3270 lines (2909 loc) · 109 KB
/
Mailing.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
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.6 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
* $Id$
*
*/
require_once 'Mail/mime.php';
/**
* Class CRM_Mailing_BAO_Mailing
*/
class CRM_Mailing_BAO_Mailing extends CRM_Mailing_DAO_Mailing {
/**
* An array that holds the complete templates
* including any headers or footers that need to be prepended
* or appended to the body
*/
private $preparedTemplates = NULL;
/**
* An array that holds the complete templates
* including any headers or footers that need to be prepended
* or appended to the body
*/
private $templates = NULL;
/**
* An array that holds the tokens that are specifically found in our text and html bodies
*/
private $tokens = NULL;
/**
* An array that holds the tokens that are specifically found in our text and html bodies
*/
private $flattenedTokens = NULL;
/**
* The header associated with this mailing
*/
private $header = NULL;
/**
* The footer associated with this mailing
*/
private $footer = NULL;
/**
* The HTML content of the message
*/
private $html = NULL;
/**
* The text content of the message
*/
private $text = NULL;
/**
* Cached BAO for the domain
*/
private $_domain = NULL;
/**
* Class constructor
*/
public function __construct() {
parent::__construct();
}
/**
* @param int $job_id
* @param int $mailing_id
* @param null $mode
*
* @return int
*/
public static function &getRecipientsCount($job_id, $mailing_id = NULL, $mode = NULL) {
// need this for backward compatibility, so we can get count for old mailings
// please do not use this function if possible
$eq = self::getRecipients($job_id, $mailing_id);
return $eq->N;
}
/**
* note that $job_id is used only as a variable in the temp table construction
* and does not play a role in the queries generated
* @param int $job_id
* (misnomer) a nonce value used to name temporary tables.
* @param int $mailing_id
* @param null $offset
* @param null $limit
* @param bool $storeRecipients
* @param bool $dedupeEmail
* @param null $mode
*
* @return CRM_Mailing_Event_BAO_Queue|string
*/
public static function &getRecipients(
$job_id,
$mailing_id = NULL,
$offset = NULL,
$limit = NULL,
$storeRecipients = FALSE,
$dedupeEmail = FALSE,
$mode = NULL) {
$mailingGroup = new CRM_Mailing_DAO_MailingGroup();
$mailing = CRM_Mailing_BAO_Mailing::getTableName();
$job = CRM_Mailing_BAO_MailingJob::getTableName();
$mg = CRM_Mailing_DAO_MailingGroup::getTableName();
$eq = CRM_Mailing_Event_DAO_Queue::getTableName();
$ed = CRM_Mailing_Event_DAO_Delivered::getTableName();
$eb = CRM_Mailing_Event_DAO_Bounce::getTableName();
$email = CRM_Core_DAO_Email::getTableName();
if ($mode == 'sms') {
$phone = CRM_Core_DAO_Phone::getTableName();
}
$contact = CRM_Contact_DAO_Contact::getTableName();
$group = CRM_Contact_DAO_Group::getTableName();
$g2contact = CRM_Contact_DAO_GroupContact::getTableName();
$m = new CRM_Mailing_DAO_Mailing();
$m->id = $mailing_id;
$m->find(TRUE);
$email_selection_method = $m->email_selection_method;
$location_type_id = $m->location_type_id;
// Note: When determining the ORDER that results are returned, it's
// the record that comes last that counts. That's because we are
// INSERT'ing INTO a table with a primary id so that last record
// over writes any previous record.
switch ($email_selection_method) {
case 'location-exclude':
$location_filter = "($email.location_type_id != $location_type_id)";
// If there is more than one email that doesn't match the location,
// prefer the one marked is_bulkmail, followed by is_primary.
$order_by = "ORDER BY $email.is_bulkmail, $email.is_primary";
break;
case 'location-only':
$location_filter = "($email.location_type_id = $location_type_id)";
// If there is more than one email of the desired location, prefer
// the one marked is_bulkmail, followed by is_primary.
$order_by = "ORDER BY $email.is_bulkmail, $email.is_primary";
break;
case 'location-prefer':
$location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1 OR $email.location_type_id = $location_type_id)";
// ORDER BY is more complicated because we have to set an arbitrary
// order that prefers the location that we want. We do that using
// the FIELD function. For more info, see:
// https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field
// We assign the location type we want the value "1" by putting it
// in the first position after we name the field. All other location
// types are left out, so they will be assigned the value 0. That
// means, they will all be equally tied for first place, with our
// location being last.
$order_by = "ORDER BY FIELD($email.location_type_id, $location_type_id), $email.is_bulkmail, $email.is_primary";
break;
case 'automatic':
// fall through to default
default:
$location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1)";
$order_by = "ORDER BY $email.is_bulkmail";
}
/* Create a temp table for contact exclusion */
$mailingGroup->query(
"CREATE TEMPORARY TABLE X_$job_id
(contact_id int primary key)
ENGINE=HEAP"
);
/* Add all the members of groups excluded from this mailing to the temp
* table */
$excludeSubGroup = "INSERT INTO X_$job_id (contact_id)
SELECT DISTINCT $g2contact.contact_id
FROM $g2contact
INNER JOIN $mg
ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
WHERE
$mg.mailing_id = {$mailing_id}
AND $g2contact.status = 'Added'
AND $mg.group_type = 'Exclude'";
$mailingGroup->query($excludeSubGroup);
/* Add all unsubscribe members of base group from this mailing to the temp
* table */
$unSubscribeBaseGroup = "INSERT INTO X_$job_id (contact_id)
SELECT DISTINCT $g2contact.contact_id
FROM $g2contact
INNER JOIN $mg
ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
WHERE
$mg.mailing_id = {$mailing_id}
AND $g2contact.status = 'Removed'
AND $mg.group_type = 'Base'";
$mailingGroup->query($unSubscribeBaseGroup);
/* Add all the (intended) recipients of an excluded prior mailing to
* the temp table */
$excludeSubMailing = "INSERT IGNORE INTO X_$job_id (contact_id)
SELECT DISTINCT $eq.contact_id
FROM $eq
INNER JOIN $job
ON $eq.job_id = $job.id
INNER JOIN $mg
ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
WHERE
$mg.mailing_id = {$mailing_id}
AND $mg.group_type = 'Exclude'";
$mailingGroup->query($excludeSubMailing);
// get all the saved searches AND hierarchical groups
// and load them in the cache
$sql = "
SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
FROM $group
INNER JOIN $mg ON $mg.entity_id = $group.id
WHERE $mg.entity_table = '$group'
AND $mg.group_type = 'Exclude'
AND $mg.mailing_id = {$mailing_id}
AND ( saved_search_id != 0
OR saved_search_id IS NOT NULL
OR children IS NOT NULL )
";
$groupDAO = CRM_Core_DAO::executeQuery($sql);
while ($groupDAO->fetch()) {
if ($groupDAO->cache_date == NULL) {
CRM_Contact_BAO_GroupContactCache::load($groupDAO);
}
$smartGroupExclude = "
INSERT IGNORE INTO X_$job_id (contact_id)
SELECT c.contact_id
FROM civicrm_group_contact_cache c
WHERE c.group_id = {$groupDAO->id}
";
$mailingGroup->query($smartGroupExclude);
}
$tempColumn = 'email_id';
if ($mode == 'sms') {
$tempColumn = 'phone_id';
}
/* Get all the group contacts we want to include */
$mailingGroup->query(
"CREATE TEMPORARY TABLE I_$job_id
($tempColumn int, contact_id int primary key)
ENGINE=HEAP"
);
/* Get the group contacts, but only those which are not in the
* exclusion temp table */
$query = "REPLACE INTO I_$job_id (email_id, contact_id)
SELECT DISTINCT $email.id as email_id,
$contact.id as contact_id
FROM $email
INNER JOIN $contact
ON $email.contact_id = $contact.id
INNER JOIN $g2contact
ON $contact.id = $g2contact.contact_id
INNER JOIN $mg
ON $g2contact.group_id = $mg.entity_id
AND $mg.entity_table = '$group'
LEFT JOIN X_$job_id
ON $contact.id = X_$job_id.contact_id
WHERE
($mg.group_type = 'Include')
AND $mg.search_id IS NULL
AND $g2contact.status = 'Added'
AND $contact.do_not_email = 0
AND $contact.is_opt_out = 0
AND $contact.is_deceased = 0
AND $location_filter
AND $email.email IS NOT NULL
AND $email.email != ''
AND $email.on_hold = 0
AND $mg.mailing_id = {$mailing_id}
AND X_$job_id.contact_id IS null
$order_by";
if ($mode == 'sms') {
$phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
$query = "REPLACE INTO I_$job_id (phone_id, contact_id)
SELECT DISTINCT $phone.id as phone_id,
$contact.id as contact_id
FROM $phone
INNER JOIN $contact
ON $phone.contact_id = $contact.id
INNER JOIN $g2contact
ON $contact.id = $g2contact.contact_id
INNER JOIN $mg
ON $g2contact.group_id = $mg.entity_id
AND $mg.entity_table = '$group'
LEFT JOIN X_$job_id
ON $contact.id = X_$job_id.contact_id
WHERE
($mg.group_type = 'Include')
AND $mg.search_id IS NULL
AND $g2contact.status = 'Added'
AND $contact.do_not_sms = 0
AND $contact.is_opt_out = 0
AND $contact.is_deceased = 0
AND $phone.phone_type_id = {$phoneTypes['Mobile']}
AND $phone.phone IS NOT NULL
AND $phone.phone != ''
AND $mg.mailing_id = {$mailing_id}
AND X_$job_id.contact_id IS null";
}
$mailingGroup->query($query);
/* Query prior mailings */
$query = "REPLACE INTO I_$job_id (email_id, contact_id)
SELECT DISTINCT $email.id as email_id,
$contact.id as contact_id
FROM $email
INNER JOIN $contact
ON $email.contact_id = $contact.id
INNER JOIN $eq
ON $eq.contact_id = $contact.id
INNER JOIN $job
ON $eq.job_id = $job.id
INNER JOIN $mg
ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
LEFT JOIN X_$job_id
ON $contact.id = X_$job_id.contact_id
WHERE
($mg.group_type = 'Include')
AND $contact.do_not_email = 0
AND $contact.is_opt_out = 0
AND $contact.is_deceased = 0
AND $location_filter
AND $email.on_hold = 0
AND $mg.mailing_id = {$mailing_id}
AND X_$job_id.contact_id IS null
$order_by";
if ($mode == 'sms') {
$query = "REPLACE INTO I_$job_id (phone_id, contact_id)
SELECT DISTINCT $phone.id as phone_id,
$contact.id as contact_id
FROM $phone
INNER JOIN $contact
ON $phone.contact_id = $contact.id
INNER JOIN $eq
ON $eq.contact_id = $contact.id
INNER JOIN $job
ON $eq.job_id = $job.id
INNER JOIN $mg
ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
LEFT JOIN X_$job_id
ON $contact.id = X_$job_id.contact_id
WHERE
($mg.group_type = 'Include')
AND $contact.do_not_sms = 0
AND $contact.is_opt_out = 0
AND $contact.is_deceased = 0
AND $phone.phone_type_id = {$phoneTypes['Mobile']}
AND $mg.mailing_id = {$mailing_id}
AND X_$job_id.contact_id IS null";
}
$mailingGroup->query($query);
$sql = "
SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
FROM $group
INNER JOIN $mg ON $mg.entity_id = $group.id
WHERE $mg.entity_table = '$group'
AND $mg.group_type = 'Include'
AND $mg.search_id IS NULL
AND $mg.mailing_id = {$mailing_id}
AND ( saved_search_id != 0
OR saved_search_id IS NOT NULL
OR children IS NOT NULL )
";
$groupDAO = CRM_Core_DAO::executeQuery($sql);
while ($groupDAO->fetch()) {
if ($groupDAO->cache_date == NULL) {
CRM_Contact_BAO_GroupContactCache::load($groupDAO);
}
$smartGroupInclude = "
REPLACE INTO I_$job_id (email_id, contact_id)
SELECT civicrm_email.id as email_id, c.id as contact_id
FROM civicrm_contact c
INNER JOIN civicrm_email ON civicrm_email.contact_id = c.id
INNER JOIN civicrm_group_contact_cache gc ON gc.contact_id = c.id
LEFT JOIN X_$job_id ON X_$job_id.contact_id = c.id
WHERE gc.group_id = {$groupDAO->id}
AND c.do_not_email = 0
AND c.is_opt_out = 0
AND c.is_deceased = 0
AND $location_filter
AND civicrm_email.on_hold = 0
AND X_$job_id.contact_id IS null
$order_by
";
if ($mode == 'sms') {
$smartGroupInclude = "
REPLACE INTO I_$job_id (phone_id, contact_id)
SELECT p.id as phone_id, c.id as contact_id
FROM civicrm_contact c
INNER JOIN civicrm_phone p ON p.contact_id = c.id
INNER JOIN civicrm_group_contact_cache gc ON gc.contact_id = c.id
LEFT JOIN X_$job_id ON X_$job_id.contact_id = c.id
WHERE gc.group_id = {$groupDAO->id}
AND c.do_not_sms = 0
AND c.is_opt_out = 0
AND c.is_deceased = 0
AND p.phone_type_id = {$phoneTypes['Mobile']}
AND X_$job_id.contact_id IS null";
}
$mailingGroup->query($smartGroupInclude);
}
/**
* Construct the filtered search queries
*/
$query = "
SELECT search_id, search_args, entity_id
FROM $mg
WHERE $mg.search_id IS NOT NULL
AND $mg.mailing_id = {$mailing_id}
";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$customSQL = CRM_Contact_BAO_SearchCustom::civiMailSQL($dao->search_id,
$dao->search_args,
$dao->entity_id
);
$query = "REPLACE INTO I_$job_id ({$tempColumn}, contact_id)
$customSQL";
$mailingGroup->query($query);
}
/* Get the emails with only location override */
$query = "REPLACE INTO I_$job_id (email_id, contact_id)
SELECT DISTINCT $email.id as local_email_id,
$contact.id as contact_id
FROM $email
INNER JOIN $contact
ON $email.contact_id = $contact.id
INNER JOIN $g2contact
ON $contact.id = $g2contact.contact_id
INNER JOIN $mg
ON $g2contact.group_id = $mg.entity_id
LEFT JOIN X_$job_id
ON $contact.id = X_$job_id.contact_id
WHERE
$mg.entity_table = '$group'
AND $mg.group_type = 'Include'
AND $g2contact.status = 'Added'
AND $contact.do_not_email = 0
AND $contact.is_opt_out = 0
AND $contact.is_deceased = 0
AND $location_filter
AND $email.on_hold = 0
AND $mg.mailing_id = {$mailing_id}
AND X_$job_id.contact_id IS null
$order_by";
if ($mode == "sms") {
$query = "REPLACE INTO I_$job_id (phone_id, contact_id)
SELECT DISTINCT $phone.id as phone_id,
$contact.id as contact_id
FROM $phone
INNER JOIN $contact
ON $phone.contact_id = $contact.id
INNER JOIN $g2contact
ON $contact.id = $g2contact.contact_id
INNER JOIN $mg
ON $g2contact.group_id = $mg.entity_id
LEFT JOIN X_$job_id
ON $contact.id = X_$job_id.contact_id
WHERE
$mg.entity_table = '$group'
AND $mg.group_type = 'Include'
AND $g2contact.status = 'Added'
AND $contact.do_not_sms = 0
AND $contact.is_opt_out = 0
AND $contact.is_deceased = 0
AND $phone.phone_type_id = {$phoneTypes['Mobile']}
AND $mg.mailing_id = {$mailing_id}
AND X_$job_id.contact_id IS null";
}
$mailingGroup->query($query);
$results = array();
$eq = new CRM_Mailing_Event_BAO_Queue();
list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause();
$aclWhere = $aclWhere ? "WHERE {$aclWhere}" : '';
$limitString = NULL;
if ($limit && $offset !== NULL) {
$offset = CRM_Utils_Type::escape($offset, 'Int');
$limit = CRM_Utils_Type::escape($limit, 'Int');
$limitString = "LIMIT $offset, $limit";
}
if ($storeRecipients && $mailing_id) {
$sql = "
DELETE
FROM civicrm_mailing_recipients
WHERE mailing_id = %1
";
$params = array(1 => array($mailing_id, 'Integer'));
CRM_Core_DAO::executeQuery($sql, $params);
// CRM-3975
$groupBy = $groupJoin = '';
if ($dedupeEmail) {
$groupJoin = " INNER JOIN civicrm_email e ON e.id = i.email_id";
$groupBy = " GROUP BY e.email ";
}
$sql = "
INSERT INTO civicrm_mailing_recipients ( mailing_id, contact_id, {$tempColumn} )
SELECT %1, i.contact_id, i.{$tempColumn}
FROM civicrm_contact contact_a
INNER JOIN I_$job_id i ON contact_a.id = i.contact_id
$groupJoin
{$aclFrom}
{$aclWhere}
$groupBy
ORDER BY i.contact_id, i.{$tempColumn}
";
CRM_Core_DAO::executeQuery($sql, $params);
// if we need to add all emails marked bulk, do it as a post filter
// on the mailing recipients table
if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
self::addMultipleEmails($mailing_id);
}
}
/* Delete the temp table */
$mailingGroup->reset();
$mailingGroup->query("DROP TEMPORARY TABLE X_$job_id");
$mailingGroup->query("DROP TEMPORARY TABLE I_$job_id");
return $eq;
}
/**
* @param string $type
*
* @return array
*/
private function _getMailingGroupIds($type = 'Include') {
$mailingGroup = new CRM_Mailing_DAO_MailingGroup();
$group = CRM_Contact_DAO_Group::getTableName();
if (!isset($this->id)) {
// we're just testing tokens, so return any group
$query = "SELECT id AS entity_id
FROM $group
ORDER BY id
LIMIT 1";
}
else {
$query = "SELECT entity_id
FROM $mg
WHERE mailing_id = {$this->id}
AND group_type = '$type'
AND entity_table = '$group'";
}
$mailingGroup->query($query);
$groupIds = array();
while ($mailingGroup->fetch()) {
$groupIds[] = $mailingGroup->entity_id;
}
return $groupIds;
}
/**
* Returns the regex patterns that are used for preparing the text and html templates.
*/
private function &getPatterns($onlyHrefs = FALSE) {
$patterns = array();
$protos = '(https?|ftp)';
$letters = '\w';
$gunk = '\{\}/#~:.?+=&;%@!\,\-\|\(\)\*';
$punc = '.:?\-';
$any = "{$letters}{$gunk}{$punc}";
if ($onlyHrefs) {
$pattern = "\\bhref[ ]*=[ ]*([\"'])?(($protos:[$any]+?(?=[$punc]*[^$any]|$)))([\"'])?";
}
else {
$pattern = "\\b($protos:[$any]+?(?=[$punc]*[^$any]|$))";
}
$patterns[] = $pattern;
$patterns[] = '\\\\\{\w+\.\w+\\\\\}|\{\{\w+\.\w+\}\}';
$patterns[] = '\{\w+\.\w+\}';
$patterns = '{' . implode('|', $patterns) . '}im';
return $patterns;
}
/**
* Returns an array that denotes the type of token that we are dealing with
* we use the type later on when we are doing a token replacement lookup
*
* @param string $token
* The token for which we will be doing adata lookup.
*
* @return array
* An array that holds the token itself and the type.
* the type will tell us which function to use for the data lookup
* if we need to do a lookup at all
*/
public function &getDataFunc($token) {
static $_categories = NULL;
static $_categoryString = NULL;
if (!$_categories) {
$_categories = array(
'domain' => NULL,
'action' => NULL,
'mailing' => NULL,
'contact' => NULL,
);
CRM_Utils_Hook::tokens($_categories);
$_categoryString = implode('|', array_keys($_categories));
}
$funcStruct = array('type' => NULL, 'token' => $token);
$matches = array();
if ((preg_match('/^href/i', $token) || preg_match('/^http/i', $token))) {
// it is a url so we need to check to see if there are any tokens embedded
// if so then call this function again to get the token dataFunc
// and assign the type 'embedded' so that the data retrieving function
// will know what how to handle this token.
if (preg_match_all('/(\{\w+\.\w+\})/', $token, $matches)) {
$funcStruct['type'] = 'embedded_url';
$funcStruct['embed_parts'] = $funcStruct['token'] = array();
foreach ($matches[1] as $match) {
$preg_token = '/' . preg_quote($match, '/') . '/';
$list = preg_split($preg_token, $token, 2);
$funcStruct['embed_parts'][] = $list[0];
$token = $list[1];
$funcStruct['token'][] = $this->getDataFunc($match);
}
// fixed truncated url, CRM-7113
if ($token) {
$funcStruct['embed_parts'][] = $token;
}
}
else {
$funcStruct['type'] = 'url';
}
}
elseif (preg_match('/^\{(' . $_categoryString . ')\.(\w+)\}$/', $token, $matches)) {
$funcStruct['type'] = $matches[1];
$funcStruct['token'] = $matches[2];
}
elseif (preg_match('/\\\\\{(\w+\.\w+)\\\\\}|\{\{(\w+\.\w+)\}\}/', $token, $matches)) {
// we are an escaped token
// so remove the escape chars
$unescaped_token = preg_replace('/\{\{|\}\}|\\\\\{|\\\\\}/', '', $matches[0]);
$funcStruct['token'] = '{' . $unescaped_token . '}';
}
return $funcStruct;
}
/**
*
* Prepares the text and html templates
* for generating the emails and returns a copy of the
* prepared templates
*/
private function getPreparedTemplates() {
if (!$this->preparedTemplates) {
$patterns['html'] = $this->getPatterns(TRUE);
$patterns['subject'] = $patterns['text'] = $this->getPatterns();
$templates = $this->getTemplates();
$this->preparedTemplates = array();
foreach (array(
'html',
'text',
'subject',
) as $key) {
if (!isset($templates[$key])) {
continue;
}
$matches = array();
$tokens = array();
$split_template = array();
$email = $templates[$key];
preg_match_all($patterns[$key], $email, $matches, PREG_PATTERN_ORDER);
foreach ($matches[0] as $idx => $token) {
$preg_token = '/' . preg_quote($token, '/') . '/im';
list($split_template[], $email) = preg_split($preg_token, $email, 2);
array_push($tokens, $this->getDataFunc($token));
}
if ($email) {
$split_template[] = $email;
}
$this->preparedTemplates[$key]['template'] = $split_template;
$this->preparedTemplates[$key]['tokens'] = $tokens;
}
}
return ($this->preparedTemplates);
}
/**
* Retrieve a ref to an array that holds the email and text templates for this email
* assembles the complete template including the header and footer
* that the user has uploaded or declared (if they have dome that)
*
* @return array
* reference to an assoc array
*/
private function &getTemplates() {
if (!$this->templates) {
$this->getHeaderFooter();
$this->templates = array();
if ($this->body_text) {
$template = array();
if ($this->header) {
$template[] = $this->header->body_text;
}
$template[] = $this->body_text;
if ($this->footer) {
$template[] = $this->footer->body_text;
}
$this->templates['text'] = implode("\n", $template);
}
if ($this->body_html) {
$template = array();
if ($this->header) {
$template[] = $this->header->body_html;
}
$template[] = $this->body_html;
if ($this->footer) {
$template[] = $this->footer->body_html;
}
$this->templates['html'] = implode("\n", $template);
// this is where we create a text template from the html template if the text template did not exist
// this way we ensure that every recipient will receive an email even if the pref is set to text and the
// user uploads an html email only
if (!$this->body_text) {
$this->templates['text'] = CRM_Utils_String::htmlToText($this->templates['html']);
}
}
if ($this->subject) {
$template = array();
$template[] = $this->subject;
$this->templates['subject'] = implode("\n", $template);
}
}
return $this->templates;
}
/**
*
* Retrieve a ref to an array that holds all of the tokens in the email body
* where the keys are the type of token and the values are ordinal arrays
* that hold the token names (even repeated tokens) in the order in which
* they appear in the body of the email.
*
* note: the real work is done in the _getTokens() function
*
* this function needs to have some sort of a body assigned
* either text or html for this to have any meaningful impact
*
* @return array
* reference to an assoc array
*/
public function &getTokens() {
if (!$this->tokens) {
$this->tokens = array('html' => array(), 'text' => array(), 'subject' => array());
if ($this->body_html) {
$this->_getTokens('html');
if (!$this->body_text) {
// Since the text template was created from html, use the html tokens.
// @see CRM_Mailing_BAO_Mailing::getTemplates()
$this->tokens['text'] = $this->tokens['html'];
}
}
if ($this->body_text) {
$this->_getTokens('text');
}
if ($this->subject) {
$this->_getTokens('subject');
}
}
return $this->tokens;
}
/**
* Returns the token set for all 3 parts as one set. This allows it to be sent to the
* hook in one call and standardizes it across other token workflows
*
* @return array
* reference to an assoc array
*/
public function &getFlattenedTokens() {
if (!$this->flattenedTokens) {
$tokens = $this->getTokens();
$this->flattenedTokens = CRM_Utils_Token::flattenTokens($tokens);
}
return $this->flattenedTokens;
}
/**
*
* _getTokens parses out all of the tokens that have been
* included in the html and text bodies of the email
* we get the tokens and then separate them into an
* internal structure named tokens that has the same
* form as the static tokens property(?) of the CRM_Utils_Token class.
* The difference is that there might be repeated token names as we want the
* structures to represent the order in which tokens were found from left to right, top to bottom.
*
*
* @param string $prop name of the property that holds the text that we want to scan for tokens (html, text).
* Name of the property that holds the text that we want to scan for tokens (html, text).
*
* @return void
*/
private function _getTokens($prop) {
$templates = $this->getTemplates();
$newTokens = CRM_Utils_Token::getTokens($templates[$prop]);
foreach ($newTokens as $type => $names) {
if (!isset($this->tokens[$prop][$type])) {
$this->tokens[$prop][$type] = array();
}
foreach ($names as $key => $name) {
$this->tokens[$prop][$type][] = $name;
}
}
}
/**
* Generate an event queue for a test job.
*
* @param array $testParams
* Contains form values.
*
* @return void
*/
public function getTestRecipients($testParams) {
if (array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant::group())) {
$contacts = civicrm_api('contact', 'get', array(
'version' => 3,
'group' => $testParams['test_group'],
'return' => 'id',
'options' => array(
'limit' => 100000000000,
),
)
);
foreach (array_keys($contacts['values']) as $groupContact) {
$query = "
SELECT civicrm_email.id AS email_id,
civicrm_email.is_primary as is_primary,
civicrm_email.is_bulkmail as is_bulkmail
FROM civicrm_email
INNER JOIN civicrm_contact ON civicrm_email.contact_id = civicrm_contact.id
WHERE (civicrm_email.is_bulkmail = 1 OR civicrm_email.is_primary = 1)
AND civicrm_contact.id = {$groupContact}
AND civicrm_contact.do_not_email = 0
AND civicrm_contact.is_deceased = 0
AND civicrm_email.on_hold = 0
AND civicrm_contact.is_opt_out = 0
GROUP BY civicrm_email.id
ORDER BY civicrm_email.is_bulkmail DESC
";
$dao = CRM_Core_DAO::executeQuery($query);
if ($dao->fetch()) {
$params = array(
'job_id' => $testParams['job_id'],
'email_id' => $dao->email_id,
'contact_id' => $groupContact,
);
CRM_Mailing_Event_BAO_Queue::create($params);
}
}
}
}
/**
* Load this->header and this->footer.
*/
private function getHeaderFooter() {
if (!$this->header and $this->header_id) {
$this->header = new CRM_Mailing_BAO_Component();
$this->header->id = $this->header_id;
$this->header->find(TRUE);
$this->header->free();
}
if (!$this->footer and $this->footer_id) {
$this->footer = new CRM_Mailing_BAO_Component();
$this->footer->id = $this->footer_id;
$this->footer->find(TRUE);
$this->footer->free();
}
}
/**
* Given and array of headers and a prefix, job ID, event queue ID, and hash,
* add a Message-ID header if needed.
*
* i.e. if the global includeMessageId is set and there isn't already a
* Message-ID in the array.
* The message ID is structured the same way as a verp. However no interpretation
* is placed on the values received, so they do not need to follow the verp
* convention.
*
* @param array $headers
* Array of message headers to update, in-out.
* @param string $prefix
* Prefix for the message ID, use same prefixes as verp.
* wherever possible
* @param string $job_id
* Job ID component of the generated message ID.
* @param string $event_queue_id
* Event Queue ID component of the generated message ID.
* @param string $hash
* Hash component of the generated message ID.