-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathContact.php
1400 lines (1222 loc) · 46.6 KB
/
Contact.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
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
/**
* This class generates form components generic to all the contact types.
*
* It delegates the work to lower level subclasses and integrates the changes
* back in. It also uses a lot of functionality with the CRM API's, so any change
* made here could potentially affect the API etc. Be careful, be aware, use unit tests.
*
*/
class CRM_Contact_Form_Contact extends CRM_Core_Form {
/**
* The contact type of the form.
*
* @var string
*/
public $_contactType;
/**
* The contact type of the form.
*
* @var string
*/
public $_contactSubType;
/**
* The contact id, used when editing the form
*
* @var int
*/
public $_contactId;
/**
* The default group id passed in via the url.
*
* @var int
*/
public $_gid;
/**
* The default tag id passed in via the url.
*
* @var int
*/
public $_tid;
/**
* Name of de-dupe button
*
* @var string
*/
protected $_dedupeButtonName;
/**
* Name of optional save duplicate button.
*
* @var string
*/
protected $_duplicateButtonName;
protected $_editOptions = [];
protected $_oldSubtypes = [];
public $_blocks;
public $_values = [];
public $_action;
public $_customValueCount;
/**
* The array of greetings with option group and filed names.
*
* @var array
*/
public $_greetings;
/**
* Do we want to parse street address.
* @var bool
*/
public $_parseStreetAddress;
/**
* Check contact has a subtype or not.
* @var bool
*/
public $_isContactSubType;
/**
* Lets keep a cache of all the values that we retrieved.
* THis is an attempt to avoid the number of update statements
* during the write phase
* @var array
*/
public $_preEditValues;
/**
* Explicitly declare the entity api name.
*/
public function getDefaultEntity() {
return 'Contact';
}
/**
* Explicitly declare the form context.
*/
public function getDefaultContext() {
return 'create';
}
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
$this->_dedupeButtonName = $this->getButtonName('refresh', 'dedupe');
$this->_duplicateButtonName = $this->getButtonName('upload', 'duplicate');
CRM_Core_Resources::singleton()
->addStyleFile('civicrm', 'css/contactSummary.css', 2, 'html-header');
$session = CRM_Core_Session::singleton();
if ($this->_action == CRM_Core_Action::ADD) {
// check for add contacts permissions
if (!CRM_Core_Permission::check('add contacts')) {
CRM_Utils_System::permissionDenied();
CRM_Utils_System::civiExit();
}
$this->_contactType = CRM_Utils_Request::retrieve('ct', 'String',
$this, TRUE, NULL, 'REQUEST'
);
if (!in_array($this->_contactType,
['Individual', 'Household', 'Organization']
)
) {
CRM_Core_Error::statusBounce(ts('Could not get a contact id and/or contact type'));
}
$this->_isContactSubType = FALSE;
if ($this->_contactSubType = CRM_Utils_Request::retrieve('cst', 'String', $this)) {
$this->_isContactSubType = TRUE;
}
if (
$this->_contactSubType &&
!(CRM_Contact_BAO_ContactType::isExtendsContactType($this->_contactSubType, $this->_contactType, TRUE))
) {
CRM_Core_Error::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", [1 => $this->_contactType]));
}
$this->_gid = CRM_Utils_Request::retrieve('gid', 'Integer',
CRM_Core_DAO::$_nullObject,
FALSE, NULL, 'GET'
);
$this->_tid = CRM_Utils_Request::retrieve('tid', 'Integer',
CRM_Core_DAO::$_nullObject,
FALSE, NULL, 'GET'
);
$typeLabel = CRM_Contact_BAO_ContactType::contactTypePairs(TRUE, $this->_contactSubType ?
$this->_contactSubType : $this->_contactType
);
$typeLabel = implode(' / ', $typeLabel);
$this->setTitle(ts('New %1', [1 => $typeLabel]));
$session->pushUserContext(CRM_Utils_System::url('civicrm/dashboard', 'reset=1'));
$this->_contactId = NULL;
}
else {
//update mode
if (!$this->_contactId) {
$this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
}
if ($this->_contactId) {
$defaults = [];
$params = ['id' => $this->_contactId];
$returnProperities = ['id', 'contact_type', 'contact_sub_type', 'modified_date', 'is_deceased'];
CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact', $params, $defaults, $returnProperities);
if (empty($defaults['id'])) {
CRM_Core_Error::statusBounce(ts('A Contact with that ID does not exist: %1', [1 => $this->_contactId]));
}
$this->_contactType = $defaults['contact_type'] ?? NULL;
$this->_contactSubType = $defaults['contact_sub_type'] ?? NULL;
// check for permissions
$session = CRM_Core_Session::singleton();
if (!CRM_Contact_BAO_Contact_Permission::allow($this->_contactId, CRM_Core_Permission::EDIT)) {
CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
}
$displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId);
if ($defaults['is_deceased']) {
$displayName .= ' <span class="crm-contact-deceased">(' . ts('deceased') . ')</span>';
}
$displayName = ts('Edit %1', [1 => $displayName]);
// Check if this is default domain contact CRM-10482
if (CRM_Contact_BAO_Contact::checkDomainContact($this->_contactId)) {
$displayName .= ' (' . ts('default organization') . ')';
}
// omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
$this->setTitle($displayName);
$context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
$urlParams = 'reset=1&cid=' . $this->_contactId;
if ($context) {
$urlParams .= "&context=$context";
}
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&key=$qfKey";
}
$session->pushUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams));
$values = $this->get('values');
// get contact values.
if (!empty($values)) {
$this->_values = $values;
}
else {
$params = [
'id' => $this->_contactId,
'contact_id' => $this->_contactId,
'noRelationships' => TRUE,
'noNotes' => TRUE,
'noGroups' => TRUE,
];
$contact = CRM_Contact_BAO_Contact::retrieve($params, $this->_values, TRUE);
$this->set('values', $this->_values);
}
}
else {
CRM_Core_Error::statusBounce(ts('Could not get a contact_id and/or contact_type'));
}
}
// parse street address, CRM-5450
$this->_parseStreetAddress = $this->get('parseStreetAddress');
if (!isset($this->_parseStreetAddress)) {
$addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'address_options'
);
$this->_parseStreetAddress = FALSE;
if (!empty($addressOptions['street_address']) && !empty($addressOptions['street_address_parsing'])) {
$this->_parseStreetAddress = TRUE;
}
$this->set('parseStreetAddress', $this->_parseStreetAddress);
}
$this->assign('parseStreetAddress', $this->_parseStreetAddress);
$this->_editOptions = $this->get('contactEditOptions');
if (CRM_Utils_System::isNull($this->_editOptions)) {
$this->_editOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_edit_options', TRUE, NULL,
FALSE, 'name', TRUE, 'AND v.filter = 0'
);
$this->set('contactEditOptions', $this->_editOptions);
}
// build demographics only for Individual contact type
if ($this->_contactType != 'Individual' &&
array_key_exists('Demographics', $this->_editOptions)
) {
unset($this->_editOptions['Demographics']);
}
// in update mode don't show notes
if ($this->_contactId && array_key_exists('Notes', $this->_editOptions)) {
unset($this->_editOptions['Notes']);
}
$this->assign('editOptions', $this->_editOptions);
$this->assign('contactType', $this->_contactType);
$this->assign('contactSubType', $this->_contactSubType);
// get the location blocks.
$this->_blocks = $this->get('blocks');
if (CRM_Utils_System::isNull($this->_blocks)) {
$this->_blocks = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_edit_options', TRUE, NULL,
FALSE, 'name', TRUE, 'AND v.filter = 1'
);
$this->set('blocks', $this->_blocks);
}
$this->assign('blocks', $this->_blocks);
// this is needed for custom data.
$this->assign('entityID', $this->_contactId);
// also keep the convention.
$this->assign('contactId', $this->_contactId);
// location blocks.
CRM_Contact_Form_Location::preProcess($this);
// retain the multiple count custom fields value
if (!empty($_POST['hidden_custom'])) {
$customGroupCount = $_POST['hidden_custom_group_count'] ?? NULL;
if ($contactSubType = CRM_Utils_Array::value('contact_sub_type', $_POST)) {
$paramSubType = implode(',', $contactSubType);
}
$this->_getCachedTree = FALSE;
unset($customGroupCount[0]);
foreach ($customGroupCount as $groupID => $groupCount) {
if ($groupCount > 1) {
$this->set('groupID', $groupID);
//loop the group
for ($i = 0; $i <= $groupCount; $i++) {
CRM_Custom_Form_CustomData::preProcess($this, NULL, $contactSubType,
$i, $this->_contactType, $this->_contactId
);
CRM_Contact_Form_Edit_CustomData::buildQuickForm($this);
}
}
}
//reset all the ajax stuff, for normal processing
if (isset($this->_groupTree)) {
$this->_groupTree = NULL;
}
$this->set('groupID', NULL);
$this->_getCachedTree = TRUE;
}
// execute preProcess dynamically by js else execute normal preProcess
if (array_key_exists('CustomData', $this->_editOptions)) {
//assign a parameter to pass for sub type multivalue
//custom field to load
if ($this->_contactSubType || isset($paramSubType)) {
$paramSubType = (isset($paramSubType)) ? $paramSubType :
str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ',', trim($this->_contactSubType, CRM_Core_DAO::VALUE_SEPARATOR));
$this->assign('paramSubType', $paramSubType);
}
if (CRM_Utils_Request::retrieve('type', 'String')) {
CRM_Contact_Form_Edit_CustomData::preProcess($this);
}
else {
$contactSubType = $this->_contactSubType;
// need contact sub type to build related grouptree array during post process
if (!empty($_POST['qfKey'])) {
$contactSubType = $_POST['contact_sub_type'] ?? NULL;
}
//only custom data has preprocess hence directly call it
CRM_Custom_Form_CustomData::preProcess($this, NULL, $contactSubType,
1, $this->_contactType, $this->_contactId
);
$this->assign('customValueCount', $this->_customValueCount);
}
}
}
/**
* Set default values for the form.
*
* Note that in edit/view mode the default values are retrieved from the database
*/
public function setDefaultValues() {
$defaults = $this->_values;
if ($this->_action & CRM_Core_Action::ADD) {
if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
// set group and tag defaults if any
if ($this->_gid) {
$defaults['group'][] = $this->_gid;
}
if ($this->_tid) {
$defaults['tag'][$this->_tid] = 1;
}
}
if ($this->_contactSubType) {
$defaults['contact_sub_type'] = $this->_contactSubType;
}
}
else {
foreach ($defaults['email'] as $dontCare => & $val) {
if (isset($val['signature_text'])) {
$val['signature_text_hidden'] = $val['signature_text'];
}
if (isset($val['signature_html'])) {
$val['signature_html_hidden'] = $val['signature_html'];
}
}
if (!empty($defaults['contact_sub_type'])) {
$defaults['contact_sub_type'] = $this->_oldSubtypes;
}
}
// set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
foreach ($this->_editOptions as $name => $label) {
if (!in_array($name, ['Address', 'Notes'])) {
$className = 'CRM_Contact_Form_Edit_' . $name;
$className::setDefaultValues($this, $defaults);
}
}
//set address block defaults
CRM_Contact_Form_Edit_Address::setDefaultValues($defaults, $this);
if (!empty($defaults['image_URL'])) {
$this->assign("imageURL", CRM_Utils_File::getImageURL($defaults['image_URL']));
}
//set location type and country to default for each block
$this->blockSetDefaults($defaults);
$this->_preEditValues = $defaults;
return $defaults;
}
/**
* Do the set default related to location type id, primary location, default country.
*
* @param array $defaults
*/
public function blockSetDefaults(&$defaults) {
$locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int');
sort($locationTypeKeys);
// get the default location type
$locationType = CRM_Core_BAO_LocationType::getDefault();
// unset primary location type
$primaryLocationTypeIdKey = CRM_Utils_Array::key($locationType->id, $locationTypeKeys);
unset($locationTypeKeys[$primaryLocationTypeIdKey]);
// reset the array sequence
$locationTypeKeys = array_values($locationTypeKeys);
// get default phone and im provider id.
$defPhoneTypeId = key(CRM_Core_OptionGroup::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1'));
$defIMProviderId = key(CRM_Core_OptionGroup::values('instant_messenger_service',
FALSE, FALSE, FALSE, ' AND is_default = 1'
));
$defWebsiteTypeId = key(CRM_Core_OptionGroup::values('website_type',
FALSE, FALSE, FALSE, ' AND is_default = 1'
));
$allBlocks = $this->_blocks;
if (array_key_exists('Address', $this->_editOptions)) {
$allBlocks['Address'] = $this->_editOptions['Address'];
}
$config = CRM_Core_Config::singleton();
foreach ($allBlocks as $blockName => $label) {
$name = strtolower($blockName);
$hasPrimary = $updateMode = FALSE;
// user is in update mode.
if (array_key_exists($name, $defaults) &&
!CRM_Utils_System::isNull($defaults[$name])
) {
$updateMode = TRUE;
}
for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++) {
// make we require one primary block, CRM-5505
if ($updateMode) {
if (!$hasPrimary) {
$hasPrimary = CRM_Utils_Array::value(
'is_primary',
CRM_Utils_Array::value($instance, $defaults[$name])
);
}
continue;
}
//set location to primary for first one.
if ($instance == 1) {
$hasPrimary = TRUE;
$defaults[$name][$instance]['is_primary'] = TRUE;
$defaults[$name][$instance]['location_type_id'] = $locationType->id;
}
else {
$locTypeId = $locationTypeKeys[$instance - 1] ?? $locationType->id;
$defaults[$name][$instance]['location_type_id'] = $locTypeId;
}
//set default country
if ($name == 'address' && $config->defaultContactCountry) {
$defaults[$name][$instance]['country_id'] = $config->defaultContactCountry;
}
//set default state/province
if ($name == 'address' && $config->defaultContactStateProvince) {
$defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince;
}
//set default phone type.
if ($name == 'phone' && $defPhoneTypeId) {
$defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
}
//set default website type.
if ($name == 'website' && $defWebsiteTypeId) {
$defaults[$name][$instance]['website_type_id'] = $defWebsiteTypeId;
}
//set default im provider.
if ($name == 'im' && $defIMProviderId) {
$defaults[$name][$instance]['provider_id'] = $defIMProviderId;
}
}
if (!$hasPrimary) {
$defaults[$name][1]['is_primary'] = TRUE;
}
}
}
/**
* add the rules (mainly global rules) for form.
* All local rules are added near the element
*
* @see valid_date
*/
public function addRules() {
// skip adding formRules when custom data is build
if ($this->_addBlockName || ($this->_action & CRM_Core_Action::DELETE)) {
return;
}
$this->addFormRule(['CRM_Contact_Form_Edit_' . $this->_contactType, 'formRule'], $this->_contactId);
// Call Locking check if editing existing contact
if ($this->_contactId) {
$this->addFormRule(['CRM_Contact_Form_Edit_Lock', 'formRule'], $this->_contactId);
}
if (array_key_exists('Address', $this->_editOptions)) {
$this->addFormRule(['CRM_Contact_Form_Edit_Address', 'formRule'], $this);
}
if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
$this->addFormRule(['CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'], $this);
}
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
* @param array $errors
* List of errors to be posted back to the form.
* @param int $contactId
* Contact id if doing update.
* @param string $contactType
*
* @return bool
* email/openId
*/
public static function formRule($fields, &$errors, $contactId, $contactType) {
$config = CRM_Core_Config::singleton();
// validations.
//1. for each block only single value can be marked as is_primary = true.
//2. location type id should be present if block data present.
//3. check open id across db and other each block for duplicate.
//4. at least one location should be primary.
//5. also get primaryID from email or open id block.
// take the location blocks.
$blocks = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_edit_options', TRUE, NULL,
FALSE, 'name', TRUE, 'AND v.filter = 1'
);
$otherEditOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_edit_options', TRUE, NULL,
FALSE, 'name', TRUE, 'AND v.filter = 0'
);
//get address block inside.
if (array_key_exists('Address', $otherEditOptions)) {
$blocks['Address'] = $otherEditOptions['Address'];
}
$website_types = [];
$openIds = [];
$primaryID = FALSE;
foreach ($blocks as $name => $label) {
$hasData = $hasPrimary = [];
$name = strtolower($name);
if (!empty($fields[$name]) && is_array($fields[$name])) {
foreach ($fields[$name] as $instance => $blockValues) {
$dataExists = self::blockDataExists($blockValues);
if (!$dataExists && $name == 'address') {
$dataExists = $fields['address'][$instance]['use_shared_address'] ?? NULL;
}
if ($dataExists) {
if ($name == 'website') {
if (!empty($blockValues['website_type_id'])) {
if (empty($website_types[$blockValues['website_type_id']])) {
$website_types[$blockValues['website_type_id']] = $blockValues['website_type_id'];
}
else {
$errors["{$name}[1][website_type_id]"] = ts('Contacts may only have one website of each type at most.');
}
}
// skip remaining checks for website
continue;
}
$hasData[] = $instance;
if (!empty($blockValues['is_primary'])) {
$hasPrimary[] = $instance;
if (!$primaryID &&
in_array($name, [
'email',
'openid',
]) && !empty($blockValues[$name])
) {
$primaryID = $blockValues[$name];
}
}
if (empty($blockValues['location_type_id'])) {
$errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', [1 => $label]);
}
}
if ($name == 'openid' && !empty($blockValues[$name])) {
$oid = new CRM_Core_DAO_OpenID();
$oid->openid = $openIds[$instance] = $blockValues[$name];
$cid = $contactId ?? 0;
if ($oid->find(TRUE) && ($oid->contact_id != $cid)) {
$errors["{$name}[$instance][openid]"] = ts('%1 already exist.', [1 => $blocks['OpenID']]);
}
}
}
if (empty($hasPrimary) && !empty($hasData)) {
$errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', [1 => $label]);
}
if (count($hasPrimary) > 1) {
$errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
[1 => $label]
);
}
}
}
//do validations for all opend ids they should be distinct.
if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
foreach ($openIds as $instance => $value) {
if (!array_key_exists($instance, array_unique($openIds))) {
$errors["openid[$instance][openid]"] = ts('%1 already used.', [1 => $blocks['OpenID']]);
}
}
}
// street number should be digit + suffix, CRM-5450
$parseStreetAddress = CRM_Utils_Array::value('street_address_parsing',
CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'address_options'
)
);
if ($parseStreetAddress) {
if (isset($fields['address']) &&
is_array($fields['address'])
) {
$invalidStreetNumbers = [];
foreach ($fields['address'] as $cnt => $address) {
if ($streetNumber = CRM_Utils_Array::value('street_number', $address)) {
$parsedAddress = CRM_Core_BAO_Address::parseStreetAddress($address['street_number']);
if (empty($parsedAddress['street_number'])) {
$invalidStreetNumbers[] = $cnt;
}
}
}
if (!empty($invalidStreetNumbers)) {
$first = $invalidStreetNumbers[0];
foreach ($invalidStreetNumbers as & $num) {
$num = CRM_Contact_Form_Contact::ordinalNumber($num);
}
$errors["address[$first][street_number]"] = ts('The street number you entered for the %1 address block(s) is not in an expected format. Street numbers may include numeric digit(s) followed by other characters. You can still enter the complete street address (unparsed) by clicking "Edit Complete Street Address".', [1 => implode(', ', $invalidStreetNumbers)]);
}
}
}
// Check for duplicate contact if it wasn't already handled by ajax or disabled
if (!Civi::settings()->get('contact_ajax_check_similar') || !empty($fields['_qf_Contact_refresh_dedupe'])) {
self::checkDuplicateContacts($fields, $errors, $contactId, $contactType);
}
return $primaryID;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
//load form for child blocks
if ($this->_addBlockName) {
$className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName;
return $className::buildQuickForm($this);
}
if ($this->_action == CRM_Core_Action::UPDATE) {
$deleteExtra = json_encode(ts('Are you sure you want to delete contact image.'));
$deleteURL = [
CRM_Core_Action::DELETE => [
'name' => ts('Delete Contact Image'),
'url' => 'civicrm/contact/image',
'qs' => 'reset=1&cid=%%id%%&action=delete',
'extra' => 'onclick = "' . htmlspecialchars("if (confirm($deleteExtra)) this.href+='&confirmed=1'; else return false;") . '"',
],
];
$deleteURL = CRM_Core_Action::formLink($deleteURL,
CRM_Core_Action::DELETE,
[
'id' => $this->_contactId,
],
ts('more'),
FALSE,
'contact.image.delete',
'Contact',
$this->_contactId
);
$this->assign('deleteURL', $deleteURL);
}
//build contact type specific fields
$className = 'CRM_Contact_Form_Edit_' . $this->_contactType;
$className::buildQuickForm($this);
// Ajax duplicate checking
$checkSimilar = Civi::settings()->get('contact_ajax_check_similar');
$this->assign('checkSimilar', $checkSimilar);
if ($checkSimilar == 1) {
$ruleParams = ['used' => 'Supervised', 'contact_type' => $this->_contactType];
$this->assign('ruleFields', CRM_Dedupe_BAO_DedupeRule::dedupeRuleFields($ruleParams));
}
// build Custom data if Custom data present in edit option
$buildCustomData = 'noCustomDataPresent';
if (array_key_exists('CustomData', $this->_editOptions)) {
$buildCustomData = "customDataPresent";
}
// subtype is a common field. lets keep it here
$subtypes = CRM_Contact_BAO_Contact::buildOptions('contact_sub_type', 'create', ['contact_type' => $this->_contactType]);
if (!empty($subtypes)) {
$this->addField('contact_sub_type', [
'label' => ts('Contact Type'),
'options' => $subtypes,
'class' => $buildCustomData,
'multiple' => 'multiple',
'option_url' => NULL,
]);
}
// build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
foreach ($this->_editOptions as $name => $label) {
if ($name == 'Address') {
$this->_blocks['Address'] = $this->_editOptions['Address'];
continue;
}
if ($name == 'TagsAndGroups') {
continue;
}
$className = 'CRM_Contact_Form_Edit_' . $name;
$className::buildQuickForm($this);
}
// build tags and groups
CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups::ALL,
FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'select');
// build location blocks.
CRM_Contact_Form_Edit_Lock::buildQuickForm($this);
CRM_Contact_Form_Location::buildQuickForm($this);
// add attachment
$this->addField('image_URL', ['maxlength' => '255', 'label' => ts('Browse/Upload Image')]);
// add the dedupe button
$this->addElement('xbutton',
$this->_dedupeButtonName,
ts('Check for Matching Contact(s)'),
[
'type' => 'submit',
'value' => 1,
'class' => "crm-button crm-button{$this->_dedupeButtonName}",
]
);
$this->addElement('xbutton',
$this->_duplicateButtonName,
ts('Save Matching Contact'),
[
'type' => 'submit',
'value' => 1,
'class' => "crm-button crm-button{$this->_duplicateButtonName}",
]
);
$this->addElement('xbutton',
$this->getButtonName('next', 'sharedHouseholdDuplicate'),
ts('Save With Duplicate Household'),
[
'type' => 'submit',
'value' => 1,
]
);
$buttons = [
[
'type' => 'upload',
'name' => ts('Save'),
'subName' => 'view',
'isDefault' => TRUE,
],
];
if (CRM_Core_Permission::check('add contacts')) {
$buttons[] = [
'type' => 'upload',
'name' => ts('Save and New'),
'spacing' => ' ',
'subName' => 'new',
];
}
$buttons[] = [
'type' => 'cancel',
'name' => ts('Cancel'),
];
if (!empty($this->_values['contact_sub_type'])) {
$this->_oldSubtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
trim($this->_values['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR)
);
}
$this->assign('oldSubtypes', json_encode($this->_oldSubtypes));
$this->addButtons($buttons);
}
/**
* Form submission of new/edit contact is processed.
*/
public function postProcess() {
// check if dedupe button, if so return.
$buttonName = $this->controller->getButtonName();
if ($buttonName == $this->_dedupeButtonName) {
return;
}
//get the submitted values in an array
$params = $this->controller->exportValues($this->_name);
if (!isset($params['preferred_communication_method'])) {
// If this field is empty QF will trim it so we have to add it in.
$params['preferred_communication_method'] = 'null';
}
$group = $params['group'] ?? NULL;
$params['group'] = ($params['group'] == '') ? [] : $params['group'];
if (!empty($group)) {
$group = is_array($group) ? $group : explode(',', $group);
$params['group'] = [];
foreach ($group as $key => $value) {
$params['group'][$value] = 1;
}
}
if (!empty($params['image_URL'])) {
CRM_Contact_BAO_Contact::processImageParams($params);
}
if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
$params['current_employer'] = $params['current_employer_id'];
}
// don't carry current_employer_id field,
// since we don't want to directly update DAO object without
// handling related business logic ( eg related membership )
if (isset($params['current_employer_id'])) {
unset($params['current_employer_id']);
}
$params['contact_type'] = $this->_contactType;
if (empty($params['contact_sub_type']) && $this->_isContactSubType) {
$params['contact_sub_type'] = [$this->_contactSubType];
}
if ($this->_contactId) {
$params['contact_id'] = $this->_contactId;
}
//make deceased date null when is_deceased = false
if ($this->_contactType == 'Individual' && !empty($this->_editOptions['Demographics']) && empty($params['is_deceased'])) {
$params['is_deceased'] = FALSE;
$params['deceased_date'] = NULL;
}
// action is taken depending upon the mode
if ($this->_action & CRM_Core_Action::UPDATE) {
CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
}
else {
CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
}
//CRM-5143
//if subtype is set, send subtype as extend to validate subtype customfield
$customFieldExtends = (CRM_Utils_Array::value('contact_sub_type', $params)) ? $params['contact_sub_type'] : $params['contact_type'];
$params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
$this->_contactId,
$customFieldExtends,
TRUE
);
if ($this->_contactId && !empty($this->_oldSubtypes)) {
CRM_Contact_BAO_ContactType::deleteCustomSetForSubtypeMigration($this->_contactId,
$params['contact_type'],
$this->_oldSubtypes,
$params['contact_sub_type']
);
}
if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
// this is a chekbox, so mark false if we dont get a POST value
$params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
}
// process shared contact address.
CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']);
if (!array_key_exists('TagsAndGroups', $this->_editOptions)) {
unset($params['group']);
}
elseif (!empty($params['contact_id']) && ($this->_action & CRM_Core_Action::UPDATE)) {
// figure out which all groups are intended to be removed
$contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
if (is_array($contactGroupList)) {
foreach ($contactGroupList as $key) {
if ((!array_key_exists($key['group_id'], $params['group']) || $params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
$params['group'][$key['group_id']] = -1;
}
}
}
}
// parse street address, CRM-5450
$parseStatusMsg = NULL;
if ($this->_parseStreetAddress) {
$parseResult = self::parseAddress($params);
$parseStatusMsg = self::parseAddressStatusMsg($parseResult);
}
$blocks = ['email', 'phone', 'im', 'openid', 'address', 'website'];
foreach ($blocks as $block) {
if (!empty($this->_preEditValues[$block]) && is_array($this->_preEditValues[$block])) {
foreach ($this->_preEditValues[$block] as $count => $value) {
if (!empty($value['id'])) {
$params[$block][$count]['id'] = $value['id'];
$params[$block]['isIdSet'] = TRUE;
}
}
}
}
// Allow un-setting of location info, CRM-5969
$params['updateBlankLocInfo'] = TRUE;
$contact = CRM_Contact_BAO_Contact::create($params, TRUE, FALSE, TRUE);
// status message
if ($this->_contactId) {
$message = ts('%1 has been updated.', [1 => $contact->display_name]);