Merge pull request #16692 from MegaphoneJon/financial-119
[civicrm-core.git] / CRM / Contact / Form / Contact.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
19 * This class generates form components generic to all the contact types.
20 *
21 * It delegates the work to lower level subclasses and integrates the changes
22 * back in. It also uses a lot of functionality with the CRM API's, so any change
23 * made here could potentially affect the API etc. Be careful, be aware, use unit tests.
24 *
25 */
26class CRM_Contact_Form_Contact extends CRM_Core_Form {
27
28 /**
fe482240 29 * The contact type of the form.
6a488035
TO
30 *
31 * @var string
32 */
33 public $_contactType;
34
35 /**
fe482240 36 * The contact type of the form.
6a488035
TO
37 *
38 * @var string
39 */
40 public $_contactSubType;
41
42 /**
43 * The contact id, used when editing the form
44 *
45 * @var int
46 */
47 public $_contactId;
48
49 /**
fe482240 50 * The default group id passed in via the url.
6a488035
TO
51 *
52 * @var int
53 */
54 public $_gid;
55
56 /**
fe482240 57 * The default tag id passed in via the url.
6a488035
TO
58 *
59 * @var int
60 */
61 public $_tid;
62
63 /**
100fef9d 64 * Name of de-dupe button
6a488035
TO
65 *
66 * @var string
6a488035
TO
67 */
68 protected $_dedupeButtonName;
69
70 /**
fe482240 71 * Name of optional save duplicate button.
6a488035
TO
72 *
73 * @var string
6a488035
TO
74 */
75 protected $_duplicateButtonName;
76
be2fb01f 77 protected $_editOptions = [];
6a488035 78
be2fb01f 79 protected $_oldSubtypes = [];
6a488035
TO
80
81 public $_blocks;
82
be2fb01f 83 public $_values = [];
6a488035
TO
84
85 public $_action;
86
87 public $_customValueCount;
88 /**
fe482240 89 * The array of greetings with option group and filed names.
6a488035
TO
90 *
91 * @var array
92 */
93 public $_greetings;
94
95 /**
96 * Do we want to parse street address.
69078420 97 * @var bool
6a488035
TO
98 */
99 public $_parseStreetAddress;
100
101 /**
fe482240 102 * Check contact has a subtype or not.
69078420 103 * @var bool
6a488035
TO
104 */
105 public $_isContactSubType;
106
107 /**
108 * Lets keep a cache of all the values that we retrieved.
109 * THis is an attempt to avoid the number of update statements
110 * during the write phase
69078420 111 * @var array
6a488035
TO
112 */
113 public $_preEditValues;
d5965a37 114
6e62b28c
TM
115 /**
116 * Explicitly declare the entity api name.
117 */
118 public function getDefaultEntity() {
119 return 'Contact';
120 }
6a488035 121
1ae720b3
TM
122 /**
123 * Explicitly declare the form context.
124 */
125 public function getDefaultContext() {
126 return 'create';
127 }
128
6a488035 129 /**
fe482240 130 * Build all the data structures needed to build the form.
6a488035 131 */
00be9182 132 public function preProcess() {
6a488035
TO
133 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
134
135 $this->_dedupeButtonName = $this->getButtonName('refresh', 'dedupe');
136 $this->_duplicateButtonName = $this->getButtonName('upload', 'duplicate');
137
0e44568b
CW
138 CRM_Core_Resources::singleton()
139 ->addStyleFile('civicrm', 'css/contactSummary.css', 2, 'html-header');
140
6a488035
TO
141 $session = CRM_Core_Session::singleton();
142 if ($this->_action == CRM_Core_Action::ADD) {
143 // check for add contacts permissions
144 if (!CRM_Core_Permission::check('add contacts')) {
145 CRM_Utils_System::permissionDenied();
146 CRM_Utils_System::civiExit();
147 }
148 $this->_contactType = CRM_Utils_Request::retrieve('ct', 'String',
149 $this, TRUE, NULL, 'REQUEST'
150 );
151 if (!in_array($this->_contactType,
be2fb01f 152 ['Individual', 'Household', 'Organization']
353ffa53
TO
153 )
154 ) {
6a488035
TO
155 CRM_Core_Error::statusBounce(ts('Could not get a contact id and/or contact type'));
156 }
157
158 $this->_isContactSubType = FALSE;
159 if ($this->_contactSubType = CRM_Utils_Request::retrieve('cst', 'String', $this)) {
160 $this->_isContactSubType = TRUE;
161 }
162
163 if (
164 $this->_contactSubType &&
353ffa53
TO
165 !(CRM_Contact_BAO_ContactType::isExtendsContactType($this->_contactSubType, $this->_contactType, TRUE))
166 ) {
be2fb01f 167 CRM_Core_Error::statusBounce(ts("Could not get a valid contact subtype for contact type '%1'", [1 => $this->_contactType]));
6a488035
TO
168 }
169
170 $this->_gid = CRM_Utils_Request::retrieve('gid', 'Integer',
171 CRM_Core_DAO::$_nullObject,
172 FALSE, NULL, 'GET'
173 );
174 $this->_tid = CRM_Utils_Request::retrieve('tid', 'Integer',
175 CRM_Core_DAO::$_nullObject,
176 FALSE, NULL, 'GET'
177 );
178 $typeLabel = CRM_Contact_BAO_ContactType::contactTypePairs(TRUE, $this->_contactSubType ?
353ffa53 179 $this->_contactSubType : $this->_contactType
6a488035
TO
180 );
181 $typeLabel = implode(' / ', $typeLabel);
182
be2fb01f 183 CRM_Utils_System::setTitle(ts('New %1', [1 => $typeLabel]));
6a488035
TO
184 $session->pushUserContext(CRM_Utils_System::url('civicrm/dashboard', 'reset=1'));
185 $this->_contactId = NULL;
186 }
187 else {
188 //update mode
189 if (!$this->_contactId) {
190 $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
191 }
192
193 if ($this->_contactId) {
be2fb01f
CW
194 $defaults = [];
195 $params = ['id' => $this->_contactId];
196 $returnProperities = ['id', 'contact_type', 'contact_sub_type', 'modified_date', 'is_deceased'];
6a488035
TO
197 CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Contact', $params, $defaults, $returnProperities);
198
a7488080 199 if (empty($defaults['id'])) {
be2fb01f 200 CRM_Core_Error::statusBounce(ts('A Contact with that ID does not exist: %1', [1 => $this->_contactId]));
6a488035
TO
201 }
202
203 $this->_contactType = CRM_Utils_Array::value('contact_type', $defaults);
204 $this->_contactSubType = CRM_Utils_Array::value('contact_sub_type', $defaults);
205
206 // check for permissions
207 $session = CRM_Core_Session::singleton();
ad623fd4 208 if (!CRM_Contact_BAO_Contact_Permission::allow($this->_contactId, CRM_Core_Permission::EDIT)) {
6a488035
TO
209 CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
210 }
211
212 $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId);
7d3ddae6 213 if ($defaults['is_deceased']) {
7c38bbf0 214 $displayName .= ' <span class="crm-contact-deceased">(' . ts('deceased') . ')</span>';
7d3ddae6 215 }
be2fb01f 216 $displayName = ts('Edit %1', [1 => $displayName]);
8ef12e64 217
6a488035
TO
218 // Check if this is default domain contact CRM-10482
219 if (CRM_Contact_BAO_Contact::checkDomainContact($this->_contactId)) {
220 $displayName .= ' (' . ts('default organization') . ')';
221 }
8ef12e64 222
6a488035
TO
223 // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
224 CRM_Utils_System::setTitle($displayName);
edc80cda 225 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
6a488035
TO
226 $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
227
228 $urlParams = 'reset=1&cid=' . $this->_contactId;
229 if ($context) {
230 $urlParams .= "&context=$context";
231 }
232
233 if (CRM_Utils_Rule::qfKey($qfKey)) {
234
235 $urlParams .= "&key=$qfKey";
236
237 }
238 $session->pushUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams));
239
240 $values = $this->get('values');
241 // get contact values.
242 if (!empty($values)) {
243 $this->_values = $values;
244 }
245 else {
be2fb01f 246 $params = [
6a488035
TO
247 'id' => $this->_contactId,
248 'contact_id' => $this->_contactId,
249 'noRelationships' => TRUE,
250 'noNotes' => TRUE,
251 'noGroups' => TRUE,
be2fb01f 252 ];
6a488035
TO
253
254 $contact = CRM_Contact_BAO_Contact::retrieve($params, $this->_values, TRUE);
255 $this->set('values', $this->_values);
256 }
257 }
258 else {
259 CRM_Core_Error::statusBounce(ts('Could not get a contact_id and/or contact_type'));
260 }
261 }
262
263 // parse street address, CRM-5450
264 $this->_parseStreetAddress = $this->get('parseStreetAddress');
265 if (!isset($this->_parseStreetAddress)) {
266 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
267 'address_options'
268 );
269 $this->_parseStreetAddress = FALSE;
8cc574cf 270 if (!empty($addressOptions['street_address']) && !empty($addressOptions['street_address_parsing'])) {
6a488035
TO
271 $this->_parseStreetAddress = TRUE;
272 }
273 $this->set('parseStreetAddress', $this->_parseStreetAddress);
274 }
275 $this->assign('parseStreetAddress', $this->_parseStreetAddress);
276
277 $this->_editOptions = $this->get('contactEditOptions');
278 if (CRM_Utils_System::isNull($this->_editOptions)) {
279 $this->_editOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
280 'contact_edit_options', TRUE, NULL,
281 FALSE, 'name', TRUE, 'AND v.filter = 0'
282 );
283 $this->set('contactEditOptions', $this->_editOptions);
284 }
285
286 // build demographics only for Individual contact type
287 if ($this->_contactType != 'Individual' &&
288 array_key_exists('Demographics', $this->_editOptions)
289 ) {
290 unset($this->_editOptions['Demographics']);
291 }
292
293 // in update mode don't show notes
294 if ($this->_contactId && array_key_exists('Notes', $this->_editOptions)) {
295 unset($this->_editOptions['Notes']);
296 }
297
298 $this->assign('editOptions', $this->_editOptions);
299 $this->assign('contactType', $this->_contactType);
300 $this->assign('contactSubType', $this->_contactSubType);
301
6a488035
TO
302 // get the location blocks.
303 $this->_blocks = $this->get('blocks');
304 if (CRM_Utils_System::isNull($this->_blocks)) {
305 $this->_blocks = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
306 'contact_edit_options', TRUE, NULL,
307 FALSE, 'name', TRUE, 'AND v.filter = 1'
308 );
309 $this->set('blocks', $this->_blocks);
310 }
311 $this->assign('blocks', $this->_blocks);
312
313 // this is needed for custom data.
314 $this->assign('entityID', $this->_contactId);
315
316 // also keep the convention.
317 $this->assign('contactId', $this->_contactId);
318
319 // location blocks.
320 CRM_Contact_Form_Location::preProcess($this);
321
322 // retain the multiple count custom fields value
a7488080 323 if (!empty($_POST['hidden_custom'])) {
6a488035
TO
324 $customGroupCount = CRM_Utils_Array::value('hidden_custom_group_count', $_POST);
325
481a74f4 326 if ($contactSubType = CRM_Utils_Array::value('contact_sub_type', $_POST)) {
6a488035
TO
327 $paramSubType = implode(',', $contactSubType);
328 }
329
330 $this->_getCachedTree = FALSE;
331 unset($customGroupCount[0]);
332 foreach ($customGroupCount as $groupID => $groupCount) {
333 if ($groupCount > 1) {
334 $this->set('groupID', $groupID);
335 //loop the group
336 for ($i = 0; $i <= $groupCount; $i++) {
337 CRM_Custom_Form_CustomData::preProcess($this, NULL, $contactSubType,
e6a1bdbe 338 $i, $this->_contactType, $this->_contactId
6a488035
TO
339 );
340 CRM_Contact_Form_Edit_CustomData::buildQuickForm($this);
341 }
342 }
343 }
344
345 //reset all the ajax stuff, for normal processing
346 if (isset($this->_groupTree)) {
347 $this->_groupTree = NULL;
348 }
349 $this->set('groupID', NULL);
350 $this->_getCachedTree = TRUE;
351 }
352
353 // execute preProcess dynamically by js else execute normal preProcess
354 if (array_key_exists('CustomData', $this->_editOptions)) {
355 //assign a parameter to pass for sub type multivalue
356 //custom field to load
357 if ($this->_contactSubType || isset($paramSubType)) {
358 $paramSubType = (isset($paramSubType)) ? $paramSubType :
481a74f4 359 str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ',', trim($this->_contactSubType, CRM_Core_DAO::VALUE_SEPARATOR));
6a488035
TO
360
361 $this->assign('paramSubType', $paramSubType);
362 }
363
a3d827a7 364 if (CRM_Utils_Request::retrieve('type', 'String')) {
6a488035
TO
365 CRM_Contact_Form_Edit_CustomData::preProcess($this);
366 }
367 else {
368 $contactSubType = $this->_contactSubType;
369 // need contact sub type to build related grouptree array during post process
a7488080 370 if (!empty($_POST['contact_sub_type'])) {
6a488035
TO
371 $contactSubType = $_POST['contact_sub_type'];
372 }
373 //only custom data has preprocess hence directly call it
374 CRM_Custom_Form_CustomData::preProcess($this, NULL, $contactSubType,
375 1, $this->_contactType, $this->_contactId
376 );
377 $this->assign('customValueCount', $this->_customValueCount);
378 }
379 }
380 }
381
382 /**
c037736a 383 * Set default values for the form.
6a488035 384 *
c037736a 385 * Note that in edit/view mode the default values are retrieved from the database
6a488035 386 */
00be9182 387 public function setDefaultValues() {
6a488035 388 $defaults = $this->_values;
6a488035
TO
389
390 if ($this->_action & CRM_Core_Action::ADD) {
391 if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
392 // set group and tag defaults if any
393 if ($this->_gid) {
c18f95b7 394 $defaults['group'][] = $this->_gid;
6a488035
TO
395 }
396 if ($this->_tid) {
397 $defaults['tag'][$this->_tid] = 1;
398 }
399 }
400 if ($this->_contactSubType) {
401 $defaults['contact_sub_type'] = $this->_contactSubType;
402 }
403 }
404 else {
6a488035
TO
405 foreach ($defaults['email'] as $dontCare => & $val) {
406 if (isset($val['signature_text'])) {
407 $val['signature_text_hidden'] = $val['signature_text'];
408 }
409 if (isset($val['signature_html'])) {
410 $val['signature_html_hidden'] = $val['signature_html'];
411 }
412 }
413
a7488080 414 if (!empty($defaults['contact_sub_type'])) {
6a488035
TO
415 $defaults['contact_sub_type'] = $this->_oldSubtypes;
416 }
417 }
6a488035
TO
418 // set defaults for blocks ( custom data, address, communication preference, notes, tags and groups )
419 foreach ($this->_editOptions as $name => $label) {
be2fb01f 420 if (!in_array($name, ['Address', 'Notes'])) {
150f50c1
CW
421 $className = 'CRM_Contact_Form_Edit_' . $name;
422 $className::setDefaultValues($this, $defaults);
6a488035
TO
423 }
424 }
425
426 //set address block defaults
481a74f4 427 CRM_Contact_Form_Edit_Address::setDefaultValues($defaults, $this);
6a488035 428
a7488080 429 if (!empty($defaults['image_URL'])) {
c3821398 430 $this->assign("imageURL", CRM_Utils_File::getImageURL($defaults['image_URL']));
6a488035
TO
431 }
432
433 //set location type and country to default for each block
434 $this->blockSetDefaults($defaults);
435
436 $this->_preEditValues = $defaults;
437 return $defaults;
438 }
439
440 /**
ea3ddccf 441 * Do the set default related to location type id, primary location, default country.
442 *
443 * @param array $defaults
6a488035 444 */
00be9182 445 public function blockSetDefaults(&$defaults) {
b2b0530a 446 $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int');
6a488035
TO
447 sort($locationTypeKeys);
448
449 // get the default location type
450 $locationType = CRM_Core_BAO_LocationType::getDefault();
451
452 // unset primary location type
453 $primaryLocationTypeIdKey = CRM_Utils_Array::key($locationType->id, $locationTypeKeys);
454 unset($locationTypeKeys[$primaryLocationTypeIdKey]);
455
456 // reset the array sequence
457 $locationTypeKeys = array_values($locationTypeKeys);
458
459 // get default phone and im provider id.
460 $defPhoneTypeId = key(CRM_Core_OptionGroup::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1'));
461 $defIMProviderId = key(CRM_Core_OptionGroup::values('instant_messenger_service',
353ffa53
TO
462 FALSE, FALSE, FALSE, ' AND is_default = 1'
463 ));
1d477756
PN
464 $defWebsiteTypeId = key(CRM_Core_OptionGroup::values('website_type',
465 FALSE, FALSE, FALSE, ' AND is_default = 1'
466 ));
6a488035
TO
467
468 $allBlocks = $this->_blocks;
469 if (array_key_exists('Address', $this->_editOptions)) {
470 $allBlocks['Address'] = $this->_editOptions['Address'];
471 }
472
473 $config = CRM_Core_Config::singleton();
474 foreach ($allBlocks as $blockName => $label) {
475 $name = strtolower($blockName);
476 $hasPrimary = $updateMode = FALSE;
477
478 // user is in update mode.
479 if (array_key_exists($name, $defaults) &&
480 !CRM_Utils_System::isNull($defaults[$name])
481 ) {
482 $updateMode = TRUE;
483 }
484
485 for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++) {
486 // make we require one primary block, CRM-5505
594833d6 487 if ($updateMode) {
23839387 488 if (!$hasPrimary) {
594833d6 489 $hasPrimary = CRM_Utils_Array::value(
490 'is_primary',
491 CRM_Utils_Array::value($instance, $defaults[$name])
492 );
493 }
6a488035
TO
494 continue;
495 }
496
497 //set location to primary for first one.
498 if ($instance == 1) {
499 $hasPrimary = TRUE;
500 $defaults[$name][$instance]['is_primary'] = TRUE;
501 $defaults[$name][$instance]['location_type_id'] = $locationType->id;
502 }
503 else {
504 $locTypeId = isset($locationTypeKeys[$instance - 1]) ? $locationTypeKeys[$instance - 1] : $locationType->id;
505 $defaults[$name][$instance]['location_type_id'] = $locTypeId;
506 }
507
508 //set default country
509 if ($name == 'address' && $config->defaultContactCountry) {
510 $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry;
511 }
512
513 //set default state/province
514 if ($name == 'address' && $config->defaultContactStateProvince) {
515 $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince;
516 }
517
518 //set default phone type.
519 if ($name == 'phone' && $defPhoneTypeId) {
520 $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId;
521 }
1d477756
PN
522 //set default website type.
523 if ($name == 'website' && $defWebsiteTypeId) {
524 $defaults[$name][$instance]['website_type_id'] = $defWebsiteTypeId;
525 }
6a488035
TO
526
527 //set default im provider.
528 if ($name == 'im' && $defIMProviderId) {
529 $defaults[$name][$instance]['provider_id'] = $defIMProviderId;
530 }
531 }
532
533 if (!$hasPrimary) {
534 $defaults[$name][1]['is_primary'] = TRUE;
535 }
536 }
6a488035
TO
537 }
538
539 /**
dc195289 540 * add the rules (mainly global rules) for form.
6a488035
TO
541 * All local rules are added near the element
542 *
6a488035
TO
543 * @see valid_date
544 */
00be9182 545 public function addRules() {
6a488035
TO
546 // skip adding formRules when custom data is build
547 if ($this->_addBlockName || ($this->_action & CRM_Core_Action::DELETE)) {
548 return;
549 }
550
be2fb01f 551 $this->addFormRule(['CRM_Contact_Form_Edit_' . $this->_contactType, 'formRule'], $this->_contactId);
6a488035
TO
552
553 // Call Locking check if editing existing contact
554 if ($this->_contactId) {
be2fb01f 555 $this->addFormRule(['CRM_Contact_Form_Edit_Lock', 'formRule'], $this->_contactId);
6a488035
TO
556 }
557
558 if (array_key_exists('Address', $this->_editOptions)) {
be2fb01f 559 $this->addFormRule(['CRM_Contact_Form_Edit_Address', 'formRule'], $this);
6a488035
TO
560 }
561
562 if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
be2fb01f 563 $this->addFormRule(['CRM_Contact_Form_Edit_CommunicationPreferences', 'formRule'], $this);
6a488035
TO
564 }
565 }
566
567 /**
fe482240 568 * Global validation rules for the form.
6a488035 569 *
77c5b619
TO
570 * @param array $fields
571 * Posted values of the form.
572 * @param array $errors
573 * List of errors to be posted back to the form.
574 * @param int $contactId
575 * Contact id if doing update.
69078420 576 * @param string $contactType
6a488035 577 *
a6c01b45
CW
578 * @return bool
579 * email/openId
6a488035 580 */
d6def514 581 public static function formRule($fields, &$errors, $contactId, $contactType) {
6a488035
TO
582 $config = CRM_Core_Config::singleton();
583
584 // validations.
585 //1. for each block only single value can be marked as is_primary = true.
586 //2. location type id should be present if block data present.
587 //3. check open id across db and other each block for duplicate.
588 //4. at least one location should be primary.
589 //5. also get primaryID from email or open id block.
590
591 // take the location blocks.
592 $blocks = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
593 'contact_edit_options', TRUE, NULL,
594 FALSE, 'name', TRUE, 'AND v.filter = 1'
595 );
596
597 $otherEditOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
598 'contact_edit_options', TRUE, NULL,
599 FALSE, 'name', TRUE, 'AND v.filter = 0'
600 );
601 //get address block inside.
602 if (array_key_exists('Address', $otherEditOptions)) {
603 $blocks['Address'] = $otherEditOptions['Address'];
604 }
605
be2fb01f
CW
606 $website_types = [];
607 $openIds = [];
6a488035
TO
608 $primaryID = FALSE;
609 foreach ($blocks as $name => $label) {
be2fb01f 610 $hasData = $hasPrimary = [];
6a488035 611 $name = strtolower($name);
a7488080 612 if (!empty($fields[$name]) && is_array($fields[$name])) {
6a488035
TO
613 foreach ($fields[$name] as $instance => $blockValues) {
614 $dataExists = self::blockDataExists($blockValues);
615
616 if (!$dataExists && $name == 'address') {
617 $dataExists = CRM_Utils_Array::value('use_shared_address', $fields['address'][$instance]);
618 }
619
620 if ($dataExists) {
6a488035 621 if ($name == 'website') {
778fd763
GB
622 if (!empty($blockValues['website_type_id'])) {
623 if (empty($website_types[$blockValues['website_type_id']])) {
624 $website_types[$blockValues['website_type_id']] = $blockValues['website_type_id'];
625 }
626 else {
627 $errors["{$name}[1][website_type_id]"] = ts('Contacts may only have one website of each type at most.');
628 }
629 }
630
631 // skip remaining checks for website
6a488035
TO
632 continue;
633 }
634
635 $hasData[] = $instance;
a7488080 636 if (!empty($blockValues['is_primary'])) {
6a488035
TO
637 $hasPrimary[] = $instance;
638 if (!$primaryID &&
be2fb01f 639 in_array($name, [
353ffa53 640 'email',
af9b09df 641 'openid',
be2fb01f 642 ]) && !empty($blockValues[$name])
353ffa53 643 ) {
6a488035
TO
644 $primaryID = $blockValues[$name];
645 }
646 }
647
a7488080 648 if (empty($blockValues['location_type_id'])) {
be2fb01f 649 $errors["{$name}[$instance][location_type_id]"] = ts('The Location Type should be set if there is %1 information.', [1 => $label]);
6a488035
TO
650 }
651 }
652
8cc574cf 653 if ($name == 'openid' && !empty($blockValues[$name])) {
353ffa53 654 $oid = new CRM_Core_DAO_OpenID();
6a488035 655 $oid->openid = $openIds[$instance] = CRM_Utils_Array::value($name, $blockValues);
353ffa53 656 $cid = isset($contactId) ? $contactId : 0;
6a488035 657 if ($oid->find(TRUE) && ($oid->contact_id != $cid)) {
be2fb01f 658 $errors["{$name}[$instance][openid]"] = ts('%1 already exist.', [1 => $blocks['OpenID']]);
6a488035
TO
659 }
660 }
661 }
662
663 if (empty($hasPrimary) && !empty($hasData)) {
be2fb01f 664 $errors["{$name}[1][is_primary]"] = ts('One %1 should be marked as primary.', [1 => $label]);
6a488035
TO
665 }
666
667 if (count($hasPrimary) > 1) {
668 $errors["{$name}[" . array_pop($hasPrimary) . "][is_primary]"] = ts('Only one %1 can be marked as primary.',
be2fb01f 669 [1 => $label]
6a488035
TO
670 );
671 }
672 }
673 }
674
675 //do validations for all opend ids they should be distinct.
676 if (!empty($openIds) && (count(array_unique($openIds)) != count($openIds))) {
677 foreach ($openIds as $instance => $value) {
678 if (!array_key_exists($instance, array_unique($openIds))) {
be2fb01f 679 $errors["openid[$instance][openid]"] = ts('%1 already used.', [1 => $blocks['OpenID']]);
6a488035
TO
680 }
681 }
682 }
683
684 // street number should be digit + suffix, CRM-5450
685 $parseStreetAddress = CRM_Utils_Array::value('street_address_parsing',
686 CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
687 'address_options'
688 )
689 );
690 if ($parseStreetAddress) {
691 if (isset($fields['address']) &&
692 is_array($fields['address'])
693 ) {
be2fb01f 694 $invalidStreetNumbers = [];
6a488035
TO
695 foreach ($fields['address'] as $cnt => $address) {
696 if ($streetNumber = CRM_Utils_Array::value('street_number', $address)) {
697 $parsedAddress = CRM_Core_BAO_Address::parseStreetAddress($address['street_number']);
a7488080 698 if (empty($parsedAddress['street_number'])) {
6a488035
TO
699 $invalidStreetNumbers[] = $cnt;
700 }
701 }
702 }
703
704 if (!empty($invalidStreetNumbers)) {
705 $first = $invalidStreetNumbers[0];
353ffa53
TO
706 foreach ($invalidStreetNumbers as & $num) {
707 $num = CRM_Contact_Form_Contact::ordinalNumber($num);
708 }
be2fb01f 709 $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)]);
6a488035
TO
710 }
711 }
712 }
713
d6def514 714 // Check for duplicate contact if it wasn't already handled by ajax or disabled
a7ba493c 715 if (!Civi::settings()->get('contact_ajax_check_similar') || !empty($fields['_qf_Contact_refresh_dedupe'])) {
d6def514
CW
716 self::checkDuplicateContacts($fields, $errors, $contactId, $contactType);
717 }
718
6a488035
TO
719 return $primaryID;
720 }
721
722 /**
fe482240 723 * Build the form object.
6a488035
TO
724 */
725 public function buildQuickForm() {
726 //load form for child blocks
727 if ($this->_addBlockName) {
150f50c1
CW
728 $className = 'CRM_Contact_Form_Edit_' . $this->_addBlockName;
729 return $className::buildQuickForm($this);
6a488035
TO
730 }
731
732 if ($this->_action == CRM_Core_Action::UPDATE) {
e8fb9449 733 $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.'));
be2fb01f
CW
734 $deleteURL = [
735 CRM_Core_Action::DELETE => [
af9b09df
TO
736 'name' => ts('Delete Contact Image'),
737 'url' => 'civicrm/contact/image',
738 'qs' => 'reset=1&cid=%%id%%&action=delete',
e8fb9449 739 'extra' => 'onclick = "' . htmlspecialchars("if (confirm($deleteExtra)) this.href+='&confirmed=1'; else return false;") . '"',
be2fb01f
CW
740 ],
741 ];
6a488035
TO
742 $deleteURL = CRM_Core_Action::formLink($deleteURL,
743 CRM_Core_Action::DELETE,
be2fb01f 744 [
6a488035 745 'id' => $this->_contactId,
be2fb01f 746 ],
87dab4a4
AH
747 ts('more'),
748 FALSE,
749 'contact.image.delete',
750 'Contact',
751 $this->_contactId
6a488035
TO
752 );
753 $this->assign('deleteURL', $deleteURL);
754 }
755
756 //build contact type specific fields
150f50c1
CW
757 $className = 'CRM_Contact_Form_Edit_' . $this->_contactType;
758 $className::buildQuickForm($this);
6a488035 759
d6def514 760 // Ajax duplicate checking
a7ba493c 761 $checkSimilar = Civi::settings()->get('contact_ajax_check_similar');
d6def514
CW
762 $this->assign('checkSimilar', $checkSimilar);
763 if ($checkSimilar == 1) {
be2fb01f 764 $ruleParams = ['used' => 'Supervised', 'contact_type' => $this->_contactType];
d6def514
CW
765 $this->assign('ruleFields', CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams));
766 }
767
6a488035
TO
768 // build Custom data if Custom data present in edit option
769 $buildCustomData = 'noCustomDataPresent';
770 if (array_key_exists('CustomData', $this->_editOptions)) {
771 $buildCustomData = "customDataPresent";
772 }
773
774 // subtype is a common field. lets keep it here
be2fb01f 775 $subtypes = CRM_Contact_BAO_Contact::buildOptions('contact_sub_type', 'create', ['contact_type' => $this->_contactType]);
6a488035 776 if (!empty($subtypes)) {
be2fb01f 777 $this->addField('contact_sub_type', [
33fa033c
TM
778 'label' => ts('Contact Type'),
779 'options' => $subtypes,
780 'class' => $buildCustomData,
781 'multiple' => 'multiple',
599ae208 782 'option_url' => NULL,
be2fb01f 783 ]);
6a488035
TO
784 }
785
786 // build edit blocks ( custom data, demographics, communication preference, notes, tags and groups )
787 foreach ($this->_editOptions as $name => $label) {
788 if ($name == 'Address') {
789 $this->_blocks['Address'] = $this->_editOptions['Address'];
790 continue;
791 }
c18f95b7
PJ
792 if ($name == 'TagsAndGroups') {
793 continue;
794 }
150f50c1
CW
795 $className = 'CRM_Contact_Form_Edit_' . $name;
796 $className::buildQuickForm($this);
6a488035
TO
797 }
798
c18f95b7
PJ
799 // build tags and groups
800 CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($this, 0, CRM_Contact_Form_Edit_TagsAndGroups::ALL,
ab345ca5 801 FALSE, NULL, 'Group(s)', 'Tag(s)', NULL, 'select');
c18f95b7 802
6a488035
TO
803 // build location blocks.
804 CRM_Contact_Form_Edit_Lock::buildQuickForm($this);
805 CRM_Contact_Form_Location::buildQuickForm($this);
806
807 // add attachment
be2fb01f 808 $this->addField('image_URL', ['maxlength' => '255', 'label' => ts('Browse/Upload Image')]);
6a488035
TO
809
810 // add the dedupe button
811 $this->addElement('submit',
812 $this->_dedupeButtonName,
813 ts('Check for Matching Contact(s)')
814 );
815 $this->addElement('submit',
816 $this->_duplicateButtonName,
817 ts('Save Matching Contact')
818 );
819 $this->addElement('submit',
820 $this->getButtonName('next', 'sharedHouseholdDuplicate'),
821 ts('Save With Duplicate Household')
822 );
823
be2fb01f
CW
824 $buttons = [
825 [
6a488035
TO
826 'type' => 'upload',
827 'name' => ts('Save'),
828 'subName' => 'view',
829 'isDefault' => TRUE,
be2fb01f
CW
830 ],
831 ];
1870cae9 832 if (CRM_Core_Permission::check('add contacts')) {
be2fb01f 833 $buttons[] = [
6a488035
TO
834 'type' => 'upload',
835 'name' => ts('Save and New'),
836 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
837 'subName' => 'new',
be2fb01f 838 ];
1870cae9 839 }
be2fb01f 840 $buttons[] = [
1870cae9
CW
841 'type' => 'cancel',
842 'name' => ts('Cancel'),
be2fb01f 843 ];
6a488035 844
a7488080 845 if (!empty($this->_values['contact_sub_type'])) {
6a488035
TO
846 $this->_oldSubtypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
847 trim($this->_values['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR)
848 );
849 }
850 $this->assign('oldSubtypes', json_encode($this->_oldSubtypes));
851
852 $this->addButtons($buttons);
853 }
854
855 /**
856 * Form submission of new/edit contact is processed.
6a488035
TO
857 */
858 public function postProcess() {
859 // check if dedupe button, if so return.
860 $buttonName = $this->controller->getButtonName();
861 if ($buttonName == $this->_dedupeButtonName) {
862 return;
863 }
864
865 //get the submitted values in an array
866 $params = $this->controller->exportValues($this->_name);
37f7ae88 867 if (!isset($params['preferred_communication_method'])) {
868 // If this field is empty QF will trim it so we have to add it in.
869 $params['preferred_communication_method'] = 'null';
870 }
6a488035 871
c18f95b7 872 $group = CRM_Utils_Array::value('group', $params);
7e6c32e8 873 if (!empty($group) && is_array($group)) {
c18f95b7
PJ
874 unset($params['group']);
875 foreach ($group as $key => $value) {
876 $params['group'][$value] = 1;
877 }
878 }
879
a7488080 880 if (!empty($params['image_URL'])) {
6a488035
TO
881 CRM_Contact_BAO_Contact::processImageParams($params);
882 }
883
8cc574cf 884 if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
6a488035
TO
885 $params['current_employer'] = $params['current_employer_id'];
886 }
887
888 // don't carry current_employer_id field,
889 // since we don't want to directly update DAO object without
890 // handling related business logic ( eg related membership )
891 if (isset($params['current_employer_id'])) {
892 unset($params['current_employer_id']);
893 }
894
895 $params['contact_type'] = $this->_contactType;
896 if (empty($params['contact_sub_type']) && $this->_isContactSubType) {
be2fb01f 897 $params['contact_sub_type'] = [$this->_contactSubType];
6a488035
TO
898 }
899
900 if ($this->_contactId) {
901 $params['contact_id'] = $this->_contactId;
902 }
903
904 //make deceased date null when is_deceased = false
8cc574cf 905 if ($this->_contactType == 'Individual' && !empty($this->_editOptions['Demographics']) && empty($params['is_deceased'])) {
6a488035
TO
906 $params['is_deceased'] = FALSE;
907 $params['deceased_date'] = NULL;
908 }
909
910 if (isset($params['contact_id'])) {
911 // process membership status for deceased contact
be2fb01f 912 $deceasedParams = [
6ea503d4 913 'contact_id' => CRM_Utils_Array::value('contact_id', $params),
6a488035
TO
914 'is_deceased' => CRM_Utils_Array::value('is_deceased', $params, FALSE),
915 'deceased_date' => CRM_Utils_Array::value('deceased_date', $params, NULL),
be2fb01f 916 ];
dfd10cd7 917 $updateMembershipMsg = CRM_Member_BAO_Membership::updateMembershipStatus($deceasedParams, $this->_contactType);
6a488035
TO
918 }
919
920 // action is taken depending upon the mode
921 if ($this->_action & CRM_Core_Action::UPDATE) {
922 CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
923 }
924 else {
925 CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
926 }
927
6a488035
TO
928 //CRM-5143
929 //if subtype is set, send subtype as extend to validate subtype customfield
930 $customFieldExtends = (CRM_Utils_Array::value('contact_sub_type', $params)) ? $params['contact_sub_type'] : $params['contact_type'];
931
932 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
6a488035
TO
933 $this->_contactId,
934 $customFieldExtends,
935 TRUE
936 );
937 if ($this->_contactId && !empty($this->_oldSubtypes)) {
938 CRM_Contact_BAO_ContactType::deleteCustomSetForSubtypeMigration($this->_contactId,
939 $params['contact_type'],
940 $this->_oldSubtypes,
941 $params['contact_sub_type']
942 );
943 }
944
945 if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
946 // this is a chekbox, so mark false if we dont get a POST value
947 $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
948 }
949
950 // process shared contact address.
951 CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']);
952
0808ea6a 953 if (!array_key_exists('TagsAndGroups', $this->_editOptions)) {
6a488035
TO
954 unset($params['group']);
955 }
0808ea6a 956 elseif (!empty($params['contact_id']) && ($this->_action & CRM_Core_Action::UPDATE)) {
6a488035 957 // figure out which all groups are intended to be removed
c18f95b7
PJ
958 $contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
959 if (is_array($contactGroupList)) {
960 foreach ($contactGroupList as $key) {
8cc574cf 961 if ((!array_key_exists($key['group_id'], $params['group']) || $params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
c18f95b7 962 $params['group'][$key['group_id']] = -1;
6a488035
TO
963 }
964 }
965 }
966 }
967
968 // parse street address, CRM-5450
969 $parseStatusMsg = NULL;
970 if ($this->_parseStreetAddress) {
971 $parseResult = self::parseAddress($params);
972 $parseStatusMsg = self::parseAddressStatusMsg($parseResult);
973 }
974
be2fb01f 975 $blocks = ['email', 'phone', 'im', 'openid', 'address', 'website'];
85c882c5 976 foreach ($blocks as $block) {
a3b489b9 977 if (!empty($this->_preEditValues[$block]) && is_array($this->_preEditValues[$block])) {
978 foreach ($this->_preEditValues[$block] as $count => $value) {
979 if (!empty($value['id'])) {
980 $params[$block][$count]['id'] = $value['id'];
981 $params[$block]['isIdSet'] = TRUE;
982 }
85c882c5 983 }
984 }
985 }
986
6a488035
TO
987 // Allow un-setting of location info, CRM-5969
988 $params['updateBlankLocInfo'] = TRUE;
989
990 $contact = CRM_Contact_BAO_Contact::create($params, TRUE, FALSE, TRUE);
991
992 // status message
993 if ($this->_contactId) {
be2fb01f 994 $message = ts('%1 has been updated.', [1 => $contact->display_name]);
6a488035
TO
995 }
996 else {
be2fb01f 997 $message = ts('%1 has been created.', [1 => $contact->display_name]);
6a488035
TO
998 }
999
1000 // set the contact ID
1001 $this->_contactId = $contact->id;
1002
1003 if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
1004 //add contact to tags
85085150 1005 if (isset($params['tag'])) {
d8d2f9e1 1006 $params['tag'] = array_flip(explode(',', $params['tag']));
1007 CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']);
1008 }
6a488035
TO
1009 //save free tags
1010 if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
1011 CRM_Core_Form_Tag::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
1012 }
1013 }
1014
1015 if (!empty($parseStatusMsg)) {
1016 $message .= "<br />$parseStatusMsg";
1017 }
1018 if (!empty($updateMembershipMsg)) {
1019 $message .= "<br />$updateMembershipMsg";
1020 }
1021
1022 $session = CRM_Core_Session::singleton();
1023 $session->setStatus($message, ts('Contact Saved'), 'success');
1024
1025 // add the recently viewed contact
be2fb01f 1026 $recentOther = [];
6a488035
TO
1027 if (($session->get('userID') == $contact->id) ||
1028 CRM_Contact_BAO_Contact_Permission::allow($contact->id, CRM_Core_Permission::EDIT)
1029 ) {
1030 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id);
1031 }
1032
1033 if (($session->get('userID') != $this->_contactId) && CRM_Core_Permission::check('delete contacts')) {
1034 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id);
1035 }
1036
1037 CRM_Utils_Recent::add($contact->display_name,
1038 CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id),
1039 $contact->id,
1040 $this->_contactType,
1041 $contact->id,
1042 $contact->display_name,
1043 $recentOther
1044 );
1045
1046 // here we replace the user context with the url to view this contact
1047 $buttonName = $this->controller->getButtonName();
1048 if ($buttonName == $this->getButtonName('upload', 'new')) {
69dde52d 1049 $contactSubTypes = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_contactSubType));
6a488035 1050 $resetStr = "reset=1&ct={$contact->contact_type}";
69dde52d 1051 $resetStr .= (count($contactSubTypes) == 1) ? "&cst=" . array_pop($contactSubTypes) : '';
6a488035
TO
1052 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr));
1053 }
1054 else {
edc80cda 1055 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
6a488035
TO
1056 $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
1057 //validate the qfKey
1058 $urlParams = 'reset=1&cid=' . $contact->id;
1059 if ($context) {
1060 $urlParams .= "&context=$context";
1061 }
1062 if (CRM_Utils_Rule::qfKey($qfKey)) {
1063 $urlParams .= "&key=$qfKey";
1064 }
1065
1066 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams));
1067 }
1068
1069 // now invoke the post hook
1070 if ($this->_action & CRM_Core_Action::UPDATE) {
1071 CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
1072 }
1073 else {
1074 CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
1075 }
1076 }
1077
1078 /**
fe482240 1079 * Is there any real significant data in the hierarchical location array.
6a488035 1080 *
77c5b619
TO
1081 * @param array $fields
1082 * The hierarchical value representation of this location.
6a488035 1083 *
5c766a0b 1084 * @return bool
a6c01b45 1085 * true if data exists, false otherwise
6a488035 1086 */
00be9182 1087 public static function blockDataExists(&$fields) {
6a488035
TO
1088 if (!is_array($fields)) {
1089 return FALSE;
1090 }
1091
be2fb01f 1092 static $skipFields = [
353ffa53
TO
1093 'location_type_id',
1094 'is_primary',
1095 'phone_type_id',
1096 'provider_id',
1097 'country_id',
1098 'website_type_id',
af9b09df 1099 'master_id',
be2fb01f 1100 ];
6a488035
TO
1101 foreach ($fields as $name => $value) {
1102 $skipField = FALSE;
1103 foreach ($skipFields as $skip) {
1104 if (strpos("[$skip]", $name) !== FALSE) {
1105 if ($name == 'phone') {
1106 continue;
1107 }
1108 $skipField = TRUE;
1109 break;
1110 }
1111 }
1112 if ($skipField) {
1113 continue;
1114 }
1115 if (is_array($value)) {
1116 if (self::blockDataExists($value)) {
1117 return TRUE;
1118 }
1119 }
1120 else {
1121 if (!empty($value)) {
1122 return TRUE;
1123 }
1124 }
1125 }
1126
1127 return FALSE;
1128 }
1129
1130 /**
fe482240 1131 * That checks for duplicate contacts.
6a488035 1132 *
77c5b619
TO
1133 * @param array $fields
1134 * Fields array which are submitted.
fd31fa4c 1135 * @param $errors
77c5b619
TO
1136 * @param int $contactID
1137 * Contact id.
1138 * @param string $contactType
1139 * Contact type.
6a488035 1140 */
00be9182 1141 public static function checkDuplicateContacts(&$fields, &$errors, $contactID, $contactType) {
6a488035 1142 // if this is a forced save, ignore find duplicate rule
a7488080 1143 if (empty($fields['_qf_Contact_upload_duplicate'])) {
6a488035 1144
be2fb01f 1145 $ids = CRM_Contact_BAO_Contact::getDuplicateContacts($fields, $contactType, 'Supervised', [$contactID]);
6a488035
TO
1146 if ($ids) {
1147
1148 $contactLinks = CRM_Contact_BAO_Contact_Utils::formatContactIDSToLinks($ids, TRUE, TRUE, $contactID);
1149
1150 $duplicateContactsLinks = '<div class="matching-contacts-found">';
be2fb01f 1151 $duplicateContactsLinks .= ts('One matching contact was found. ', [
69078420
SL
1152 'count' => count($contactLinks['rows']),
1153 'plural' => '%count matching contacts were found.<br />',
1154 ]);
6a488035 1155 if ($contactLinks['msg'] == 'view') {
be2fb01f 1156 $duplicateContactsLinks .= ts('You can View the existing contact', [
69078420
SL
1157 'count' => count($contactLinks['rows']),
1158 'plural' => 'You can View the existing contacts',
1159 ]);
6a488035
TO
1160 }
1161 else {
be2fb01f 1162 $duplicateContactsLinks .= ts('You can View or Edit the existing contact', [
69078420
SL
1163 'count' => count($contactLinks['rows']),
1164 'plural' => 'You can View or Edit the existing contacts',
1165 ]);
6a488035
TO
1166 }
1167 if ($contactLinks['msg'] == 'merge') {
1168 // We should also get a merge link if this is for an existing contact
1169 $duplicateContactsLinks .= ts(', or Merge this contact with an existing contact');
1170 }
1171 $duplicateContactsLinks .= '.';
1172 $duplicateContactsLinks .= '</div>';
1173 $duplicateContactsLinks .= '<table class="matching-contacts-actions">';
1174 $row = '';
1175 for ($i = 0; $i < count($contactLinks['rows']); $i++) {
1176 $row .= ' <tr> ';
1177 $row .= ' <td class="matching-contacts-name"> ';
9a00dcb4 1178 $row .= CRM_Utils_Array::value('display_name', $contactLinks['rows'][$i]);
6a488035
TO
1179 $row .= ' </td>';
1180 $row .= ' <td class="matching-contacts-email"> ';
9a00dcb4 1181 $row .= CRM_Utils_Array::value('primary_email', $contactLinks['rows'][$i]);
6a488035
TO
1182 $row .= ' </td>';
1183 $row .= ' <td class="action-items"> ';
9a00dcb4
TS
1184 $row .= CRM_Utils_Array::value('view', $contactLinks['rows'][$i]);
1185 $row .= CRM_Utils_Array::value('edit', $contactLinks['rows'][$i]);
6a488035
TO
1186 $row .= CRM_Utils_Array::value('merge', $contactLinks['rows'][$i]);
1187 $row .= ' </td>';
1188 $row .= ' </tr> ';
1189 }
1190
1191 $duplicateContactsLinks .= $row . '</table>';
1192 $duplicateContactsLinks .= ts("If you're sure this record is not a duplicate, click the 'Save Matching Contact' button below.");
1193
1194 $errors['_qf_default'] = $duplicateContactsLinks;
1195
6a488035
TO
1196 // let smarty know that there are duplicates
1197 $template = CRM_Core_Smarty::singleton();
1198 $template->assign('isDuplicate', 1);
1199 }
a7488080 1200 elseif (!empty($fields['_qf_Contact_refresh_dedupe'])) {
6a488035
TO
1201 // add a session message for no matching contacts
1202 CRM_Core_Session::setStatus(ts('No matching contact found.'), ts('None Found'), 'info');
1203 }
1204 }
1205 }
1206
86538308 1207 /**
fe482240 1208 * Use the form name to create the tpl file name.
86538308
EM
1209 *
1210 * @return string
86538308 1211 */
00be9182 1212 public function getTemplateFileName() {
6a488035
TO
1213 if ($this->_contactSubType) {
1214 $templateFile = "CRM/Contact/Form/Edit/SubType/{$this->_contactSubType}.tpl";
1215 $template = CRM_Core_Form::getTemplate();
1216 if ($template->template_exists($templateFile)) {
1217 return $templateFile;
1218 }
1219 }
1220 return parent::getTemplateFileName();
1221 }
1222
1223 /**
1224 * Parse all address blocks present in given params
77b97be7
EM
1225 * and return parse result for all address blocks,
1226 * This function either parse street address in to child
1227 * elements or build street address from child elements.
1228 *
5a4f6742
CW
1229 * @param array $params
1230 * of key value consist of address blocks.
77b97be7 1231 *
a6c01b45 1232 * @return array
b44e3f84 1233 * as array of success/fails for each address block
77b97be7 1234 */
00be9182 1235 public function parseAddress(&$params) {
be2fb01f 1236 $parseSuccess = $parsedFields = [];
6a488035
TO
1237 if (!is_array($params['address']) ||
1238 CRM_Utils_System::isNull($params['address'])
1239 ) {
1240 return $parseSuccess;
1241 }
1242
1243 foreach ($params['address'] as $instance => & $address) {
1244 $buildStreetAddress = FALSE;
1245 $parseFieldName = 'street_address';
be2fb01f 1246 foreach ([
69078420
SL
1247 'street_number',
1248 'street_name',
1249 'street_unit',
1250 ] as $fld) {
a7488080 1251 if (!empty($address[$fld])) {
6a488035
TO
1252 $parseFieldName = 'street_number';
1253 $buildStreetAddress = TRUE;
1254 break;
1255 }
1256 }
1257
1258 // main parse string.
1259 $parseString = CRM_Utils_Array::value($parseFieldName, $address);
1260
1261 // parse address field.
1262 $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($parseString);
1263
1264 if ($buildStreetAddress) {
1265 //hack to ignore spaces between number and suffix.
1266 //here user gives input as street_number so it has to
1267 //be street_number and street_number_suffix, but
1268 //due to spaces though preg detect string as street_name
1269 //consider it as 'street_number_suffix'.
1270 $suffix = $parsedFields['street_number_suffix'];
1271 if (!$suffix) {
1272 $suffix = $parsedFields['street_name'];
1273 }
1274 $address['street_number_suffix'] = $suffix;
1275 $address['street_number'] = $parsedFields['street_number'];
1276
1277 $streetAddress = NULL;
be2fb01f 1278 foreach ([
69078420
SL
1279 'street_number',
1280 'street_number_suffix',
1281 'street_name',
1282 'street_unit',
1283 ] as $fld) {
be2fb01f 1284 if (in_array($fld, [
353ffa53 1285 'street_name',
af9b09df 1286 'street_unit',
be2fb01f 1287 ])) {
6a488035
TO
1288 $streetAddress .= ' ';
1289 }
9f26d21a 1290 // CRM-17619 - if the street number suffix begins with a number, add a space
92ab8b24
HK
1291 $thesuffix = CRM_Utils_Array::value('street_number_suffix', $address);
1292 if ($fld === 'street_number_suffix' && $thesuffix) {
1293 if (ctype_digit(substr($thesuffix, 0, 1))) {
1294 $streetAddress .= ' ';
1295 }
5e59a285 1296 }
6a488035
TO
1297 $streetAddress .= CRM_Utils_Array::value($fld, $address);
1298 }
1299 $address['street_address'] = trim($streetAddress);
1300 $parseSuccess[$instance] = TRUE;
1301 }
1302 else {
1303 $success = TRUE;
1304 // consider address is automatically parseable,
1305 // when we should found street_number and street_name
8cc574cf 1306 if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) {
6a488035
TO
1307 $success = FALSE;
1308 }
1309
1310 // check for original street address string.
1311 if (empty($parseString)) {
1312 $success = TRUE;
1313 }
1314
1315 $parseSuccess[$instance] = $success;
1316
1317 // we do not reset element values, but keep what we've parsed
1318 // in case of partial matches: CRM-8378
1319
1320 // merge parse address in to main address block.
1321 $address = array_merge($address, $parsedFields);
1322 }
1323 }
1324
1325 return $parseSuccess;
1326 }
1327
1328 /**
100fef9d 1329 * Check parse result and if some address block fails then this
6a488035
TO
1330 * function return the status message for all address blocks.
1331 *
5a4f6742 1332 * @param array $parseResult
77c5b619 1333 * An array of address blk instance and its status.
6a488035 1334 *
72b3a70c
CW
1335 * @return null|string
1336 * $statusMsg string status message for all address blocks.
6a488035 1337 */
00be9182 1338 public static function parseAddressStatusMsg($parseResult) {
6a488035
TO
1339 $statusMsg = NULL;
1340 if (!is_array($parseResult) || empty($parseResult)) {
1341 return $statusMsg;
1342 }
1343
be2fb01f 1344 $parseFails = [];
6a488035
TO
1345 foreach ($parseResult as $instance => $success) {
1346 if (!$success) {
1347 $parseFails[] = self::ordinalNumber($instance);
1348 }
1349 }
1350
1351 if (!empty($parseFails)) {
1352 $statusMsg = ts("Complete street address(es) have been saved. However we were unable to split the address in the %1 address block(s) into address elements (street number, street name, street unit) due to an unrecognized address format. You can set the address elements manually by clicking 'Edit Address Elements' next to the Street Address field while in edit mode.",
be2fb01f 1353 [1 => implode(', ', $parseFails)]
6a488035
TO
1354 );
1355 }
1356
1357 return $statusMsg;
1358 }
1359
1360 /**
1361 * Convert normal number to ordinal number format.
1362 * like 1 => 1st, 2 => 2nd and so on...
1363 *
5a4f6742
CW
1364 * @param int $number
1365 * number to convert in to ordinal number.
6a488035 1366 *
72b3a70c
CW
1367 * @return string
1368 * ordinal number for given number.
6a488035 1369 */
00be9182 1370 public static function ordinalNumber($number) {
6a488035
TO
1371 if (empty($number)) {
1372 return NULL;
1373 }
1374
1375 $str = 'th';
1376 switch (floor($number / 10) % 10) {
1377 case 1:
1378 default:
1379 switch ($number % 10) {
1380 case 1:
1381 $str = 'st';
1382 break;
1383
1384 case 2:
1385 $str = 'nd';
1386 break;
1387
1388 case 3:
1389 $str = 'rd';
1390 break;
1391 }
1392 }
1393
1394 return "$number$str";
1395 }
1396
6a488035 1397}