forked from civicrm/civicrm-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMailing.php
3140 lines (2801 loc) · 104 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.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2018 |
+--------------------------------------------------------------------+
| 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-2018
*/
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();
}
/**
* @deprecated
*
* @param int $mailingID
*
* @return int
*/
public static function getRecipientsCount($mailingID) {
//rebuild the recipients
self::getRecipients($mailingID);
return civicrm_api3('MailingRecipients', 'getcount', array('mailing_id' => $mailingID));
}
/**
* This function retrieve recipients of selected mailing groups.
*
* @param int $mailingID
*
* @return void
*/
public static function getRecipients($mailingID) {
// load mailing object
$mailingObj = new self();
$mailingObj->id = $mailingID;
$mailingObj->find(TRUE);
$mailing = CRM_Mailing_BAO_Mailing::getTableName();
$contact = CRM_Contact_DAO_Contact::getTableName();
$isSMSmode = (!CRM_Utils_System::isNull($mailingObj->sms_provider_id));
$mailingGroup = new CRM_Mailing_DAO_MailingGroup();
$recipientsGroup = $excludeSmartGroupIDs = $includeSmartGroupIDs = $priorMailingIDs = array();
$dao = CRM_Utils_SQL_Select::from('civicrm_mailing_group')
->select('GROUP_CONCAT(entity_id SEPARATOR ",") as group_ids, group_type, entity_table')
->where('mailing_id = #mailing_id AND entity_table IN ("!groupTableName", "civicrm_mailing")')
->groupBy(array('group_type', 'entity_table'))
->param('!groupTableName', CRM_Contact_BAO_Group::getTableName())
->param('#mailing_id', $mailingID)
->execute();
while ($dao->fetch()) {
if ($dao->entity_table == 'civicrm_mailing') {
$priorMailingIDs[$dao->group_type] = explode(',', $dao->group_ids);
}
else {
$recipientsGroup[$dao->group_type] = explode(',', $dao->group_ids);
}
}
// there is no need to proceed further if no mailing group is selected to include recipients,
// but before return clear the mailing recipients populated earlier since as per current params no group is selected
if (empty($recipientsGroup['Include']) && empty($priorMailingIDs['Include'])) {
CRM_Core_DAO::executeQuery(" DELETE FROM civicrm_mailing_recipients WHERE mailing_id = %1 ", array(1 => array($mailingID, 'Integer')));
return;
}
list($location_filter, $order_by) = self::getLocationFilterAndOrderBy($mailingObj->email_selection_method, $mailingObj->location_type_id);
// get all the saved searches AND hierarchical groups
// and load them in the cache
foreach ($recipientsGroup as $groupType => $groupIDs) {
$groupDAO = CRM_Utils_SQL_Select::from('civicrm_group')
->where('id IN (#groupIDs)')
->where('saved_search_id != 0 OR saved_search_id IS NOT NULL OR children IS NOT NULL')
->param('#groupIDs', $groupIDs)
->execute();
while ($groupDAO->fetch()) {
if ($groupDAO->cache_date == NULL) {
CRM_Contact_BAO_GroupContactCache::load($groupDAO);
}
if ($groupType == 'Include') {
$includeSmartGroupIDs[] = $groupDAO->id;
}
else {
$excludeSmartGroupIDs[] = $groupDAO->id;
}
}
}
// Create a temp table for contact exclusion.
$excludeTempTablename = "excluded_recipients_temp" . substr(sha1(rand()), 0, 4);
$includedTempTablename = "included_recipients_temp" . substr(sha1(rand()), 0, 4);
$mailingGroup->query(
"CREATE TEMPORARY TABLE $excludeTempTablename
(contact_id int primary key)
ENGINE=HEAP"
);
// populate exclude temp-table with recipients to be excluded from the list
// on basis of selected recipients groups and/or previous mailing
if (!empty($recipientsGroup['Exclude'])) {
CRM_Utils_SQL_Select::from('civicrm_group_contact')
->select('DISTINCT contact_id')
->where('status = "Added" AND group_id IN (#groups)')
->param('#groups', $recipientsGroup['Exclude'])
->insertInto($excludeTempTablename, array('contact_id'))
->execute();
if (count($excludeSmartGroupIDs)) {
CRM_Utils_SQL_Select::from('civicrm_group_contact_cache')
->select('contact_id')
->where('group_id IN (#groups)')
->param('#groups', $excludeSmartGroupIDs)
->insertIgnoreInto($excludeTempTablename, array('contact_id'))
->execute();
}
}
if (!empty($priorMailingIDs['Exclude'])) {
CRM_Utils_SQL_Select::from('civicrm_mailing_recipients')
->select('DISTINCT contact_id')
->where('mailing_id IN (#mailings)')
->param('#mailings', $priorMailingIDs['Exclude'])
->insertIgnoreInto($excludeTempTablename, array('contact_id'))
->execute();
}
if (!empty($recipientsGroup['Base'])) {
CRM_Utils_SQL_Select::from('civicrm_group_contact')
->select('DISTINCT contact_id')
->where('status = "Removed" AND group_id IN (#groups)')
->param('#groups', $recipientsGroup['Base'])
->insertIgnoreInto($excludeTempTablename, array('contact_id'))
->execute();
}
$entityColumn = $isSMSmode ? 'phone_id' : 'email_id';
$entityTable = $isSMSmode ? CRM_Core_DAO_Phone::getTableName() : CRM_Core_DAO_Email::getTableName();
// Get all the group contacts we want to include.
$mailingGroup->query(
"CREATE TEMPORARY TABLE $includedTempTablename
(contact_id int primary key, $entityColumn int)
ENGINE=HEAP"
);
if ($isSMSmode) {
$includeFilters = array(
"mg.group_type = 'Include'",
'mg.search_id IS NULL',
"$contact.is_opt_out = 0",
"$contact.is_deceased <> 1",
"$entityTable.phone_type_id = " . CRM_Core_PseudoConstant::getKey('CRM_Core_DAO_Phone', 'phone_type_id', 'Mobile'),
"$entityTable.phone IS NOT NULL",
"$entityTable.phone != ''",
"$entityTable.is_primary = 1",
"mg.mailing_id = #mailingID",
'temp.contact_id IS null',
);
$order_by = array("$entityTable.is_primary = 1");
}
else {
// Criterias to filter recipients that need to be included
$includeFilters = array(
"$contact.do_not_email = 0",
"$contact.is_opt_out = 0",
"$contact.is_deceased <> 1",
$location_filter,
"$entityTable.email IS NOT NULL",
"$entityTable.email != ''",
"$entityTable.on_hold = 0",
"mg.mailing_id = #mailingID",
'temp.contact_id IS NULL',
);
}
// Get the group contacts, but only those which are not in the
// exclusion temp table.
if (!empty($recipientsGroup['Include'])) {
CRM_Utils_SQL_Select::from($entityTable)
->select("$contact.id as contact_id, $entityTable.id as $entityColumn")
->join($contact, " INNER JOIN $contact ON $entityTable.contact_id = $contact.id ")
->join('gc', " INNER JOIN civicrm_group_contact gc ON gc.contact_id = $contact.id ")
->join('mg', " INNER JOIN civicrm_mailing_group mg ON gc.group_id = mg.entity_id AND mg.search_id IS NULL ")
->join('temp', " LEFT JOIN $excludeTempTablename temp ON $contact.id = temp.contact_id ")
->where('gc.group_id IN (#groups) AND gc.status = "Added"')
->where($includeFilters)
->groupBy(array("$contact.id", "$entityTable.id"))
->replaceInto($includedTempTablename, array('contact_id', $entityColumn))
->param('#groups', $recipientsGroup['Include'])
->param('#mailingID', $mailingID)
->execute();
}
// Get recipients selected in prior mailings
if (!empty($priorMailingIDs['Include'])) {
CRM_Utils_SQL_Select::from('civicrm_mailing_recipients')
->select("contact_id, $entityColumn")
->where('mailing_id IN (#mailings)')
->param('#mailings', $priorMailingIDs['Include'])
->insertIgnoreInto($includedTempTablename, array('contact_id', $entityColumn))
->execute();
}
if (count($includeSmartGroupIDs)) {
$query = CRM_Utils_SQL_Select::from($contact)
->select("$contact.id as contact_id, $entityTable.id as $entityColumn")
->join($entityTable, " INNER JOIN $entityTable ON $entityTable.contact_id = $contact.id ")
->join('gc', " INNER JOIN civicrm_group_contact_cache gc ON $contact.id = gc.contact_id ")
->join('mg', " INNER JOIN civicrm_mailing_group mg ON gc.group_id = mg.entity_id AND mg.search_id IS NULL ")
->join('temp', " LEFT JOIN $excludeTempTablename temp ON $contact.id = temp.contact_id ")
->where('gc.group_id IN (#groups)')
->where($includeFilters)
->orderBy($order_by)
->replaceInto($includedTempTablename, array('contact_id', $entityColumn))
->param('#groups', $includeSmartGroupIDs)
->param('#mailingID', $mailingID)
->execute();
}
// Construct the filtered search queries.
$dao = CRM_Utils_SQL_Select::from('civicrm_mailing_group')
->select('search_id, search_args, entity_id')
->where('search_id IS NOT NULL AND mailing_id = #mailingID')
->param('#mailingID', $mailingID)
->execute();
while ($dao->fetch()) {
$customSQL = CRM_Contact_BAO_SearchCustom::civiMailSQL($dao->search_id,
$dao->search_args,
$dao->entity_id
);
$query = "REPLACE INTO {$includedTempTablename} ($entityColumn, contact_id) {$customSQL} ";
$mailingGroup->query($query);
}
list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause();
// clear all the mailing recipients before populating
CRM_Core_DAO::executeQuery(" DELETE FROM civicrm_mailing_recipients WHERE mailing_id = %1 ", array(1 => array($mailingID, 'Integer')));
$selectClause = array('#mailingID', 'i.contact_id', "i.$entityColumn");
// CRM-3975
$orderBy = array("i.contact_id", "i.$entityColumn");
$query = CRM_Utils_SQL_Select::from('civicrm_contact contact_a')->join('i', " INNER JOIN {$includedTempTablename} i ON contact_a.id = i.contact_id ");
if (!$isSMSmode && $mailingObj->dedupe_email) {
$orderBy = array("MIN(i.contact_id)", "MIN(i.$entityColumn)");
$query = $query->join('e', " INNER JOIN civicrm_email e ON e.id = i.email_id ")->groupBy("e.email");
if (CRM_Utils_SQL::supportsFullGroupBy()) {
$selectClause = array('#mailingID', 'ANY_VALUE(i.contact_id) contact_id', "ANY_VALUE(i.$entityColumn) $entityColumn", "e.email");
}
}
$query = $query->select($selectClause)->orderBy($orderBy);
if (!CRM_Utils_System::isNull($aclFrom)) {
$query = $query->from('acl', $aclFrom);
}
if (!CRM_Utils_System::isNull($aclWhere)) {
$query = $query->where($aclWhere);
}
// this mean if dedupe_email AND the mysql 5.7 supports ONLY_FULL_GROUP_BY mode then as
// SELECT must contain 'email' column as its used in GROUP BY, so in order to resolve This
// here the whole SQL code is wrapped up in FROM table i and not selecting email column for INSERT
if ($key = array_search('e.email', $selectClause)) {
unset($selectClause[$key]);
$sql = $query->toSQL();
CRM_Utils_SQL_Select::from("( $sql ) AS i ")
->select($selectClause)
->insertInto('civicrm_mailing_recipients', array('mailing_id', 'contact_id', $entityColumn))
->param('#mailingID', $mailingID)
->execute();
}
else {
$query->insertInto('civicrm_mailing_recipients', array('mailing_id', 'contact_id', $entityColumn))
->param('#mailingID', $mailingID)
->execute();
}
// 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($mailingID);
}
// Delete the temp table.
$mailingGroup->reset();
$mailingGroup->query(" DROP TEMPORARY TABLE $excludeTempTablename ");
$mailingGroup->query(" DROP TEMPORARY TABLE $includedTempTablename ");
}
/**
* Function to retrieve location filter and order by clause later used by SQL query that is used to fetch and include mailing recipients
*
* @param string $email_selection_method
* @param int $location_type_id
*
* @return array
*/
public static function getLocationFilterAndOrderBy($email_selection_method, $location_type_id) {
$email = CRM_Core_DAO_Email::getTableName();
// 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.
$orderBy = array("$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.
$orderBy = array("$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.
$orderBy = array("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)";
$orderBy = array("$email.is_bulkmail");
}
return array($location_filter, $orderBy);
}
/**
* @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 {
$mg = CRM_Mailing_DAO_MailingGroup::getTableName();
$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.
*
* @param bool $onlyHrefs
*
* @return array|string
*/
private function getPatterns($onlyHrefs = FALSE) {
$patterns = array();
$protos = '(https?|ftp|mailto)';
$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) . '}imu';
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
*
* @deprecated
* This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
*/
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 done that)
*
* @return array
* reference to an assoc array
*/
public function getTemplates() {
if (!$this->templates) {
$this->getHeaderFooter();
$this->templates = array();
if ($this->body_text || !empty($this->header)) {
$template = array();
if (!empty($this->header->body_text)) {
$template[] = $this->header->body_text;
}
elseif (!empty($this->header->body_html)) {
$template[] = CRM_Utils_String::htmlToText($this->header->body_html);
}
if ($this->body_text) {
$template[] = $this->body_text;
}
else {
$template[] = CRM_Utils_String::htmlToText($this->body_html);
}
if (!empty($this->footer->body_text)) {
$template[] = $this->footer->body_text;
}
elseif (!empty($this->footer->body_html)) {
$template[] = CRM_Utils_String::htmlToText($this->footer->body_html);
}
$this->templates['text'] = implode("\n", $template);
}
// To check for an html part strip tags
if (trim(strip_tags($this->body_html, '<img>'))) {
$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 (empty($this->templates['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);
}
CRM_Utils_Hook::alterMailContent($this->templates);
}
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 (!empty($testParams['test_group']) && 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 <> 1
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.
*
* @return void
*/
public static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
$config = CRM_Core_Config::singleton();
$localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
$emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
$includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
$fields = array();
$fields[] = 'Message-ID';
// CRM-17754 check if Resent-Message-id is set also if not add it in when re-laying reply email
if ($prefix == 'r') {
$fields[] = 'Resent-Message-ID';
}
foreach ($fields as $field) {
if ($includeMessageId && (!array_key_exists($field, $headers))) {
$headers[$field] = '<' . implode($config->verpSeparator,
array(
$localpart . $prefix,
$job_id,
$event_queue_id,
$hash,
)
) . "@{$emailDomain}>";
}
}
}
/**
* Static wrapper for getting verp and urls.
*
* @param int $job_id
* ID of the Job associated with this message.
* @param int $event_queue_id
* ID of the EventQueue.
* @param string $hash
* Hash of the EventQueue.
* @param string $email
* Destination address.
*
* @return array
* (reference) array array ref that hold array refs to the verp info and urls
*/
public static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
// create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
$config = CRM_Core_Config::singleton();
$bao = new CRM_Mailing_BAO_Mailing();
$bao->_domain = CRM_Core_BAO_Domain::getDomain();
$bao->from_name = $bao->from_email = $bao->subject = '';
// use $bao's instance method to get verp and urls
list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
return array($verp, $urls);
}
/**
* Get verp, urls and headers
*
* @param int $job_id
* ID of the Job associated with this message.
* @param int $event_queue_id
* ID of the EventQueue.
* @param string $hash
* Hash of the EventQueue.
* @param string $email
* Destination address.
*
* @param bool $isForward
*
* @return array
* array ref that hold array refs to the verp info, urls, and headers
*/
public function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
$config = CRM_Core_Config::singleton();
/**
* Inbound VERP keys:
* reply: user replied to mailing
* bounce: email address bounced
* unsubscribe: contact opts out of all target lists for the mailing
* resubscribe: contact opts back into all target lists for the mailing
* optOut: contact unsubscribes from the domain
*/
$verp = array();
$verpTokens = array(
'reply' => 'r',
'bounce' => 'b',
'unsubscribe' => 'u',
'resubscribe' => 'e',
'optOut' => 'o',
);
$localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
$emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
// Make sure the user configured the site correctly, otherwise you just get "Could not identify any recipients. Perhaps the group is empty?" from the mailing UI
if (empty($emailDomain)) {
CRM_Core_Error::debug_log_message('Error setting verp parameters, defaultDomain is NULL. Did you configure the bounce processing account for this domain?');
}
foreach ($verpTokens as $key => $value) {
$verp[$key] = implode($config->verpSeparator,
array(
$localpart . $value,
$job_id,
$event_queue_id,
$hash,
)
) . "@$emailDomain";
}
//handle should override VERP address.
$skipEncode = FALSE;
if ($job_id &&
self::overrideVerp($job_id)
) {
$verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
}
$urls = array(
'forward' => CRM_Utils_System::url('civicrm/mailing/forward',
"reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
TRUE, NULL, TRUE, TRUE
),
'unsubscribeUrl' => CRM_Utils_System::url('civicrm/mailing/unsubscribe',
"reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
TRUE, NULL, TRUE, TRUE
),
'resubscribeUrl' => CRM_Utils_System::url('civicrm/mailing/resubscribe',
"reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
TRUE, NULL, TRUE, TRUE
),
'optOutUrl' => CRM_Utils_System::url('civicrm/mailing/optout',
"reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
TRUE, NULL, TRUE, TRUE
),
'subscribeUrl' => CRM_Utils_System::url('civicrm/mailing/subscribe',
'reset=1',
TRUE, NULL, TRUE, TRUE
),
);
$headers = array(
'Reply-To' => $verp['reply'],
'Return-Path' => $verp['bounce'],