forked from kenwest/cbf-drupal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcbf_civicrm.module
1176 lines (1108 loc) · 40.6 KB
/
cbf_civicrm.module
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
/*
* This function determines the audience for an email and sets up data for
* other functions to use
*/
function _cbf_civicrm_email_audience($params, $context) {
/*
* This function can be called from cbf_civicrm_civicrm_alterMailContent
* and cbf_civicrm_civicrm_alterMailParams which have differences between
* their parameters. So we just need to reconcile them.
*/
$contextId = false;
$workflow = $params['workflow'] ?? $params['valueName'] ?? $params['groupName'] ?? '';
if (empty($context)) {
if (isset($params['mailingID'])) {
$context = 'civimail';
$contextId = $params['mailingID'];
}
else if ($workflow) {
$context = 'singleEmail';
}
else if (!empty($params['messageTemplateID'])) {
$context = 'messageTemplate';
}
else {
$context = 'civimail';
}
}
/*
* For CiviMails, cbf_civicrm_civicrm_alterMailContent() is called before
* cbf_civicrm_civicrm_alterMailParams(). So a call to this function with
* empty $context and $params['mailingID'] set to a new value is a signal
* that a new mailing is being processed.
*/
$audienceData = &drupal_static(__FUNCTION__);
if (
empty($audienceData)
|| ($context == 'civimail'
&& $contextId
&& $contextId != $audienceData['context id']) // See note above
) {
$audienceData = [
'audience' => '',
'audiences' => [
'christian' => [
'colour' => '#1c9cd6',
],
],
'cache' => [],
'context' => $context,
'context id' => $contextId,
];
$domains = [
'christian' => [
'machine_name' => 'christian',
'sitename' => 'City Bible Forum',
'subdomain' => 'civicrm.citybibleforum.org',
'aliases' => [],
],
];
foreach ($domains as $domain) {
$domainAudience = $domain['machine_name'];
if (isset($audienceData['audiences'][$domainAudience])) {
$audienceData['audiences'][$domainAudience]['name'] = $domain['sitename'];
$audienceData['audiences'][$domainAudience]['host'] = 'https://' . $domain['subdomain'];
$audienceData['audiences'][$domainAudience]['email domain'] = $domain['subdomain'];
$audienceData['audiences'][$domainAudience]['hostnames'] = [];
$audienceData['audiences'][$domainAudience]['hostnames'][] = $domain['subdomain'];
foreach ($domain['aliases'] as $alias) {
$audienceData['audiences'][$domainAudience]['hostnames'][] = $alias['pattern'];
}
$h = '(' . implode('|', $audienceData['audiences'][$domainAudience]['hostnames']) . ')';
$h = str_replace('.', '\.', $h);
$audienceData['audiences'][$domainAudience]['patterns'] = [
'colour' => '!' . '(color: |")' . $audienceData['audiences'][$domainAudience]['colour'] . '(;|")' . '!i',
'20' => '!' . ' href=("|\')(http(s)?:)?//' . $h . '("|\'|/)' . '!i',
'30' => '!' . '^' . $h . '$' . '!i',
'email domain' => '!' . '(@)' . $h . '(>|$)' . '!i',
'email name' => '!' . '(".*)(' . $audienceData['audiences'][$domainAudience]['name'] . ')(.*")' . '!i',
'html' => '!' . ' (href|src)=("|\')(http(s)?:)?//' . $h . '("|\'|/)' . '!i',
'text' => '!' . '(^| )(http(s)?:)?//' . $h . '( |/)?' . '!i',
];
}
}
/*
* The $context and $params guide which $audience rules are applicable
*/
switch ($context) {
case 'singleEmail':
switch ($workflow) {
case 'UNKNOWN':
/*
* We can't set the $audienceData yet.
*/
$audienceData = null;
return $audienceData;
}
break;
case 'messageTemplate':
/*
* It's too early to set an $audience, knowing that we'll return here
* later with context 'singleEmail'.
*/
$audienceData = null;
return $audienceData;
}
/*
* Since we are now only processing recurring donations, the audience will
* always be 'christian'
*/
$audienceData['audience'] = 'christian';
}
return $audienceData;
}
/*
* This function amends an email's text to suit the $audience
*/
function _cbf_civicrm_amend_email(&$html, &$text, $audienceData) {
/*
* If $html is empty then do nothing. This protects against the case that
* we are processing an SMS.
* - We can't set the Campaign for a Bulk SMS so the Audience data is
* unreliable.
* - We have modified CRM_SMS_Provider::getMessage() to behave as if the
* HTML part is empty.
*
* If $audienceData is empty then do nothing. This protects against workflows
* like 'UNKNOWN'.
*/
if (empty($html) || empty($audienceData)) {
return;
}
/*
* Convert relative URLs to absolute
* Convert old-style email PNG to $audience
* Convert old-style white email PNG to $audience
* Convert old-style social links to $audience (also apply to $text)
* Convert other audience's links to $audience links (html and text)
* Ensure $audience links are well-formed (html and text)
* Convert other audience's colours to $audience colours
* Remove empty paragraphs inserted by CKeditor
* Remove non-breaking spaces inserted by CKeditor
* Convert IMG class attribute-width-NNN to a width attribute
*
* attribute-width-NNN:
* The CKeditor Image Dialog removes width attributes from HTML IMGs. This causes
* an issue for responsive email templates when the email is viewed in Outlook.
* This is resolved by adding a class 'attribute-width-NNN' to the IMG element in
* the message template. The NNN is converted into a width="NNN" attribute that
* is added to the IMG. The 'attribute-width-NNN' class is otherwise ignored.
* There is a risk that the IMG ends up with 2 width attributes, but these should
* have the same value.
*/
$audience = $audienceData['audience'];
$host = $audienceData['audiences'][$audience]['host'];
$name = $audienceData['audiences'][$audience]['name'];
$colour = $audienceData['audiences'][$audience]['colour'];
$replacements = [
[
'comment' => 'Convert relative URLs to absolute',
'from' => '! (href|src)="(/[^/])!i',
'to' => ' $1="' . $host . '$2',
'html' => true,
'text' => false,
],
[
'comment' => "Convert old-style email PNG to $audience",
'from' => '!/themes/cbf2019/logo-email.png!i',
'to' => "/themes/cbf2019/images/$audience/brand/logo-email.png",
'html' => true,
'text' => false,
],
[
'comment' => "Convert old-style white email PNG to $audience",
'from' => '!/themes/cbf2019/logo-white-email.png!i',
'to' => "/themes/cbf2019/images/$audience/brand/logo-white-email.png",
'html' => true,
'text' => false,
],
[
'comment' => "Convert old-style Facebook links to $audience",
'from' => '!https://www\.facebook\.com/CityBibleForum!i',
'to' => "$host/domain/$audience/facebook",
'html' => true,
'text' => true,
],
[
'comment' => "Convert old-style LinkedIn links to $audience",
'from' => '!https://www\.linkedin\.com/company/city-bible-forum!i',
'to' => "$host/domain/$audience/linkedin",
'html' => true,
'text' => true,
],
[
'comment' => "Convert old-style Youtube links to $audience",
'from' => '!https://www\.youtube\.com/channel/UCt1YTYKDW8f5s5q9McoHJ_Q!i',
'to' => "$host/domain/$audience/youtube",
'html' => true,
'text' => true,
],
[
'comment' => "Convert old-style Instagram links to $audience",
'from' => '!https://instagram\.com/city_bible_forum!i',
'to' => "$host/domain/$audience/instagram",
'html' => true,
'text' => true,
],
[
'comment' => "Convert IMG ALT text to $name",
'from' => '!img alt="City Bible Forum"!i',
'to' => "img alt=\"$name\"",
'html' => true,
'text' => true,
],
[
'comment' => 'Remove empty paragraphs inserted by CKeditor',
'from' => '!<p>(\r\n\t)* </p>!i',
'to' => '',
'html' => true,
'text' => false,
],
[
'comment' => 'Replace non-breaking spaces inserted by CKeditor with spaces',
'from' => '! !i',
'to' => ' ',
'html' => true,
'text' => false,
],
[
'comment' => 'Convert IMG class attribute-width-NNN to a width attribute',
'from' => '!<img ([^>]+)attribute-width-([0-9]+)([^>]+)/>!i',
'to' => '<img width="$2" $1attribute-width-processed$3/>',
'html' => true,
'text' => false,
],
];
foreach ($audienceData['audiences'] as $a => $data) {
/*
* When $audience is 'christian' we want to preserve the 'general'
* references. In all other cases we want to change the references.
*
* Note that when $a == $audience what we're doing is ensuring the
* $audience links are well-formed (explicitly HTTPS).
*/
if ($audience != 'christian' || $a != 'general') {
$replacements[] = [
'comment' => "Convert HTML $a references to $audience links",
'from' => $data['patterns']['html'],
'to' => ' $1=$2' . $host . '$6',
'html' => true,
'text' => false,
];
$replacements[] = [
'comment' => "Convert text $a references to $audience links",
'from' => $data['patterns']['text'],
'to' => '$1' . $host . '$5',
'html' => false,
'text' => true,
];
}
if ($a != $audience) {
$replacements[] = [
'comment' => "Convert $a colours to $audience colours",
'from' => $data['patterns']['colour'],
'to' => '$1' . $colour . '$2',
'html' => true,
'text' => false,
];
}
}
if ($audience != 'christian') {
$replacements[] = [
'comment' => "Convert christian brand images to $audience images",
'from' => "!/images/christian/brand/!i",
'to' => "/images/$audience/brand/",
'html' => true,
'text' => true,
];
$replacements[] = [
'comment' => "Convert christian domain links to $audience links",
'from' => "!/domain/christian/!i",
'to' => "/domain/$audience/",
'html' => true,
'text' => true,
];
}
foreach ($replacements as $r) {
if ($r['html']) {
$html = preg_replace($r['from'], $r['to'], $html) ?? $html;
}
if ($r['text']) {
$text = preg_replace($r['from'], $r['to'], $text) ?? $text;
}
}
}
/*
* This hook is called after getting the content of the mail and before tokenizing it.
*
* It is called once before sending an email, but can be called multiple times.
*/
function cbf_civicrm_civicrm_alterMailContent(&$content) {
$audienceData = _cbf_civicrm_email_audience($content, null);
if ($audienceData) {
_cbf_civicrm_amend_email($content['html'], $content['text'], $audienceData);
}
}
/*
* This hook is called when an email is about to be sent by CiviCRM.
* It ensures the email contains no relative links.
* It adds the closing tags for the BODY and HTML elements, as these are
* left off so CiviMail can add a tracking token to the email.
*/
function cbf_civicrm_civicrm_alterMailParams( &$params, $context = null ) {
$workflow = $params['workflow'] ?? $params['valueName'] ?? $params['groupName'] ?? '';
$now = date('Y-m-d G:i:s');
// Don't send event confirmations when a Pending attendee is marked as Attended after the event
if ($workflow == 'event_online_receipt'
&& isset($params['tplParams']['participant_status']) && $params['tplParams']['participant_status'] == 'Attended'
&& isset($params['tplParams']['event']['is_pay_later']) && $params['tplParams']['event']['is_pay_later'] == 1
&& isset($params['tplParams']['event']['end_date']) && $params['tplParams']['event']['end_date'] < $now) {
$params['abortMailSend'] = 1;
return;
}
// Don't send participant cancellations after the event
if ($workflow == 'participant_cancelled'
&& isset($params['tplParams']['event']['end_date']) && $params['tplParams']['event']['end_date'] < $now) {
$params['abortMailSend'] = 1;
return;
}
/*
* "Note that this hook is called twice when sending a message template,
* once early in the message generation (before tokens are applied, with
* the context 'messageTemplate') and then later from CRM_Utils_Mail::send()
* with the context 'singleEmail'"
*
* - https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_alterMailParams/
*/
if ($context == 'messageTemplate') {
return; // Wait until next invocation
}
$audienceData = _cbf_civicrm_email_audience($params, $context);
$audience = $audienceData['audience'] ?? '';
/*
* Update the From, Return-Path and Reply-To headers to match the audience.
*
* Do the From header before the others so we have a default value
* The From and Reply-To headers have a name and an address part.
* The Return-Path header only has the address part.
* Skip protected address patterns
* - can't use [email protected] as we have a conflict
* - if m@ts is alias of m@cbf how do we "send as" m@ts?
* - if m@ts is a seperate a/c how do we handle bounces as CiviCRM only
* expects a single IMAP folder (ie Mail Account)
*/
$headerData = [
'headers' => [
'From' => [
'parameter' => [
'civimail' => 'From',
'singleEmail' => 'from',
],
'parts' => [
'email name' => 'name',
'email domain' => 'email domain',
],
'default' => '',
],
'Return-Path' => [
'parameter' => [
'civimail' => 'Return-Path',
'singleEmail' => 'returnPath',
],
'parts' => [
'email domain' => 'email domain',
],
'default' => '!^.*<(.*)>$!i',
],
'Reply-To' => [
'parameter' => [
'civimail' => 'Reply-To',
'singleEmail' => 'replyTo',
],
'parts' => [
'email name' => 'name',
'email domain' => 'email domain',
],
'default' => '!^(.*)$!i',
],
],
'protected' => [
'patterns' => [
'CiviMail sending account' => '!message(\+[.a-z0-9]+)@citybibleforum\.org!i',
],
],
];
if ($audience) {
foreach ($headerData['headers'] as $_ => $header) {
$name = $header['parameter'][$context] ?? '';
if ($name) {
$address = $params[$name] ?? '';
if ($address) {
foreach ($headerData['protected']['patterns'] as $pattern) {
if (preg_match($pattern, $address)) {
continue 2; // This $address is protected: skip to the next $header
}
}
foreach ($header['parts'] as $pattern => $replacement) {
foreach ($audienceData['audiences'] as $a => $data) {
if ($a != $audience) {
$address = preg_replace(
$data['patterns'][$pattern],
'$1' . $audienceData['audiences'][$audience][$replacement] . '$3',
$address) ?? $address;
}
}
}
$params[$name] = $address;
}
else if ($header['default']) { // Default to From if not supplied
$params[$name] = preg_replace(
$header['default'],
'$1',
$params[$headerData['headers']['From']['parameter'][$context]]);
}
}
}
}
/*
* Update the To header to use the Staff email.
*
* An example of this is the Staff Contact form which sends a case_activity
* singleEmail to the staff member addressed by the form.
*/
if ($context == 'singleEmail' && $workflow == 'case_activity' && $params['contactId']) {
$email = \Civi\Api4\Email::get(false)
->addWhere('contact_id', '=', $params['contactId'])
->addWhere('location_type_id:name', '=', 'Staff')
->setLimit(1)
->setCheckPermissions(FALSE)
->execute()
->first();
if ($email) {
$params['toEmail'] = $email['email'];
}
}
_cbf_civicrm_amend_email($params['html'], $params['text'], $audienceData);
$htmlMessage = $params['html'];
if ( $htmlMessage ) {
/*
* Look for the closing tag for the BODY element, and add it if needed
* Can't do this in _cbf_civicrm_amend_email() because the tracking
* image is not added until after cbf_civicrm_civicrm_alterMailContent()
* is called.
*/
if (
stripos($htmlMessage, '<body>') !== false &&
stripos($htmlMessage, '</body>') === false
) {
$htmlMessage .= '</body></html>';
}
/*
* Ensure the email has a Title in its title-field, and that if on-line
* receipts have a title of 'Contribution' give them something better
*/
if (isset($params['subject'])) {
if (isset($params['tplParams'])) {
if (!isset($params['tplParams']['title'])) {
$htmlMessage = preg_replace('!class="title-field"> </p>!i', 'class="title-field"> ' . $params['subject'] . ' </p>', $htmlMessage);
} elseif ($params['tplParams']['title'] == 'Contribution' && $workflow == 'contribution_online_receipt') {
$htmlMessage = preg_replace('!class="title-field"> Contribution </p>!i', 'class="title-field"> ' . $params['subject'] . ' </p>', $htmlMessage);
}
}
}
/*
* Replace the '<tax-invoice/>' HTML element with the Tax Invoice text.
* This is usually empty, except for event registrations and contributions
* for Event Fees and Sales which have a non-zero value.
*/
$taxInvoice = '<tr><td>This email serves as a Tax Invoice. Amounts quoted include GST.</td></tr>';
$isTaxInvoice = false;
switch ($workflow) {
case 'contribution_offline_receipt':
case 'contribution_online_receipt':
if (isset($params['tplParams']['contributionTypeName'])) {
$financialType = $params['tplParams']['contributionTypeName'];
$nonZero = !empty($params['tplParams']['amount']);
}
else {
try {
$contribution = civicrm_api3('Contribution', 'get', array(
'sequential' => 1,
'id' => $params['contributionId'],
));
$financialType = $contribution['values'][0]['financial_type'];
$nonZero = !empty(floatval($contribution['values'][0]['total_amount']));
} catch (CiviCRM_API3_Exception $e) {
$financialType = '';
$nonZero = false;
}
}
switch ($financialType) {
case 'Event Fee':
case 'Sales':
$isTaxInvoice = $nonZero;
break;
}
break;
case 'event_offline_receipt':
case 'event_online_receipt':
if (isset($params['tplParams']['amount'])) {
$isTaxInvoice = !empty($params['tplParams']['amount']);
}
elseif (isset($params['tplParams']['fee'])) {
$isTaxInvoice = !empty($params['tplParams']['fee']);
}
else {
$isTaxInvoice = true;
}
break;
}
$htmlMessage = preg_replace('!<tax-invoice/>!i', $isTaxInvoice ? $taxInvoice : '', $htmlMessage);
/*
* There are occasions when CiviCRM uses an online contribution receipt for
* offline purposes. For example, when a recurring contribution is made
* offline the eWAY processor will use the online receipt template for all
* contributions except the first.
*
* Since the contribution was not made through a contribution page, certain
* items won't appear on the receipt. The HTML for these needs to be generated.
*/
switch ($workflow) {
case 'contribution_online_receipt':
if (stripos($htmlMessage, '<no-contribution-page/>') !== false) {
$noContributionPage = _cbf_civicrm_civicrm_no_contribution_page($params);
$htmlMessage = preg_replace('!<no-contribution-page/>!i', $noContributionPage, $htmlMessage);
}
break;
}
/*
* When sending a single email, remove the 'civimailBlock' from the HTML part.
* This allows email templates to be used for CiviMails and for sending emails.
*/
if ($context == 'singleEmail') {
$htmlMessage = preg_replace('#<!-- civimailBlock -->.*<!-- /civimailBlock -->#is', '', $htmlMessage);
}
/*
* Scheduled Reminder uses Smarty engine by default which strips out any
* CSS <style> that is defined. {literal} ... {/literal} can be used to
* protect the CSS, but if we put this in a template, that template could
* be used in another context where Smarty is not used, and the {literal}
* tokens remain. If any remain, strip them out, as Smarty would have been
* invoked before we get here.
*
* See https://civicrm.stackexchange.com/questions/17643/scheduled-reminders-email-head-css-attributes-are-being-stripped-out/17962#17962
*/
$htmlMessage = preg_replace('#\{[/]?literal\}#', '', $htmlMessage) ?? $htmlMessage;
$params['html'] = $htmlMessage;
}
}
/*
* Generate the HTML for receipts where the payment was created offline but
* uses an online receipt template.
*
* The custom field logic is copied from CRM_Contribute_Form_AdditionalInfo::emailReceipt()
* and the logic for the other items from the contribution_online_receipt
* template.
*/
function _cbf_civicrm_civicrm_no_contribution_page($params) {
$headerFormat = '"text-align: left; padding: 4px; border-bottom: 1px solid #999; background-color: #eee;"';
$labelFormat = '"padding: 4px; border-bottom: 1px solid #999; background-color: #f7f7f7;"';
$dataFormat = '"padding: 4px; border-bottom: 1px solid #999;"';
$result = '';
try {
$contribution = civicrm_api3('Contribution', 'get', array(
'sequential' => 1,
'id' => $params['tplParams']['contributionID'],
));
if ($contribution['is_error'] || $contribution['count'] != 1) {
return $result;
}
$contributionInfo = array(
'Financial Type' => $contribution['values'][0]['financial_type'],
'Receipt Date' => $contribution['values'][0]['receipt_date'],
'Paid By' => $contribution['values'][0]['payment_instrument'],
);
if (!empty($contributionInfo['Receipt Date'])) {
$config = CRM_Core_Config::singleton();
$contributionInfo['Receipt Date'] = CRM_Utils_Date::customFormat($contributionInfo['Receipt Date'], $config->dateformatFull);
}
foreach ($contributionInfo as $label => $data) {
if (!empty($data)) {
$result .= "<tr><td style=$labelFormat>$label</td><td style=$dataFormat>$data</td></tr>";
}
}
$customGroups = array();
$groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', null);
foreach ($groupTree as $groupID => $group) {
if ($groupID == 'info' || empty($group['is_public'])) {
continue;
}
$customGroups[$group['title']] = array();
$nonEmpty = 0;
foreach ($group['fields'] as $k => $field) {
if (!empty($contribution['values'][0]["custom_{$k}"])) {
if ($k == 26) {
$ministry_centre = civicrm_api3('OptionValue', 'getvalue', array(
'sequential' => 1,
'option_group_id' => 329,
'value' => $contribution['values'][0]["custom_{$k}"],
'return' => 'label',
));
$customGroups[$group['title']][$field['label']] = $ministry_centre;
} else {
$customGroups[$group['title']][$field['label']] = $contribution['values'][0]["custom_{$k}"];
}
$nonEmpty++;
} else {
$customGroups[$group['title']][$field['label']] = '';
}
}
if ($nonEmpty == 0) {
unset($customGroups[$group['title']]);
}
}
foreach ($customGroups as $groupTitle => $group) {
$result .= "<tr><th colspan=\"2\" style=$headerFormat>$groupTitle</th></tr>";
foreach ($group as $label => $data) {
$result .= "<tr><td style=$labelFormat>$label</td><td style=$dataFormat>$data</td></tr>";
}
}
} catch (Exception $e) {
;
}
return $result;
}
/*
* This function is called before CiviCRM passes payment details to a Payment Processor.
*/
function cbf_civicrm_civicrm_alterPaymentProcessorParams($paymentObj, &$rawParams, &$cookedParams) {
/*
* For the eWAY processor ...
* If the contact names have not been captured then get them from the contact.
* Capture the Credit Card Holder is captured.
* Clear the Purchaser Address details, since the Billing Address is not captured.
*/
if ($paymentObj instanceof CRM_Core_Payment_Ewayrecurring) {
$is_recur = CRM_Utils_Array::value('is_recur', $rawParams);
$credit_card_holder = CRM_Utils_Array::value('credit_card_holder', $rawParams);
$first_name = null;
$last_name = null;
if (
!empty(CRM_Utils_Array::value('contact_id', $rawParams))
&& (empty(CRM_Utils_Array::value('first_name', $rawParams))
|| empty(CRM_Utils_Array::value('last_name', $rawParams)))
) {
try {
$record = civicrm_api3('Contact', 'get', [
'sequential' => 1,
'return' => ['first_name', 'last_name'],
'id' => CRM_Utils_Array::value('contact_id', $rawParams),
]);
$first_name = $record['values'][0]['first_name'];
$last_name = $record['values'][0]['last_name'];
} catch (CiviCRM_API3_Exception $e) {
;
}
}
if ($is_recur ?? false) {
// Set credit card holder
if ($credit_card_holder) {
$cookedParams['man:CCNameOnCard'] = $credit_card_holder;
}
// Set name if needed
if (empty($cookedParams['man:FirstName']) && !empty($first_name)) {
$cookedParams['man:FirstName'] = $first_name;
}
if (empty($cookedParams['man:LastName']) && !empty($last_name)) {
$cookedParams['man:LastName'] = $last_name;
}
// Set address
$cookedParams['man:Address'] = 'c/o Level 3, 13-15 Bridge St';
$cookedParams['man:Suburb'] = 'Sydney';
$cookedParams['man:State'] = 'NSW';
$cookedParams['man:PostCode'] = '2000';
}
else {
// Set credit card holder
if ($credit_card_holder) {
$cookedParams->CardHolderName($credit_card_holder);
}
// Set name if needed
if (empty(CRM_Utils_Array::value('first_name', $rawParams)) && !empty($first_name)) {
$cookedParams->PurchaserFirstName($first_name);
}
if (empty(CRM_Utils_Array::value('last_name', $rawParams)) && !empty($last_name)) {
$cookedParams->PurchaserLastName($last_name);
}
// Clear address information
$cookedParams->PurchaserAddress('');
$cookedParams->PurchaserPostalCode('');
}
}
/*
* For the PayPal Standard processor ...
* Set the return URLs to come back to this $host to avoid invalid session issues
*/
if ($paymentObj instanceof CRM_Core_Payment_PayPalImpl) {
$host = $_SERVER['SERVER_NAME'];
$cookedParams['notify_url'] = str_replace(
'//citybibleforum.org/',
'//' . $host . '/',
$cookedParams['notify_url']
);
$cookedParams['cancel_return'] = str_replace(
'//citybibleforum.org/',
'//' . $host . '/',
$cookedParams['cancel_return']
);
$cookedParams['return'] = str_replace(
'//citybibleforum.org/',
'//' . $host . '/',
$cookedParams['return']
);
CRM_Core_Error::debug_var('PayPal variables', [
'cooked' => $cookedParams,
]);
}
}
function cbf_civicrm_civicrm_tokens( &$tokens ) {
$tokens['cbf'] = array('cbf.hostname');
}
function cbf_civicrm_civicrm_tokenValues( &$details, &$contactIDs ) {
$config = CRM_Core_Config::singleton( );
$hostname = preg_replace('!^https?://([^/]+)/$!i', '$1', $config->userFrameworkBaseURL);
if (is_array($contactIDs)) {
foreach ($details as $id => $detail) {
$details[$id]['cbf.hostname'] = $hostname;
}
}
else {
$details['cbf.hostname'] = $hostname;
}
}
/*
* Add extra variables to help with debugging, then return false so
* the standard error handling continues.
*/
function cbf_civicrm_fatal_error_handler(&$vars) {
/*
* Add extra $vars to help with debugging
*/
$vars['ip'] = ip_address();
$vars['host'] = $_SERVER['HTTP_HOST'];
$vars['url'] = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$vars['agent'] = $_SERVER['HTTP_USER_AGENT'] ?? 'not available';
if (user_is_logged_in()) {
$vars['username'] = $GLOBALS['user']->name;
}
/*
* There are a number of annoying errors that get logged. They seem to be due to
* robots etc. The $ignore array stores the patterns that should be ignored.
*
* The $ignore array consists of a number of pattern sets. Each set is matched
* against elements of the $vars array. If all the patterns in a set match, we
* simply return 'true'. This tells CiviCRM to abend processing, and nothing
* is logged.
*
* Note that the preg_match uses '#' as a pattern delimiter so this should not
* be used in a pattern in $ignore.
*/
$ignore = [
[
'message' => 'Invalid value passed to getPayment function',
'url' => '/civicrm/event/register.*id=[0-9][0-9][0-9]($|[^0-9])',
],
[
// People try to inject SQL via the Id parameter
'message' => 'id .* is not of the type Positive',
'guard' => 'SQL injection issue',
],
[
'message' => 'Invalid form parameters',
'url' => '/civicrm/mailing/forward$',
],
[
'message' => 'Missing (input )?parameters',
'url' => '/civicrm/mailing/(optout|unsubscribe)$',
],
[
'agent' => 'detectify\.com',
],
[
'message' => 'Error type: Could not find a valid session key',
],
[
// Robots trawling templates/CRM/common/paymentBlock.tpl
'message' => 'processor_id \(value: \) is not of the type Integer',
'url' => '/civicrm/payment/form\?.+&processor_id=$',
],
[
// People try to poison our database by unsubscribing or opting out
'message' => '(There was an error in your request|Missing (input )?parameters)',
'url' => '/civicrm/mailing/(optout|unsubscribe)\?.+',
'guard' => 'Mailing unsubscribe issue',
],
[
// Robots trawling an old 'sign Petition' link
'message' => 'Petition is no longer active',
'url' => '/civicrm/petition/sign\?',
'agent' => 'bot',
],
[
// Robots trawling a registration link
'message' => 'Could not find valid value for id',
'url' => '/civicrm/event/register$',
'agent' => 'bot',
],
[
// People who register and re-visit the Thankyou page
'message' => 'Could not find valid value for id',
'url' => '/civicrm/event/register\?_qf_ThankYou_display=true&qfKey=',
],
[
// People who are attempting to hack trackable URLs
'message' => 'One of parameters .* is not of the type Integer',
'url' => '/sites/all/modules/civicrm/extern/url\.php',
'guard' => 'Trackable URL issue',
],
[
// People who trigger the IDS
'message' => 'Your activity is a bit suspicious, hence aborting',
'guard' => 'IDS issue',
],
];
foreach ($ignore as $patternSet) {
$guard = false;
foreach ($patternSet as $element => $pattern) {
if ($element == 'guard') {
$guard = $pattern;
}
else if (preg_match('#' . $pattern . '#i', $vars[$element] ?? '') != 1) {
continue 2;
}
}
if (!empty($guard)) {
CRM_Core_Error::debug_log_message("|CiviCRM guard|$guard|anonymous|{$vars['ip']}|{$vars['url']}");
}
return true;
}
$vars['ip-details'] = json_decode(file_get_contents("http://ipinfo.io/" . $vars['ip'] . "/json"));
if (isset($_SESSION)) {
$vars['session'] = $_SESSION;
unset($vars['session']['csrf_token_seed']);
unset($vars['session']['CiviCRM']['qfPrivateKey']);
}
return false;
}
/*
* A hook that gets called by the AccountSync extension, prior to pulling data
* from Xero.
*
* @param string $entity entity - eg. 'contact'
* @param array $data data from accounts being processing
* @param bool $save save? - set this to false if it should be skipped
* @param $params
*
* @return mixed
* Ignore value.
*/
function cbf_civicrm_civicrm_accountPullPreSave($entity, &$data, &$save, &$params) {
switch ($entity) {
case 'contact':
// Don't try to pull Contacts that are not from CiviCRM
if (
!isset($params['contact_id']) ||
!is_numeric($params['contact_id']) ||
$params['contact_id'] > 100000
) {
$save = false;
}
break;
case 'invoice':
// Don't try to pull Invoices when the Contribution Id is not numeric
if (isset($params['contribution_id']) && !is_numeric($params['contribution_id'])) {
$save = false;
}
break;
}
}
/*
* A hook that gets called by the AccountSync extension, prior to pushing data
* to Xero.
*
* @param string $entity entity - eg. 'contact'
* @param array $data data from accounts being processing
* @param bool $save save? - set this to false if it should be skipped
* @param $params
*
* @return mixed
* Ignore value.
*/
function cbf_civicrm_civicrm_accountPushAlterMapped($entity, &$data, &$save, &$params) {
switch ($entity) {
case 'contact':
/* Baulk if all the Contributions for this Contact have
* - the Suppress Xero Invoice is set
* - the contribution is a test
* - the contribution is zero-valued
*/
try {
$contributions = \Civi\Api4\Contribution::get(FALSE)
->addWhere('contact_id', '=', $data['contact_id'])
->addClause(
'OR',
['Xero_invoice.Suppress_Xero_invoice', '=', 0],
['Xero_invoice.Suppress_Xero_invoice', 'IS NULL'])
->addWhere('is_test', '=', FALSE)
->addWhere('total_amount', '>', 0)
->setLimit(1)
->execute();
$save = false;
foreach ($contributions as $_) {
$save = true;
}
} catch (\API_Exception $e) {
CRM_Core_Error::debug_var('cbf_civicrm_civicrm_accountPushAlterMapped exception', $e);
}
// Remove prefixes etc from Contact name
if ($data['contact_type'] == 'Individual') {
$params['Name'] = $data['first_name'] . ' ' . $data['last_name'] . ' - ' . $data['contact_id'];
}
// Highlight deleted contacts in Xero
$deletedSuffix = ' (deleted in CiviCRM)';
if (!empty($data['contact_is_deleted']) && stristr($params['Name'], $deletedSuffix) === false) {
$params['Name'] .= $deletedSuffix;
}
break;
case 'invoice':
/* Baulk if
* - the Suppress Xero Invoice is set
* - the contribution is a test
* - the contribution is zero-valued
*/
if (!empty($data['custom_43']) || $data['is_test'] != '0' || $data['total_amount'] == '0.00') {
$save = false;
break;