forked from colemanw/webform_civicrm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wf_crm_webform_postprocess.inc
2665 lines (2500 loc) · 105 KB
/
wf_crm_webform_postprocess.inc
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
/**
* @file
* Front-end form validation and post-processing.
*/
module_load_include('inc', 'webform_civicrm', 'includes/wf_crm_webform_base');
class wf_crm_webform_postprocess extends wf_crm_webform_base {
// Variables used during validation
private $form;
private $form_state;
private $crmValues;
private $rawValues;
private $multiPageDataLoaded;
private $billing_params = [];
private $totalContribution = 0;
private $contributionIsIncomplete = FALSE;
private $contributionIsPayLater = FALSE;
// During validation this contains an array of known contact ids and the placeholder 0 for valid contacts
// During submission processing this contains an array of known contact ids
private $existing_contacts = [];
// Variables used during submission processing
private $submission;
private $update = [];
private $all_fields;
private $all_sets;
private $shared_address = [];
// Cache an instance of this object
// @see self::singleton()
static $singleton;
const
BILLING_MODE_LIVE = 1,
BILLING_MODE_MIXED = 3;
function __construct($node) {
civicrm_initialize();
$this->node = $node;
$this->settings = $node->webform_civicrm;
$this->data = $this->settings['data'];
$this->fixPaymentProcessorID();
$this->enabled = wf_crm_enabled_fields($node);
$this->all_fields = wf_crm_get_fields();
$this->all_sets = wf_crm_get_fields('sets');
}
/**
* This is first called during form validation. We create an instance of this object and stash it in a static variable.
* It is destroyed and rebuilt between each page submission, but after (successful) validation of the final page,
* this cache allows the object instance to persist throughout (final) validate, preSave and postSave operations.
* @param stdClass $node
* @return wf_crm_webform_postprocess
*/
public static function singleton($node) {
if (!self::$singleton) {
self::$singleton = new wf_crm_webform_postprocess($node);
}
return self::$singleton;
}
/**
* Called after a webform is submitted
* Or, for a multipage form, called after each page
* @param array $form
* @param array $form_state (reference)
*/
public function validate($form, &$form_state) {
$this->form = $form;
$this->form_state = &$form_state;
$this->rawValues = _webform_client_form_submit_flatten($this->node, wf_crm_aval($this->form_state, 'values:submitted'));
$this->crmValues = wf_crm_enabled_fields($this->node, $this->rawValues);
// Even though this object is destroyed between page submissions, this trick allows us to persist some data - see below
$this->ent = wf_crm_aval($form_state, 'civicrm:ent', []);
$this->hiddenFieldValidation();
$this->validateThisPage($this->form['submitted']);
if (!empty($this->data['participant']) && !empty($this->data['participant_reg_type'])) {
$this->loadMultiPageData();
$this->validateParticipants();
}
// Process live contribution. If the transaction is unsuccessful it will trigger a form validation error.
if ($this->contribution_page) {
// Ensure contribution js is still loaded if the form has to refresh
$this->addPaymentJs();
$this->loadMultiPageData();
if ($this->tallyLineItems()) {
if ($this->isLivePaymentProcessor() && $this->isPaymentPage() && !form_get_errors()) {
if ($this->validateBillingFields()) {
if ($this->createBillingContact()) {
$this->submitLivePayment();
}
}
}
}
}
// Even though this object is destroyed between page submissions, this trick allows us to persist some data - see above
$form_state['civicrm']['ent'] = $this->ent;
$form_state['civicrm']['line_items'] = $this->line_items;
}
/**
* Process webform submission when it is about to be saved. Called by the following hook:
* @see webform_civicrm_webform_submission_presave
* @param stdClass $submission
*/
public function preSave(&$submission) {
$this->submission = &$submission;
$this->data = $this->settings['data'];
// Check for existing submission
$this->setUpdateParam();
// Fill $this->id from existing contacts
$this->getExistingContactIds();
// While saving a draft, just skip to postSave and write the record
if (!empty($this->submission->is_draft)) {
return;
}
$this->fillDataFromSubmission();
//Fill Custom Contact reference fields.
$this->fillContactRefs(TRUE);
// Create/update contacts
foreach ($this->data['contact'] as $c => $contact) {
if (empty($this->ent['contact'][$c]['id'])) {
// Don't create contact if we don't have a name or email
if ($this->isContactEmpty($contact)) {
$this->ent['contact'][$c]['id'] = 0;
continue;
}
$this->ent['contact'][$c]['id'] = $this->findDuplicateContact($contact);
}
// Current employer must wait for ContactRef ids to be filled
unset($contact['contact'][1]['employer_id']);
$newContact = empty($this->ent['contact'][$c]['id']);
// Create new contact
if ($newContact) {
$this->ent['contact'][$c]['id'] = $this->createContact($contact);
}
if ($c == 1) {
$this->setLoggingContact();
}
// Update existing contact
if (!$newContact) {
$this->updateContact($contact, $c);
}
}
// $this->ent['contact'] will now contain all contacts in order, with 0 as a placeholder id for any contact not saved
ksort($this->ent['contact']);
// Once all contacts are saved we can fill contact ref fields
$this->fillContactRefs();
// Save a non-live transaction
if (empty($this->ent['contribution'][1]['id']) && $this->totalContribution) {
$this->createDeferredPayment();
}
// Create/update other data associated with contacts
foreach ($this->data['contact'] as $c => $contact) {
$cid = $this->ent['contact'][$c]['id'];
if (!$cid) {
continue;
}
$this->saveCurrentEmployer($contact, $cid);
$this->fillHiddenContactFields($cid, $c);
$this->saveContactLocation($contact, $cid, $c);
$this->saveGroupsAndTags($contact, $cid, $c);
// Process relationships
foreach (wf_crm_aval($contact, 'relationship', []) as $n => $params) {
$relationship_type_id = wf_crm_aval($params, 'relationship_type_id');
if ($relationship_type_id) {
foreach ((array) $relationship_type_id as $params['relationship_type_id']) {
$this->processRelationship($params, $cid, $this->ent['contact'][$n]['id']);
}
}
}
// Process event participation
if (isset($this->all_sets['participant']) && !empty($this->data['participant_reg_type'])) {
$this->processParticipants($c, $cid);
}
}
// We do this after all contacts and addresses exist
$this->processSharedAddresses();
// Process memberships after relationships have been created
foreach ($this->ent['contact'] as $c => $contact) {
if ($contact['id'] && isset($this->all_sets['membership']) && !empty($this->data['membership'][$c]['number_of_membership'])) {
$this->processMemberships($c, $contact['id']);
}
}
}
/**
* Process webform submission after it is has been saved. Called by the following hooks:
* @see webform_civicrm_webform_submission_insert
* @see webform_civicrm_webform_submission_update
* @param stdClass $submission
*/
public function postSave($submission) {
$this->submission = $submission;
if (empty($this->submission->is_draft)) {
// Save cases
if (!empty($this->data['case']['number_of_case'])) {
$this->processCases();
}
// Save activities
if (!empty($this->data['activity']['number_of_activity'])) {
$this->processActivities();
}
// Save grants
if (isset($this->data['grant']['number_of_grant'])) {
$this->processGrants();
}
// Save contribution line-items
if (!empty($this->ent['contribution'][1]['id'])) {
$this->processContribution();
}
}
// Write record; we do this when creating, updating, or saving a draft of a webform submission.
$record = $this->formatSubmission();
drupal_write_record('webform_civicrm_submissions', $record, $this->update);
// Calling an IPN payment processor will result in a redirect so this happens after everything else
if (empty($this->submission->is_draft) && !empty($this->ent['contribution'][1]['id']) && $this->contributionIsIncomplete && !$this->contributionIsPayLater) {
webform_submission_send_mail($this->node, $this->submission);
$this->submitIPNPayment();
}
// Send receipt
if (empty($this->submission->is_draft)
&& !empty($this->ent['contribution'][1]['id'])
&& !empty($this->contribution_page['is_email_receipt'])
&& (!$this->contributionIsIncomplete || $this->contributionIsPayLater)
) {
$this->sendReceipt();
}
}
/**
* Send receipt
*/
private function sendReceipt() {
// tax integration
if (!is_null($this->tax_rate)) {
$template = CRM_Core_Smarty::singleton();
$template->assign('dataArray', ["{$this->tax_rate}" => $this->tax_rate / 100]);
}
if ($this->contributionIsIncomplete) {
$template = CRM_Core_Smarty::singleton();
$template->assign('is_pay_later', 1);
}
$params = array_merge($this->contribution_page, ['id' => $this->ent['contribution'][1]['id']]);
$params['payment_processor_id'] = $this->data['contribution'][1]['contribution'][1]['payment_processor_id'];
unset($params['payment_processor']);
wf_civicrm_api('contribution', 'sendconfirmation', $params);
}
/**
* Formats submission data as expected by the schema
*/
private function formatSubmission() {
$data = $this->ent;
unset($data['contact']);
$record = [
'sid' => $this->submission->sid,
'contact_id' => '-',
'civicrm_data' => $data,
];
foreach ($this->ent['contact'] as $contact) {
$record['contact_id'] .= $contact['id'] . '-';
}
return $record;
}
/**
* Force Drupal to ignore errors for fields hidden by this module
*/
private function hiddenFieldValidation() {
$errors = form_get_errors();
foreach ((array) $errors as $key => $error) {
$pieces = wf_crm_explode_key(substr($key, strrpos($key, '][') + 2));
if ($pieces) {
list( , $c, $ent, $n, $table, $name) = $pieces;
if ($this->isFieldHiddenByExistingContactSettings($ent, $c, $table, $n, $name)) {
$this->unsetError($key);
}
elseif ($table == 'address' && !empty($this->crmValues["civicrm_{$c}_contact_{$n}_address_master_id"])) {
$master_id = $this->crmValues["civicrm_{$c}_contact_{$n}_address_master_id"];
// If widget is checkboxes, need to filter the array
if (!is_array($master_id) || array_filter($master_id)) {
$this->unsetError($key);
}
}
}
}
}
/**
* Recursive validation callback for webform page submission
*
* @param array $elements
* FAPI form array
*/
private function validateThisPage($elements) {
// Recurse through form elements.
foreach (element_children($elements) as $key) {
if (is_array($elements[$key]) && ($element = $elements[$key])) {
$this->validateThisPage($elements[$key]);
if (!empty($element['#civicrm_data_type'])
&& substr(wf_crm_aval($element, '#type', ''), 0, 4) === 'text'
&& isset($element['#value'])
&& $element['#value'] !== '') {
$dt = $element['#civicrm_data_type'];
// Validate state/prov abbreviation
if ($dt == 'state_province_abbr') {
$ckey = str_replace('state_province', 'country', $key);
if (!empty($this->crmValues[$ckey]) && is_numeric($this->crmValues[$ckey])) {
$country_id = $this->crmValues[$ckey];
}
else {
$country_id = wf_crm_get_civi_setting('defaultContactCountry', 1228);
}
$states = wf_crm_get_states($country_id);
if ($states && !array_key_exists(strtoupper($element['#value']), $states)) {
$countries = wf_crm_apivalues('address', 'getoptions', ['field' => 'country_id']);
form_error($element, t('Mismatch: "@state" is not a state/province of %country. Please enter a valid state/province abbreviation for %field.', ['@state' => $element['#value'], '%country' => $countries[$country_id], '%field' => $element['#title']]));
}
}
// Strings and files don't need any validation
elseif ($dt !== 'String' && $dt !== 'Memo' && $dt !== 'File'
&& CRM_Utils_Type::escape($element['#value'], $dt, FALSE) === NULL) {
// Allow data type names to be translated
switch ($dt) {
case 'Int':
$dt = t('an integer');
break;
case 'Float':
$dt = t('a number');
break;
case 'Link':
$dt = t('a web address starting with http://');
break;
case 'Money':
$dt = t('a currency value');
break;
}
form_error($element, t('Please enter @type for %field.', ['@type' => $dt, '%field' => $element['#title']]));
}
}
}
}
}
/**
* Validate event participants and add line items
*/
private function validateParticipants() {
// If we have no valid contacts on the form, don't bother continuing
if (!$this->existing_contacts) {
return;
}
$count = $this->data['participant_reg_type'] == 'all' ? count($this->existing_contacts) : 1;
// Collect selected events
foreach ($this->data['participant'] as $c => $par) {
if ($this->data['participant_reg_type'] == 'all') {
$contacts = $this->existing_contacts;
}
elseif (isset($this->existing_contacts[$c])) {
$contacts = [$this->existing_contacts[$c]];
}
else {
continue;
}
$participants = current(wf_crm_aval($this->data['contact'], "$c:contact", []));
$participantName = ($participants['first_name'] ?? '') . ' ' . ($participants['last_name'] ?? '');
if (!trim($participantName)) {
$participantName = $participants['webform_label'] ?? NULL;
if (!empty($this->existing_contacts[$c])) {
$participantName = wf_crm_apivalues('contact', 'get', $this->existing_contacts[$c], 'display_name')[0];
}
}
foreach (wf_crm_aval($par, 'participant', []) as $n => $p) {
foreach (array_filter(wf_crm_aval($p, 'event_id', [])) as $id_and_type) {
list($eid) = explode('-', $id_and_type);
if (is_numeric($eid)) {
$this->events[$eid]['ended'] = TRUE;
$this->events[$eid]['title'] = t('this event');
$this->events[$eid]['count'] = wf_crm_aval($this->events, "$eid:count", 0) + $count;
$this->line_items[] = [
'qty' => $count,
'entity_table' => 'civicrm_participant',
'event_id' => $eid,
'contact_ids' => $contacts,
'unit_price' => $p['fee_amount'] ?? 0,
'element' => "civicrm_{$c}_participant_{$n}_participant_{$id_and_type}",
'contact_label' => $participantName,
];
}
}
}
}
// Subtract events already registered for - this only works with known contacts
$cids = array_filter($this->existing_contacts);
if ($this->events && $cids) {
$status_types = wf_crm_apivalues('participant_status_type', 'get', ['is_counted' => 1, 'return' => 'id']);
$existing = wf_crm_apivalues('Participant', 'get', [
'return' => ['event_id', 'contact_id'],
'event_id' => ['IN' => array_keys($this->events)],
'status_id' => ['IN' => array_keys($status_types)],
'contact_id' => ['IN' => $cids],
'is_test' => 0,
]);
foreach ($existing as $participant) {
if (isset($this->events[$participant['event_id']])) {
if (!(--$this->events[$participant['event_id']]['count'])) {
unset($this->events[$participant['event_id']]);
}
}
foreach ($this->line_items as $k => &$item) {
if ($participant['event_id'] == $item['event_id'] && in_array($participant['contact_id'], $item['contact_ids'])) {
unset($this->line_items[$k]['contact_ids'][array_search($participant['contact_id'], $item['contact_ids'])]);
if (!(--$item['qty'])) {
unset($this->line_items[$k]);
}
}
}
}
}
$this->loadEvents();
// Add event info to line items
$format = wf_crm_aval($this->data['reg_options'], 'title_display', 'title');
foreach ($this->line_items as &$item) {
$label = empty($item['contact_label']) ? '' : "{$item['contact_label']} - ";
$item['label'] = $label . wf_crm_format_event($this->events[$item['event_id']], $format);
$item['financial_type_id'] = wf_crm_aval($this->events[$item['event_id']], 'financial_type_id', 'Event Fee');
}
// Form Validation
if (!empty($this->data['reg_options']['validate'])) {
foreach ($this->events as $eid => $event) {
if ($event['ended']) {
form_set_error($eid, t('Sorry, you can no longer register for %event.', ['%event' => $event['title']]));
}
elseif (!empty($event['max_participants']) && $event['count'] > $event['available_places']) {
if (!empty($event['is_full'])) {
form_set_error($eid, '<em>' . $event['title'] . '</em>: ' . $event['event_full_text']);
}
else {
form_set_error($eid, format_plural($event['available_places'],
'Sorry, you tried to register !count people for %event but there is only 1 space remaining.',
'Sorry, you tried to register !count people for %event but there are only @count spaces remaining.',
['%event' => $event['title'], '!count' => $event['count']]));
}
}
}
}
}
/**
* Load entire webform submission during validation, including contact ids and $this->data
* Used when validation for one page needs access to submitted values from other pages
*/
private function loadMultiPageData() {
if (!$this->multiPageDataLoaded) {
$this->multiPageDataLoaded = TRUE;
if (!empty($this->form_state['storage']['submitted'])
&& wf_crm_aval($this->form_state, 'storage:page_num', 1) > 1)
{
$this->rawValues += $this->form_state['storage']['submitted'];
$this->crmValues = wf_crm_enabled_fields($this->node, $this->rawValues);
}
// Check how many valid contacts we have
foreach ($this->data['contact'] as $c => $contact) {
// Check if we have a contact_id
$fid = "civicrm_{$c}_contact_1_contact_existing";
if ($this->verifyExistingContact(wf_crm_aval($this->crmValues, $fid), $fid)) {
$this->existing_contacts[$c] = $this->crmValues[$fid];
}
// Or else see if enough info was entered to create a contact - use 0 as a placeholder for unknown cid
elseif (wf_crm_name_field_exists($this->crmValues, $c, $contact['contact'][1]['contact_type'], $this->node)) {
$this->existing_contacts[$c] = 0;
}
}
// Fill data array with submitted form values
$this->fillDataFromSubmission();
}
}
/**
* If this is an update op, set param for drupal_write_record()
*/
private function setUpdateParam() {
if (!empty($this->submission->sid)) {
$submitted = [$this->submission->sid => new stdClass()];
webform_civicrm_webform_submission_load($submitted);
if (isset($submitted[$this->submission->sid]->civicrm)) {
$this->update = 'sid';
}
}
}
/**
* Fetch contact ids from "existing contact" fields
*/
private function getExistingContactIds() {
foreach ($this->enabled as $field_key => $fid) {
if (substr($field_key, -8) == 'existing') {
list(, $c, ) = explode('_', $field_key, 3);
$cid = wf_crm_aval($this->submissionValue($fid), 0);
$this->ent['contact'][$c]['id'] = $this->verifyExistingContact($cid, $field_key);
if ($this->ent['contact'][$c]['id']) {
$this->existing_contacts[$c] = $cid;
}
}
}
}
/**
* Ensure we have a valid contact id in a contact ref field
* @param $cid
* @param $fid
* @return int
*/
private function verifyExistingContact($cid, $fid) {
if (wf_crm_is_positive($cid) && !empty($this->enabled[$fid])) {
module_load_include('inc', 'webform_civicrm', 'includes/contact_component');
$component = $this->getComponent($fid);
$filters = wf_crm_search_filters($this->node, $component);
// Verify access to this contact
if (wf_crm_contact_access($component, $filters, $cid) !== FALSE) {
return $cid;
}
}
return 0;
}
/**
* Check if at least one required field was filled for a contact
* @param array $contact
* @return bool
*/
private function isContactEmpty($contact) {
$contact_type = $contact['contact'][1]['contact_type'];
foreach (wf_crm_required_contact_fields($contact_type) as $f) {
if (!empty($contact[$f['table']][1][$f['name']])) {
return FALSE;
}
}
return TRUE;
}
/**
* Search for an existing contact using configured deupe rule
* @param array $contact
* @return int
*/
private function findDuplicateContact($contact) {
// This is either a default type (Unsupervised or Supervised) or the id of a specific rule
$rule = wf_crm_aval($contact, 'matching_rule', 'Unsupervised', TRUE);
if ($rule) {
$contact['contact'][1]['contact_type'] = ucfirst($contact['contact'][1]['contact_type']);
$params = [
'check_permission' => FALSE,
'sequential' => TRUE,
'rule_type' => is_numeric($rule) ? NULL : $rule,
'dedupe_rule_id' => is_numeric($rule) ? $rule : NULL,
'match' => [],
];
// If sharing an address, use the master
if (!empty($contact['address'][1]['master_id'])) {
$m = $contact['address'][1]['master_id'];
// If master address is exposed to the form, use it
if (!empty($this->data['contact'][$m]['address'][1])) {
$contact['address'][1] = $this->data['contact']['address'][1];
}
// Else look up the master contact's address
elseif (!empty($this->existing_contacts[$m])) {
$masters = wf_crm_apivalues('address', 'get', [
'contact_id' => $this->ent['contact'][$m]['id'],
'sort' => 'is_primary DESC',
'limit' => 1,
]);
if (!empty($masters)) {
$contact['address'][1] = reset($masters);
}
}
}
// Translate state abbr to id (skip if using $masters address which would have returned id not abbr from the api)
if (empty($masters) && !empty($contact['address'][1]['state_province_id'])) {
$contact['address'][1]['state_province_id'] = wf_crm_state_abbr($contact['address'][1]['state_province_id'], 'id', $contact['address'][1]['country_id'] ?? NULL);
}
foreach ($contact as $table => $fields) {
if (is_array($fields) && !empty($fields[1])) {
$params['match'] += $fields[1];
}
}
// Pass custom params to deduper
if ($params['match']) {
$dupes = wf_crm_apivalues('Contact', 'duplicatecheck', $params);
}
}
return $dupes[0]['id'] ?? 0;
}
/**
* Create a new contact
* @param array $contact
* @return int
*/
private function createContact($contact) {
$params = $contact['contact'][1];
// CiviCRM API is too picky about this, imho
$params['contact_type'] = ucfirst($params['contact_type']);
unset($params['contact_id'], $params['id']);
if (!isset($params['source'])) {
$params['source'] = $this->settings['new_contact_source'];
}
// If creating individual with no first/last name,
// set display name and sort_name
if ($params['contact_type'] == 'Individual' && empty($params['first_name']) && empty($params['last_name'])) {
$params['display_name'] = $params['sort_name'] = empty($params['nick_name']) ? $contact['email'][1]['email'] : $params['nick_name'];
}
$result = wf_civicrm_api('contact', 'create', $params);
return wf_crm_aval($result, 'id', 0);
}
/**
* Update a contact
* @param array $contact
* @param int $c
*/
private function updateContact($contact, $c) {
$params = $contact['contact'][1];
unset($params['contact_type'], $params['contact_id']);
// Fetch data from existing multivalued fields
$fetch = $multi = [];
foreach ($this->all_fields as $fid => $field) {
if (!empty($field['extra']['multiple']) && substr($fid, 0, 7) == 'contact') {
list(, $name) = explode('_', $fid, 2);
if ($name != 'privacy' && isset($params[$name])) {
$fetch["return.$name"] = 1;
$multi[] = $name;
}
}
}
// Merge data from existing multivalued fields
if ($multi) {
$existing = wf_civicrm_api('contact', 'get', ['id' => $this->ent['contact'][$c]['id']] + $fetch);
$existing = wf_crm_aval($existing, 'values:' . $this->ent['contact'][$c]['id'], []);
foreach ($multi as $name) {
$exist = array_filter(drupal_map_assoc((array) wf_crm_aval($existing, $name, [])));
// Only known contacts are allowed to empty a field
if (!empty($this->existing_contacts[$c])) {
foreach ($this->getExposedOptions("civicrm_{$c}_contact_1_contact_$name") as $k => $v) {
unset($exist[$k]);
}
}
$params[$name] = array_unique(array_merge($params[$name], $exist));
}
}
$params['id'] = $this->ent['contact'][$c]['id'];
wf_civicrm_api('contact', 'create', $params);
}
/**
* Save current employer for a contact
* @param array $contact
* @param int $cid
*/
function saveCurrentEmployer($contact, $cid) {
if ($contact['contact'][1]['contact_type'] == 'individual' && !empty($contact['contact'][1]['employer_id'])) {
wf_civicrm_api('contact', 'create', [
'id' => $cid,
'employer_id' => $contact['contact'][1]['employer_id'],
]);
}
}
/**
* Fill values for hidden ID & CS fields
* @param int $c
* @param int $cid
*/
private function fillHiddenContactFields($cid, $c) {
$fid = 'civicrm_' . $c . '_contact_1_contact_';
if (!empty($this->enabled[$fid . 'contact_id'])) {
$this->submissionValue($this->enabled[$fid . 'contact_id'], $cid);
}
if (!empty($this->enabled[$fid . 'user_id'])) {
$user_id = wf_crm_user_cid($cid, 'contact');
$user_id = $user_id ? $user_id : '';
$this->submissionValue($this->enabled[$fid . 'user_id'], $user_id);
}
if (!empty($this->enabled[$fid . 'existing'])) {
$this->submissionValue($this->enabled[$fid . 'existing'], $cid);
}
if (!empty($this->enabled[$fid . 'external_identifier']) && !empty($this->existing_contacts[$c])) {
$exid = wf_civicrm_api('contact', 'get', ['contact_id' => $cid, 'return.external_identifier' => 1]);
$this->submissionValue($this->enabled[$fid . 'external_identifier'], wf_crm_aval($exid, "values:$cid:external_identifier"));
}
if (!empty($this->enabled[$fid . 'cs'])) {
$cs = $this->submissionValue($this->enabled[$fid . 'cs']);
$life = !empty($cs[0]) ? intval(24 * $cs[0]) : 'inf';
$cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($cid, NULL, $life);
$this->submissionValue($this->enabled[$fid . 'cs'], $cs);
}
}
/**
* Save location data for a contact
* @param array $contact
* @param int $cid
* @param int $c
*/
private function saveContactLocation($contact, $cid, $c) {
// Check which location_type_id is to be set as is_primary=1;
$is_primary_address_location_type = wf_crm_aval($contact, 'address:1:location_type_id');
$is_primary_email_location_type = wf_crm_aval($contact, 'email:1:location_type_id');
// Fix address fields.
if (!empty($contact['address'])) {
foreach ($contact['address'] as &$address) {
// Translate state/prov abbr to id
if (!empty($address['state_province_id'])) {
$default_country = wf_crm_get_civi_setting('defaultContactCountry', 1228);
if (!($address['state_province_id'] = wf_crm_state_abbr($address['state_province_id'], 'id', wf_crm_aval($address, 'country_id', $default_country)))) {
$address['state_province_id'] = '';
}
}
// Substitute county stub ('-' is a hack to get around required field when there are no available counties)
if (isset($address['county_id']) && $address['county_id'] === '-') {
$address['county_id'] = '';
}
}
}
foreach (wf_crm_location_fields() as $location) {
if (!empty($contact[$location])) {
$existing = [];
$params = ['contact_id' => $cid];
if ($location != 'website') {
$params['options'] = ['sort' => 'is_primary DESC'];
}
$result = wf_civicrm_api($location, 'get', $params);
if (!empty($result['values'])) {
$contact[$location] = self::reorderLocationValues($contact[$location], $result['values'], $location);
// start array index at 1
$existing = array_merge([[]], $result['values']);
}
foreach ($contact[$location] as $i => $params) {
// Update drupal email address
if ($location == 'email' && !empty($params['email']) && $i == 1) {
$uid = wf_crm_user_cid($cid, 'contact');
if ($uid) {
$user = user_load($uid);
if ($params['email'] != $user->mail) {
// Verify this email is unique before saving it to user
$args = [':mail' => $params['email']];
if (!(db_query("SELECT count(uid) FROM {users} WHERE mail = :mail", $args)->fetchField())) {
user_save($user, ['mail' => $params['email']]);
}
}
}
}
// Check if anything was changed, else skip the update
if (!empty($existing[$i])) {
$same = TRUE;
foreach ($params as $param => $val) {
if ($val != (string) wf_crm_aval($existing[$i], $param, '')) {
$same = FALSE;
}
}
if ($same) {
continue;
}
}
if ($location == 'address') {
// Store shared addresses for later since we haven't necessarily processed
// the contact this address is shared with yet.
if (!empty($params['master_id'])) {
$this->shared_address[$cid][$i] = [
'id' => wf_crm_aval($existing, "$i:id"),
'mc' => $params['master_id'],
'loc' => $params['location_type_id'],
'pri' => $params['location_type_id'] == $is_primary_address_location_type,
];
continue;
}
// Reset calculated values when updating an address
$params['master_id'] = $params['geo_code_1'] = $params['geo_code_2'] = 'null';
}
$params['contact_id'] = $cid;
if (!empty($existing[$i])) {
$params['id'] = $existing[$i]['id'];
}
if ($this->locationIsEmpty($location, $params)) {
// Delete this location if nothing was entered and this is a known contact
if (!empty($this->existing_contacts[$c]) && !empty($params['id'])) {
wf_civicrm_api($location, 'delete', $params);
}
continue;
}
if ($location != 'website') {
if (empty($params['location_type_id'])) {
$params['location_type_id'] = wf_crm_aval($existing, "$i:location_type_id", 1);
}
$params['is_primary'] = $i == 1 ? 1 : 0;
// Override that just in cases we know
if ($location == 'address' && $params['location_type_id'] == $is_primary_address_location_type) {
$params['is_primary'] = 1;
}
if ($location == 'email' && $params['location_type_id'] == $is_primary_email_location_type) {
$params['is_primary'] = 1;
}
}
wf_civicrm_api($location, 'create', $params);
}
}
}
}
/**
* Save groups and tags for a contact
* @param array $contact
* @param int $cid
* @param int $c
*/
private function saveGroupsAndTags($contact, $cid, $c) {
// Process groups & tags
foreach ($this->all_fields as $fid => $field) {
list($set, $type) = explode('_', $fid, 2);
if ($set == 'other') {
$field_name = 'civicrm_' . $c . '_contact_1_' . $fid;
if (!empty($contact['other'][1][$type]) || isset($this->enabled[$field_name])) {
$add = wf_crm_aval($contact, "other:1:$type", []);
$remove = empty($this->existing_contacts[$c]) ? [] : $this->getExposedOptions($field_name, $add);
$this->addOrRemoveMultivaluedData($field['table'], 'contact', $cid, $add, $remove);
}
}
}
}
/**
* Handle adding/removing multivalued data for a contact/activity/etc.
* Currently used only for groups and tags, but written with expansion in mind.
*
* @param $data_type
* 'group' or 'tag'
* @param $entity_type
* Parent entity: 'contact' etc.
* @param $id
* Entity id
* @param $add
* Groups/tags to add
* @param array $remove
* Groups/tags to remove
*/
private function addOrRemoveMultivaluedData($data_type, $entity_type, $id, $add, $remove = []) {
$confirmations_sent = $existing = $params = [];
$add = drupal_map_assoc($add);
static $mailing_lists = [];
switch ($data_type) {
case 'group':
$api = 'group_contact';
$params['method'] = 'Webform';
break;
case 'tag':
$api = 'EntityTag';
break;
default:
$api = $data_type;
}
if (!empty($add) || !empty($remove)) {
// Retrieve current records for this entity
if ($api == 'EntityTag') {
$params['entity_id'] = $id;
$params['entity_table'] = 'civicrm_' . $entity_type;
}
elseif ($api == 'group_contact' && $entity_type == 'contact') {
$params['contact_id'] = $id;
}
else {
$params['entity_id'] = $id;
$params['entity_type'] = 'civicrm_' . $entity_type;
}
$fetch = wf_civicrm_api($api, 'get', $params);
foreach (wf_crm_aval($fetch, 'values', []) as $i) {
$existing[] = $i[$data_type . '_id'];
unset($add[$i[$data_type . '_id']]);
}
foreach ($remove as $i => $name) {
if (!in_array($i, $existing)) {
unset($remove[$i]);
}
}
}
if (!empty($add)) {
// Prepare for sending subscription confirmations
if ($data_type == 'group' && !empty($this->settings['confirm_subscription'])) {
// Retrieve this contact's primary email address and perform error-checking
$result = wf_civicrm_api('email', 'get', ['contact_id' => $id, 'options' => ['sort' => 'is_primary DESC']]);
if (!empty($result['values'])) {
foreach ($result['values'] as $value) {
if (($value['is_primary'] || empty($email)) && strpos($value['email'], '@')) {
$email = $value['email'];
}
}
$mailer_params = [
'contact_id' => $id,
'email' => $email,
];
if (empty($mailing_lists)) {
$mailing_lists = wf_crm_apivalues('group', 'get', ['visibility' => 'Public Pages', 'group_type' => 2], 'title');
}
}
}
foreach ($add as $a) {
$params[$data_type . '_id'] = $mailer_params['group_id'] = $a;
if ($data_type == 'group' && isset($mailing_lists[$a]) && !empty($email)) {
$result = wf_civicrm_api('mailing_event_subscribe', 'create', $mailer_params);
if (empty($result['is_error'])) {
$confirmations_sent[] = check_plain($mailing_lists[$a]);
}
else {
wf_civicrm_api($api, 'create', $params);
}
}
else {
wf_civicrm_api($api, 'create', $params);
}
}
if ($confirmations_sent) {
drupal_set_message(t('A message has been sent to %email to confirm subscription to !group.', ['%email' => $email, '!group' => '<em>' . implode('</em> ' . t('and') . ' <em>', $confirmations_sent) . '</em>']));
}
}
// Remove data from entity
foreach ($remove as $a => $name) {
$params[$data_type . '_id'] = $a;
wf_civicrm_api($api, 'delete', $params);
}
if (!empty($remove) && $data_type == 'group') {
$display_name = wf_civicrm_api('contact', 'get', ['contact_id' => $id, 'return.display_name' => 1]);
$display_name = wf_crm_aval($display_name, "values:$id:display_name", t('Contact'));
drupal_set_message(t('%contact has been removed from !group.', ['%contact' => $display_name, '!group' => '<em>' . implode('</em> ' . t('and') . ' <em>', $remove) . '</em>']));
}
}
/**
* Add/update relationship for a pair of contacts
*
* @param $params
* Params array for relationship api
* @param $cid1
* Contact id
* @param $cid2
* Contact id
*/
private function processRelationship($params, $cid1, $cid2) {
if (!empty($params['relationship_type_id']) && $cid2 && $cid1 != $cid2) {
list($type, $side) = explode('_', $params['relationship_type_id']);
$existing = $this->getRelationship([$params['relationship_type_id']], $cid1, $cid2);
$perm = wf_crm_aval($params, 'relationship_permission');
// Swap contacts if this is an inverse relationship
if ($side == 'b' || ($existing && $existing['contact_id_a'] != $cid1)) {
list($cid1, $cid2) = [$cid2, $cid1];
if ($perm == 1 || $perm == 2) {
$perm = $perm == 1 ? 2 : 1;
}
}
//initialise start_date for create action.
if (empty($existing) && !array_key_exists('start_date', $params)) {
$params['start_date'] = 'now';
}
$params += $existing;
$params['contact_id_a'] = $cid1;
$params['contact_id_b'] = $cid2;
$params['relationship_type_id'] = $type;
if ($perm) {
$params['is_permission_a_b'] = $params['is_permission_b_a'] = $perm == 3 ? 1 : 0;
if ($perm == 1 || $perm == 2) {
$params['is_permission_' . ($perm == 1 ? 'a_b' : 'b_a')] = 1;
}
}