Merge pull request #15822 from eileenmcnaughton/label
[civicrm-core.git] / CRM / Dedupe / Merger.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
f299f7db 6 | Copyright CiviCRM LLC (c) 2004-2020 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
f299f7db 31 * @copyright CiviCRM LLC (c) 2004-2020
6a488035
TO
32 */
33class CRM_Dedupe_Merger {
6a488035 34
e0ef6999 35 /**
4f1f1f2a
CW
36 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
37 * FIXME: the sub-pages references by the URLs should
38 * be loaded dynamically on the merge form instead
e0ef6999
EM
39 * @return array
40 */
00be9182 41 public static function relTables() {
6a488035 42
641a8cb5 43 if (!isset(Civi::$statics[__CLASS__]['relTables'])) {
12d73bba 44
641a8cb5
J
45 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
46 // if the url can't be retrieved. A more standardised way to retrieve them is.
47 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
48 // we may need a different function when it is not known.
49 $title = $userRecordUrl = '';
50
51 $config = CRM_Core_Config::singleton();
52 if ($config->userSystem->is_drupal) {
53 $userRecordUrl = CRM_Utils_System::url('user/%ufid');
2c16165a 54 $title = ts('%1 User: %2; user id: %3', [
55 1 => $config->userFramework,
56 2 => '$ufname',
57 3 => '$ufid',
58 ]);
641a8cb5
J
59 }
60 elseif ($config->userFramework == 'Joomla') {
61 $userRecordUrl = $config->userSystem->getVersion() > 1.5 ? $config->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . '%ufid' : $config->userFrameworkBaseURL . "index2.php?option=com_users&view=user&task=edit&id[]=" . '%ufid';
2c16165a 62 $title = ts('%1 User: %2; user id: %3', [
63 1 => $config->userFramework,
64 2 => '$ufname',
65 3 => '$ufid',
66 ]);
641a8cb5 67 }
6a488035 68
2c16165a 69 $relTables = [
70 'rel_table_contributions' => [
6a488035 71 'title' => ts('Contributions'),
2c16165a 72 'tables' => [
73 'civicrm_contribution',
74 'civicrm_contribution_recur',
75 'civicrm_contribution_soft',
76 ],
6a488035 77 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
2c16165a 78 ],
79 'rel_table_contribution_page' => [
6a488035 80 'title' => ts('Contribution Pages'),
2c16165a 81 'tables' => ['civicrm_contribution_page'],
6a488035 82 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
2c16165a 83 ],
84 'rel_table_memberships' => [
6a488035 85 'title' => ts('Memberships'),
2c16165a 86 'tables' => [
87 'civicrm_membership',
88 'civicrm_membership_log',
89 'civicrm_membership_type',
90 ],
6a488035 91 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
2c16165a 92 ],
93 'rel_table_participants' => [
6a488035 94 'title' => ts('Participants'),
2c16165a 95 'tables' => ['civicrm_participant'],
6a488035 96 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
2c16165a 97 ],
98 'rel_table_events' => [
6a488035 99 'title' => ts('Events'),
2c16165a 100 'tables' => ['civicrm_event'],
6a488035 101 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
2c16165a 102 ],
103 'rel_table_activities' => [
6a488035 104 'title' => ts('Activities'),
2c16165a 105 'tables' => ['civicrm_activity', 'civicrm_activity_contact'],
6a488035 106 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
2c16165a 107 ],
108 'rel_table_relationships' => [
6a488035 109 'title' => ts('Relationships'),
2c16165a 110 'tables' => ['civicrm_relationship'],
6a488035 111 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
2c16165a 112 ],
113 'rel_table_custom_groups' => [
6a488035 114 'title' => ts('Custom Groups'),
2c16165a 115 'tables' => ['civicrm_custom_group'],
6a488035 116 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
2c16165a 117 ],
118 'rel_table_uf_groups' => [
6a488035 119 'title' => ts('Profiles'),
2c16165a 120 'tables' => ['civicrm_uf_group'],
6a488035 121 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
2c16165a 122 ],
123 'rel_table_groups' => [
6a488035 124 'title' => ts('Groups'),
2c16165a 125 'tables' => ['civicrm_group_contact'],
6a488035 126 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
2c16165a 127 ],
128 'rel_table_notes' => [
6a488035 129 'title' => ts('Notes'),
2c16165a 130 'tables' => ['civicrm_note'],
6a488035 131 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
2c16165a 132 ],
133 'rel_table_tags' => [
6a488035 134 'title' => ts('Tags'),
2c16165a 135 'tables' => ['civicrm_entity_tag'],
6a488035 136 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
2c16165a 137 ],
138 'rel_table_mailings' => [
6a488035 139 'title' => ts('Mailings'),
2c16165a 140 'tables' => [
141 'civicrm_mailing',
142 'civicrm_mailing_event_queue',
143 'civicrm_mailing_event_subscribe',
144 ],
f521f375 145 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
2c16165a 146 ],
147 'rel_table_cases' => [
6a488035 148 'title' => ts('Cases'),
2c16165a 149 'tables' => ['civicrm_case_contact'],
6a488035 150 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
2c16165a 151 ],
152 'rel_table_grants' => [
6a488035 153 'title' => ts('Grants'),
2c16165a 154 'tables' => ['civicrm_grant'],
6a488035 155 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
2c16165a 156 ],
157 'rel_table_pcp' => [
6a488035 158 'title' => ts('PCPs'),
2c16165a 159 'tables' => ['civicrm_pcp'],
6a488035 160 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
2c16165a 161 ],
162 'rel_table_pledges' => [
6a488035 163 'title' => ts('Pledges'),
2c16165a 164 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'],
6a488035 165 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
2c16165a 166 ],
167 'rel_table_users' => [
6a488035 168 'title' => $title,
2c16165a 169 'tables' => ['civicrm_uf_match'],
6a488035 170 'url' => $userRecordUrl,
2c16165a 171 ],
172 ];
6a488035 173
76c53278
CW
174 $relTables += self::getMultiValueCustomSets('relTables');
175
6a488035
TO
176 // Allow hook_civicrm_merge() to adjust $relTables
177 CRM_Utils_Hook::merge('relTables', $relTables);
641a8cb5
J
178
179 // Cache the results in a static variable
180 Civi::$statics[__CLASS__]['relTables'] = $relTables;
6a488035 181 }
641a8cb5
J
182
183 return Civi::$statics[__CLASS__]['relTables'];
6a488035
TO
184 }
185
186 /**
fe482240 187 * Returns the related tables groups for which a contact has any info entered.
ad37ac8e 188 *
189 * @param int $cid
190 *
191 * @return array
6a488035 192 */
00be9182 193 public static function getActiveRelTables($cid) {
6a488035 194 $cid = (int) $cid;
2c16165a 195 $groups = [];
6a488035
TO
196
197 $relTables = self::relTables();
198 $cidRefs = self::cidRefs();
199 $eidRefs = self::eidRefs();
200 foreach ($relTables as $group => $params) {
2c16165a 201 $sqls = [];
6a488035
TO
202 foreach ($params['tables'] as $table) {
203 if (isset($cidRefs[$table])) {
204 foreach ($cidRefs[$table] as $field) {
205 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
206 }
207 }
208 if (isset($eidRefs[$table])) {
209 foreach ($eidRefs[$table] as $entityTable => $entityId) {
210 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
211 }
212 }
213 foreach ($sqls as $sql) {
214 if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
215 $groups[] = $group;
216 }
217 }
218 }
219 }
220 return array_unique($groups);
221 }
222
223 /**
3ae0ae3d 224 * Get array tables and fields that reference civicrm_contact.id.
225 *
e3e87c73 226 * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call.
227 * The entityTypes hook is the recommended way to add tables to this result.
3ae0ae3d 228 *
e3e87c73 229 * I thought about adding another hook to alter tableReferences but decided it was unclear if there
230 * are use cases not covered by entityTables and instead we should wait & see.
6a488035 231 */
00be9182 232 public static function cidRefs() {
e31c3de1 233 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) {
234 return \Civi::$statics[__CLASS__]['contact_references'];
235 }
64b3569d 236
e3e87c73 237 $contactReferences = $coreReferences = CRM_Core_DAO::getReferencesToContactTable();
6a488035 238
e31c3de1 239 CRM_Utils_Hook::merge('cidRefs', $contactReferences);
e3e87c73 240 if ($contactReferences !== $coreReferences) {
2c16165a 241 Civi::log()
242 ->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", ['civi.tag' => 'deprecated']);
e3e87c73 243 }
e31c3de1 244 \Civi::$statics[__CLASS__]['contact_references'] = $contactReferences;
245 return \Civi::$statics[__CLASS__]['contact_references'];
6a488035
TO
246 }
247
248 /**
249 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
250 */
00be9182 251 public static function eidRefs() {
6a488035
TO
252 static $eidRefs;
253 if (!$eidRefs) {
254 // FIXME: this should be generated dynamically from the schema
255 // tables that reference contacts with entity_{id,table}
2c16165a 256 $eidRefs = [
257 'civicrm_acl' => ['entity_table' => 'entity_id'],
258 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'],
259 'civicrm_entity_file' => ['entity_table' => 'entity_id'],
260 'civicrm_log' => ['entity_table' => 'entity_id'],
261 'civicrm_mailing_group' => ['entity_table' => 'entity_id'],
262 'civicrm_note' => ['entity_table' => 'entity_id'],
263 ];
6a488035
TO
264
265 // Allow hook_civicrm_merge() to adjust $eidRefs
266 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
267 }
268 return $eidRefs;
269 }
270
9da04f20 271 /**
fe482240 272 * Return tables using locations.
9da04f20 273 */
00be9182 274 public static function locTables() {
9da04f20
AS
275 static $locTables;
276 if (!$locTables) {
2c16165a 277 $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone'];
9da04f20
AS
278
279 // Allow hook_civicrm_merge() to adjust $locTables
280 CRM_Utils_Hook::merge('locTables', $locTables);
281 }
282 return $locTables;
283 }
284
76c53278
CW
285 /**
286 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
98997235
TO
287 * @param string $request
288 * 'relTables' or 'cidRefs'.
641a8cb5 289 * @return array
76c53278
CW
290 * @see CRM-13836
291 */
00be9182 292 public static function getMultiValueCustomSets($request) {
641a8cb5
J
293
294 if (!isset(Civi::$statics[__CLASS__]['multiValueCustomSets'])) {
2c16165a 295 $data = [
296 'relTables' => [],
297 'cidRefs' => [],
298 ];
299 $result = civicrm_api3('custom_group', 'get', [
76c53278 300 'is_multiple' => 1,
2c16165a 301 'extends' => [
302 'IN' => [
303 'Individual',
304 'Organization',
305 'Household',
306 'Contact',
307 ],
308 ],
309 'return' => ['id', 'title', 'table_name', 'style'],
310 ]);
22e263ad 311 foreach ($result['values'] as $custom) {
2c16165a 312 $data['cidRefs'][$custom['table_name']] = ['entity_id'];
76c53278 313 $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
2c16165a 314 $data['relTables']['rel_table_custom_' . $custom['id']] = [
76c53278 315 'title' => $custom['title'],
2c16165a 316 'tables' => [$custom['table_name']],
76c53278 317 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
2c16165a 318 ];
76c53278 319 }
641a8cb5
J
320
321 // Store the result in a static variable cache
322 Civi::$statics[__CLASS__]['multiValueCustomSets'] = $data;
76c53278 323 }
641a8cb5
J
324
325 return Civi::$statics[__CLASS__]['multiValueCustomSets'][$request];
76c53278
CW
326 }
327
6a488035
TO
328 /**
329 * Tables which require custom processing should declare functions to call here.
330 * Doing so will override normal processing.
331 */
00be9182 332 public static function cpTables() {
6a488035
TO
333 static $tables;
334 if (!$tables) {
2c16165a 335 $tables = [
336 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'],
337 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'],
6a488035 338 // Empty array == do nothing - this table is handled by mergeGroupContact
2c16165a 339 'civicrm_subscription_history' => [],
340 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'],
341 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'],
342 ];
6a488035
TO
343 }
344 return $tables;
345 }
346
347 /**
100fef9d 348 * Return payment related table.
6a488035 349 */
00be9182 350 public static function paymentTables() {
6a488035
TO
351 static $tables;
352 if (!$tables) {
2c16165a 353 $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant'];
6a488035 354 }
6a488035
TO
355 return $tables;
356 }
357
358 /**
100fef9d 359 * Return payment update Query.
54957108 360 *
361 * @param string $tableName
362 * @param int $mainContactId
363 * @param int $otherContactId
364 *
365 * @return array
6a488035 366 */
00be9182 367 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
2c16165a 368 $sqls = [];
6a488035
TO
369 if (!$tableName || !$mainContactId || !$otherContactId) {
370 return $sqls;
371 }
372
373 $paymentTables = self::paymentTables();
374 if (!in_array($tableName, $paymentTables)) {
375 return $sqls;
376 }
377
378 switch ($tableName) {
379 case 'civicrm_pledge':
380 $sqls[] = "
381 UPDATE IGNORE civicrm_contribution contribution
382INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
383INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
384 SET contribution.contact_id = $mainContactId
385 WHERE pledge.contact_id = $otherContactId";
386 break;
387
388 case 'civicrm_membership':
389 $sqls[] = "
390 UPDATE IGNORE civicrm_contribution contribution
391INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
392INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
393 SET contribution.contact_id = $mainContactId
394 WHERE membership.contact_id = $otherContactId";
395 break;
396
397 case 'civicrm_participant':
398 $sqls[] = "
399 UPDATE IGNORE civicrm_contribution contribution
400INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
401INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
402 SET contribution.contact_id = $mainContactId
403 WHERE participant.contact_id = $otherContactId";
404 break;
405 }
406
407 return $sqls;
408 }
409
e0ef6999 410 /**
100fef9d
CW
411 * @param int $mainId
412 * @param int $otherId
413 * @param string $tableName
e0ef6999
EM
414 * @param array $tableOperations
415 * @param string $mode
416 *
417 * @return array
418 */
2c16165a 419 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') {
420 $sqls = [];
6a488035
TO
421 if (!$tableName || !$mainId || !$otherId) {
422 return $sqls;
423 }
424
6a488035
TO
425 switch ($tableName) {
426 case 'civicrm_membership':
d58a19a1
TO
427 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
428 break;
429 }
430 if ($mode == 'add') {
431 $sqls[] = "
6a488035
TO
432DELETE membership1.* FROM civicrm_membership membership1
433 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
434 AND membership1.contact_id = {$mainId}
435 AND membership2.contact_id = {$otherId} ";
d58a19a1
TO
436 }
437 if ($mode == 'payment') {
438 $sqls[] = "
6a488035
TO
439DELETE contribution.* FROM civicrm_contribution contribution
440INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
441INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
442 AND membership1.contact_id = {$mainId}
443INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
444 AND membership2.contact_id = {$otherId}";
d58a19a1
TO
445 }
446 break;
6a488035
TO
447
448 case 'civicrm_uf_match':
449 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
b44e3f84 450 // failing to meet intended result. Therefore we introduce this additional query:
6a488035
TO
451 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
452 break;
453 }
454
455 return $sqls;
456 }
457
4099a9c5
AP
458 /**
459 * Based on the provided two contact_ids and a set of tables, remove the
460 * belongings of the other contact and of their relations.
461 *
462 * @param int $otherID
463 * @param bool $tables
464 */
465 public static function removeContactBelongings($otherID, $tables) {
466 // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
467 if (in_array("civicrm_membership", $tables)) {
468 $membershipIDs = CRM_Utils_Array::collect('id',
469 CRM_Utils_Array::value('values',
2c16165a 470 civicrm_api3("Membership", "get", [
518fa0ee
SL
471 "contact_id" => $otherID,
472 "return" => "id",
473 ])
e122e55d
TO
474 )
475 );
4099a9c5
AP
476
477 if (!empty($membershipIDs)) {
2c16165a 478 civicrm_api3("Membership", "get", [
479 'owner_membership_id' => ['IN' => $membershipIDs],
480 'api.Membership.delete' => ['id' => '$value.id'],
481 ]);
4099a9c5
AP
482 }
483 }
484 }
485
6a488035
TO
486 /**
487 * Based on the provided two contact_ids and a set of tables, move the
488 * belongings of the other contact to the main one.
489 *
54957108 490 * @param int $mainId
491 * @param int $otherId
492 * @param bool $tables
493 * @param array $tableOperations
b35800bd 494 * @param array $customTableToCopyFrom
6a488035 495 */
2c16165a 496 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = [], $customTableToCopyFrom = NULL) {
6a488035
TO
497 $cidRefs = self::cidRefs();
498 $eidRefs = self::eidRefs();
499 $cpTables = self::cpTables();
500 $paymentTables = self::paymentTables();
501
b35800bd 502 // getting all custom tables
2c16165a 503 $customTables = [];
ae2346d4 504 if ($customTableToCopyFrom !== NULL) {
e3e87c73 505 // @todo this duplicates cidRefs?
506 CRM_Core_DAO::appendCustomTablesExtendingContacts($customTables);
4c7e5001 507 CRM_Core_DAO::appendCustomContactReferenceFields($customTables);
674920ca 508 $customTables = array_keys($customTables);
6a488035 509 }
674920ca
ES
510
511 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
0556db5d
CR
512
513 // if there aren't any specific tables, don't affect the ones handled by relTables()
514 // also don't affect tables in locTables() CRM-15658
515 $relTables = self::relTables();
516 $handled = self::locTables();
517
518 foreach ($relTables as $params) {
519 $handled = array_merge($handled, $params['tables']);
6a488035 520 }
0556db5d 521 $affected = array_diff($affected, $handled);
e3159b07 522 $affected = array_unique(array_merge($affected, $tables));
6a488035
TO
523
524 $mainId = (int) $mainId;
525 $otherId = (int) $otherId;
06f4969c 526 $multi_value_tables = array_keys(CRM_Dedupe_Merger::getMultiValueCustomSets('cidRefs'));
6a488035 527
2c16165a 528 $sqls = [];
6a488035 529 foreach ($affected as $table) {
06f4969c 530 // skipping non selected single-value custom table's value migration
531 if (!in_array($table, $multi_value_tables)) {
532 if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
4c7e5001
PF
533 if (isset($cidRefs[$table]) && ($delCol = array_search('entity_id', $cidRefs[$table])) !== FALSE) {
534 // remove entity_id from the field list
535 unset($cidRefs[$table][$delCol]);
536 }
06f4969c 537 }
b35800bd 538 }
674920ca 539
6a488035
TO
540 // Call custom processing function for objects that require it
541 if (isset($cpTables[$table])) {
542 foreach ($cpTables[$table] as $className => $fnName) {
43d4ad93 543 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
6a488035
TO
544 }
545 // Skip normal processing
546 continue;
547 }
b3fdbf3d 548
6a488035
TO
549 // use UPDATE IGNORE + DELETE query pair to skip on situations when
550 // there's a UNIQUE restriction on ($field, some_other_field) pair
551 if (isset($cidRefs[$table])) {
552 foreach ($cidRefs[$table] as $field) {
553 // carry related contributions CRM-5359
554 if (in_array($table, $paymentTables)) {
6a488035
TO
555 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
556 $sqls = array_merge($sqls, $paymentSqls);
71560cf3
C
557
558 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
559 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
560 $sqls = array_merge($sqls, $payOprSqls);
561 }
6a488035
TO
562 }
563
564 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
565 $sqls = array_merge($sqls, $preOperationSqls);
566
4c7e5001
PF
567 if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self::customRecordExists($mainId, $table, $field) && $field == 'entity_id') {
568 // this is the entity_id column of a custom field group where:
569 // - the custom table should be copied as indicated by $customTableToCopyFrom
570 // e.g. because a field in the group was selected in a form
571 // - AND no record exists yet for the $mainId contact
572 // we only do this for column "entity_id" as we wouldn't want to
573 // run this INSERT for ContactReference fields
ae2346d4
CR
574 $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
575 }
6a488035
TO
576 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
577 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
578 }
579 }
ae2346d4 580
6a488035
TO
581 if (isset($eidRefs[$table])) {
582 foreach ($eidRefs[$table] as $entityTable => $entityId) {
583 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
584 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
585 }
586 }
587 }
588
589 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
590 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
591
6a488035 592 foreach ($sqls as $sql) {
2c16165a 593 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE);
6a488035 594 }
0556db5d 595 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
6a488035
TO
596 }
597
4f751978
CR
598 /**
599 * Given a contact ID, will check if a record exists in given table.
600 *
601 * @param $contactID
602 * @param $table
603 * @param $idField
604 * Field where the contact's ID is stored in the table
605 *
606 * @return bool
607 * True if a record is found for the given contact ID, false otherwise
608 */
ae2346d4
CR
609 private static function customRecordExists($contactID, $table, $idField) {
610 $sql = "
611 SELECT COUNT(*) AS count
612 FROM $table
613 WHERE $idField = $contactID
614 ";
615 $dbResult = CRM_Core_DAO::executeQuery($sql);
616 $dbResult->fetch();
617
618 if ($dbResult->count > 0) {
ee3b1d86 619 return TRUE;
ae2346d4
CR
620 }
621
ee3b1d86 622 return FALSE;
ae2346d4
CR
623 }
624
6a488035 625 /**
4eea8606 626 * Load all non-empty fields for the contacts
b3fdbf3d 627 *
98997235
TO
628 * @param array $main
629 * Contact details.
630 * @param array $other
631 * Contact details.
6a488035 632 *
77b97be7 633 * @return array
6a488035 634 */
4eea8606 635 public static function retrieveFields($main, $other) {
2c16165a 636 $result = [
637 'contact' => [],
638 'custom' => [],
639 ];
16254ae1 640 foreach (self::getContactFields() as $validField) {
eb61dc07
J
641 // CRM-17556 Get all non-empty fields, to make comparison easier
642 if (!empty($main[$validField]) || !empty($other[$validField])) {
6a488035
TO
643 $result['contact'][] = $validField;
644 }
645 }
646
647 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
648 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
649 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
650 foreach ($keys as $key) {
76c53278
CW
651 // Exclude multi-value fields CRM-13836
652 if (strpos($key, '_')) {
653 continue;
654 }
6a488035
TO
655 $key1 = CRM_Utils_Array::value($key, $mainEvs);
656 $key2 = CRM_Utils_Array::value($key, $otherEvs);
26b7ff28 657 // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
658 // However I can't think of a case where an empty string is more meaningful than null
659 // or where it would be FALSE or something else nullish.
660 $valuesToIgnore = [NULL, '', []];
661 if (!in_array($key1, $valuesToIgnore, TRUE) || !in_array($key2, $valuesToIgnore, TRUE)) {
6a488035
TO
662 $result['custom'][] = $key;
663 }
664 }
665 return $result;
666 }
667
668 /**
100fef9d 669 * Batch merge a set of contacts based on rule-group and group.
6a488035 670 *
98997235
TO
671 * @param int $rgid
672 * Rule group id.
673 * @param int $gid
674 * Group id.
675 * @param string $mode
676 * Helps decide how to behave when there are conflicts.
15a793bb
EM
677 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
678 * mode does a force merge.
f931b74c 679 * @param int $batchLimit number of merges to carry out in one batch.
680 * @param int $isSelected if records with is_selected column needs to be processed.
bb22928b 681 * Note the option of '2' is only used in conjunction with $redirectForPerformance
b5a6c6c5 682 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
683 * out in favour of explicitly passing in $reloadCacheIfEmpty
6a488035 684 *
e23e26ec 685 * @param array $criteria
686 * Criteria to use in the filter.
687 *
3058f4d9 688 * @param bool $checkPermissions
689 * Respect logged in user permissions.
bb22928b 690 * @param bool|NULL $reloadCacheIfEmpty
691 * If not set explicitly this is calculated but it is preferred that it be set
692 * per comments on isSelected above.
3058f4d9 693 *
997a03fe 694 * @param int $searchLimit
695 * Limit on number of contacts to search for duplicates for.
696 * This means that if the limit is 1000 then only duplicates for the first 1000 contacts
697 * matching criteria will be found and batchMerged (the number of merges could be less than or greater than 100)
698 *
77b97be7 699 * @return array|bool
997a03fe 700 *
701 * @throws \CRM_Core_Exception
702 * @throws \CiviCRM_API3_Exception
6a488035 703 */
997a03fe 704 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL, $searchLimit = 0) {
63ef778e 705 $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
418ffc5b 706 if ($mode === 'aggressive' && $checkPermissions && !CRM_Core_Permission::check('force merge duplicate contacts')) {
707 throw new CRM_Core_Exception(ts('Insufficient permissions for aggressive mode batch merge'));
708 }
bb22928b 709 if (!isset($reloadCacheIfEmpty)) {
710 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
711 }
712 if ($isSelected !== 0 && $isSelected !== 1) {
713 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
714 $isSelected = NULL;
715 }
e3c42269 716 $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode == 'aggressive'), $criteria, $checkPermissions, $searchLimit);
6a488035 717
2c16165a 718 $cacheParams = [
997a03fe 719 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions, $searchLimit),
2988f5c7 720 // @todo stop passing these parameters in & instead calculate them in the merge function based
721 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
722 'join' => self::getJoinOnDedupeTable(),
ed3c1599 723 'where' => self::getWhereString($isSelected),
724 'limit' => (int) $batchLimit,
2c16165a 725 ];
d238756a 726 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
6a488035
TO
727 }
728
2ae26001 729 /**
730 * Get the string to join the prevnext cache to the dedupe table.
731 *
732 * @return string
733 * The join string to join prevnext cache on the dedupe table.
734 */
735 public static function getJoinOnDedupeTable() {
736 return "
737 LEFT JOIN civicrm_dedupe_exception de
738 ON (
739 pn.entity_id1 = de.contact_id1
740 AND pn.entity_id2 = de.contact_id2 )
741 ";
742 }
743
2988f5c7 744 /**
745 * Get where string for dedupe join.
746 *
2988f5c7 747 * @param bool $isSelected
748 *
749 * @return string
750 */
ed3c1599 751 protected static function getWhereString($isSelected) {
2988f5c7 752 $where = "de.id IS NULL";
753 if ($isSelected === 0 || $isSelected === 1) {
754 $where .= " AND pn.is_selected = {$isSelected}";
755 }
2988f5c7 756 return $where;
757 }
758
bc854509 759 /**
760 * Update the statistics for the merge set.
761 *
762 * @param string $cacheKeyString
763 * @param array $result
764 */
2c16165a 765 public static function updateMergeStats($cacheKeyString, $result = []) {
63ef778e 766 // gather latest stats
2c16165a 767 $merged = count($result['merged']);
63ef778e 768 $skipped = count($result['skipped']);
769
770 if ($merged <= 0 && $skipped <= 0) {
771 return;
772 }
773
774 // get previous stats
e13fa54b 775 $previousStats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
63ef778e 776 if (!empty($previousStats)) {
e13fa54b 777 if ($previousStats['merged']) {
778 $merged = $merged + $previousStats['merged'];
63ef778e 779 }
e13fa54b 780 if ($previousStats['skipped']) {
781 $skipped = $skipped + $previousStats['skipped'];
63ef778e 782 }
783 }
784
785 // delete old stats
786 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
787
788 // store the updated stats
2c16165a 789 $data = [
790 'merged' => $merged,
63ef778e 791 'skipped' => $skipped,
2c16165a 792 ];
63ef778e 793 $data = CRM_Core_DAO::escapeString(serialize($data));
794
e1c519d7 795 CRM_Core_BAO_PrevNextCache::setItem('civicrm_contact', 0, 0, $cacheKeyString . '_stats', $data);
63ef778e 796 }
797
ae6455b2 798 /**
799 * Delete information about merges for the given string.
800 *
801 * @param $cacheKeyString
802 */
f931b74c 803 public static function resetMergeStats($cacheKeyString) {
ae6455b2 804 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
63ef778e 805 }
806
bc854509 807 /**
808 * Get merge outcome statistics.
809 *
810 * @param string $cacheKeyString
811 *
812 * @return array
813 * Array of how many were merged and how many were skipped.
e13fa54b 814 *
815 * @throws \CiviCRM_API3_Exception
bc854509 816 */
f931b74c 817 public static function getMergeStats($cacheKeyString) {
e13fa54b 818 $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values'];
63ef778e 819 if (!empty($stats)) {
e13fa54b 820 return $stats[0]['data'];
63ef778e 821 }
e13fa54b 822 return [];
63ef778e 823 }
824
bc854509 825 /**
826 * Get merge statistics message.
827 *
3743fd3d 828 * @param array $stats
bc854509 829 *
830 * @return string
831 */
3743fd3d
CW
832 public static function getMergeStatsMsg($stats) {
833 $msg = '';
63ef778e 834 if (!empty($stats['merged'])) {
2c16165a 835 $msg = '<p>' . ts('One contact merged.', [
518fa0ee
SL
836 'count' => $stats['merged'],
837 'plural' => '%count contacts merged.',
838 ]) . '</p>';
63ef778e 839 }
840 if (!empty($stats['skipped'])) {
2c16165a 841 $msg .= '<p>' . ts('One contact was skipped.', [
518fa0ee
SL
842 'count' => $stats['skipped'],
843 'plural' => '%count contacts were skipped.',
844 ]) . '</p>';
63ef778e 845 }
846 return $msg;
847 }
848
6a488035 849 /**
100fef9d 850 * Merge given set of contacts. Performs core operation.
6a488035 851 *
98997235
TO
852 * @param array $dupePairs
853 * Set of pair of contacts for whom merge is to be done.
854 * @param array $cacheParams
855 * Prev-next-cache params based on which next pair of contacts are computed.
6a488035 856 * Generally used with batch-merge.
98997235
TO
857 * @param string $mode
858 * Helps decide how to behave when there are conflicts.
6a488035
TO
859 * A 'safe' value skips the merge if there are any un-resolved conflicts.
860 * Does a force merge otherwise (aggressive mode).
6a488035 861 *
77b97be7 862 * @param bool $redirectForPerformance
3058f4d9 863 * Redirect to a url for batch processing.
864 *
865 * @param bool $checkPermissions
866 * Respect logged in user permissions.
77b97be7
EM
867 *
868 * @return array|bool
b068bfde 869 *
870 * @throws \API_Exception
871 * @throws \CRM_Core_Exception
872 * @throws \CiviCRM_API3_Exception
6a488035 873 */
2c16165a 874 public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe',
875 $redirectForPerformance = FALSE, $checkPermissions = TRUE
6a488035
TO
876 ) {
877 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
2c16165a 878 $resultStats = ['merged' => [], 'skipped' => []];
6a488035
TO
879
880 // we don't want dupe caching to get reset after every-merge, and therefore set the
0626851e 881 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
2c16165a 882 $deletedContacts = [];
6a488035
TO
883
884 while (!empty($dupePairs)) {
78272750 885 foreach ($dupePairs as $index => $dupes) {
886 if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) {
887 unset($dupePairs[$index]);
888 continue;
889 }
b068bfde 890 if (($result = self::dedupePair($dupes, $mode, $checkPermissions, $cacheKeyString)) === FALSE) {
891 unset($dupePairs[$index]);
892 continue;
893 }
894 if (!empty($result['merged'])) {
895 $deletedContacts[] = $result['merged'][0]['other_id'];
896 $resultStats['merged'][] = ($result['merged'][0]);
897 }
898 else {
899 $resultStats['skipped'][] = ($result['skipped'][0]);
6a488035 900 }
6a488035
TO
901 }
902
903 if ($cacheKeyString && !$redirectForPerformance) {
904 // retrieve next pair of dupes
2988f5c7 905 // @todo call getDuplicatePairs.
6a488035
TO
906 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
907 $cacheParams['join'],
66eceb0b 908 $cacheParams['where'],
909 0,
ed3c1599 910 $cacheParams['limit'],
2c16165a 911 [],
66eceb0b 912 '',
913 FALSE
6a488035
TO
914 );
915 }
916 else {
917 // do not proceed. Terminate the loop
918 unset($dupePairs);
919 }
920 }
63ef778e 921
922 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
6a488035
TO
923 return $resultStats;
924 }
925
926 /**
927 * A function which uses various rules / algorithms for choosing which contact to bias to
928 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
929 *
98997235
TO
930 * @param int $mainId
931 * Main contact with whom merge has to happen.
932 * @param int $otherId
933 * Duplicate contact which would be deleted after merge operation.
934 * @param array $migrationInfo
935 * Array of information about which elements to merge.
936 * @param string $mode
937 * Helps decide how to behave when there are conflicts.
13919cf8
J
938 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
939 * - Does a force merge otherwise (aggressive mode).
6a488035 940 *
ad37ac8e 941 * @param array $conflicts
a2abc387 942 * An empty array to be filed with conflict information.
ad37ac8e 943 *
77b97be7 944 * @return bool
ffa59d18 945 *
946 * @throws \CRM_Core_Exception
947 * @throws \CiviCRM_API3_Exception
948 * @throws \API_Exception
6a488035 949 */
2c16165a 950 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) {
0971143c 951
a2abc387 952 $conflicts = self::getConflicts($migrationInfo, $mainId, $otherId, $mode);
6a488035
TO
953
954 if (!empty($conflicts)) {
fd630ef9 955 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
a2abc387 956 return (bool) $migrationInfo['skip_merge'];
6a488035
TO
957 }
958 return FALSE;
959 }
960
d48ad2c0 961 /**
962 * Compare 2 addresses to see if they are the same.
963 *
964 * @param array $mainAddress
965 * @param array $comparisonAddress
966 *
967 * @return bool
968 */
518fa0ee 969 public static function locationIsSame($mainAddress, $comparisonAddress) {
ffa59d18 970 $keysToIgnore = self::ignoredFields();
d48ad2c0 971 foreach ($comparisonAddress as $field => $value) {
972 if (in_array($field, $keysToIgnore)) {
973 continue;
974 }
00443529 975 if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
d48ad2c0 976 return FALSE;
977 }
978 }
979 return TRUE;
980 }
981
34917198
J
982 /**
983 * A function to build an array of information about location blocks that is
984 * required when merging location fields
985 *
986 * @return array
987 */
988 public static function getLocationBlockInfo() {
2c16165a 989 $locationBlocks = [
990 'address' => [
34917198
J
991 'label' => 'Address',
992 'displayField' => 'display',
993 'sortString' => 'location_type_id',
994 'hasLocation' => TRUE,
995 'hasType' => FALSE,
2c16165a 996 ],
997 'email' => [
34917198 998 'label' => 'Email',
2a7e1ddc 999 'displayField' => 'display',
34917198
J
1000 'sortString' => 'location_type_id',
1001 'hasLocation' => TRUE,
1002 'hasType' => FALSE,
2c16165a 1003 ],
1004 'im' => [
34917198
J
1005 'label' => 'IM',
1006 'displayField' => 'name',
1007 'sortString' => 'location_type_id,provider_id',
1008 'hasLocation' => TRUE,
1009 'hasType' => 'provider_id',
2c16165a 1010 ],
1011 'phone' => [
34917198
J
1012 'label' => 'Phone',
1013 'displayField' => 'phone',
1014 'sortString' => 'location_type_id,phone_type_id',
1015 'hasLocation' => TRUE,
1016 'hasType' => 'phone_type_id',
2c16165a 1017 ],
1018 'website' => [
34917198
J
1019 'label' => 'Website',
1020 'displayField' => 'url',
1021 'sortString' => 'website_type_id',
1022 'hasLocation' => FALSE,
1023 'hasType' => 'website_type_id',
2c16165a 1024 ],
1025 ];
34917198
J
1026 return $locationBlocks;
1027 }
1028
6a488035
TO
1029 /**
1030 * A function to build an array of information required by merge function and the merge UI.
1031 *
98997235
TO
1032 * @param int $mainId
1033 * Main contact with whom merge has to happen.
1034 * @param int $otherId
1035 * Duplicate contact which would be deleted after merge operation.
201057c0 1036 * @param bool $checkPermissions
1037 * Should the logged in user's permissions be ignore. Setting this to false is
1038 * highly risky as it could cause data to be lost due to conflicts not showing up.
1039 * OTOH there is a risk a merger might view custom data they do not have permission to.
1040 * Hence for now only making this really explicit and making it reflect perms in
1041 * an api call.
1042 *
1043 * @todo review permissions issue!
6a488035 1044 *
77b97be7 1045 * @return array|bool|int
1e3e0eed
J
1046 *
1047 * rows => An array of arrays, each is row of merge information for the table
1048 * Format: move_fieldname, eg: move_contact_type
1049 * main => Value associated with the main contact
1050 * other => Value associated with the other contact
1051 * title => The title of the field to display in the merge table
1052 *
1053 * elements => An array of form elements for the merge UI
1054 *
1055 * rel_table_elements => An array of form elements for the merge UI for
1056 * entities related to the contact (eg: checkbox to move 'mailings')
1057 *
1e3e0eed
J
1058 * rel_tables => Stores the tables that have related entities for the contact
1059 * for example mailings, groups
1060 *
1061 * main_details => An array of core contact field values, eg: first_name, etc.
1062 * location_blocks => An array of location block data for the main contact
1063 * stored as the 'result' of an API call.
1064 * eg: main_details['location_blocks']['address'][0]['id']
1065 * eg: main_details['location_blocks']['email'][1]['id']
1066 *
1067 * other_details => As above, but for the 'other' contact
1068 *
1069 * migration_info => Stores the 'default' merge actions for each field which
1070 * is used when programatically merging contacts. It contains instructions
1071 * to move all fields from the 'other' contact to the 'main' contact, as
1072 * though the form had been submitted with those options.
1073 *
3058f4d9 1074 * @throws \CRM_Core_Exception
1075 * @throws \CiviCRM_API3_Exception
1076 * @throws \Exception
6a488035 1077 */
201057c0 1078 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
6a488035 1079 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
74a6069d 1080 $fields = self::getMergeFieldsMetadata();
6a488035 1081
fcc3d8ee 1082 $main = self::getMergeContactDetails($mainId);
1083 $other = self::getMergeContactDetails($otherId);
6a488035 1084
4eea8606 1085 $compareFields = self::retrieveFields($main, $other);
6a488035 1086
2c16165a 1087 $rows = $elements = $relTableElements = $migrationInfo = [];
6a488035 1088
4eea8606 1089 foreach ($compareFields['contact'] as $field) {
4d5f18cc 1090 if ($field == 'contact_sub_type') {
1091 // CRM-15681 don't display sub-types in UI
1092 continue;
1093 }
2fd72602 1094 $rows["move_$field"]['main'] = self::getFieldValueAndLabel($field, $main)['label'];
1095 $rows["move_$field"]['other'] = self::getFieldValueAndLabel($field, $other)['label'];
1096
bdc6e6ee 1097 $value = self::getFieldValueAndLabel($field, $other)['value'];
1098 //CRM-14334
1099 if ($value === NULL || $value == '') {
1100 $value = 'null';
1101 }
1102 if ($value === 0 or $value === '0') {
1103 $value = $qfZeroBug;
1104 }
1105 if (is_array($value) && empty($value[1])) {
1106 $value[1] = NULL;
1107 }
13919cf8 1108
bdc6e6ee 1109 // Display a checkbox to migrate, only if the values are different
1110 if ($value != $main[$field]) {
1111 $elements[] = [
3d1d395a 1112 0 => 'advcheckbox',
1113 1 => "move_$field",
1114 2 => NULL,
1115 3 => NULL,
1116 4 => NULL,
1117 5 => $value,
1118 'is_checked' => (!isset($main[$field]) || $main[$field] === ''),
bdc6e6ee 1119 ];
1120 }
13919cf8 1121
bdc6e6ee 1122 $migrationInfo["move_$field"] = $value;
6a488035
TO
1123 $rows["move_$field"]['title'] = $fields[$field]['title'];
1124 }
1125
eb61dc07
J
1126 // Handle location blocks.
1127 // @todo OpenID not in API yet, so is not supported here.
65a35632 1128
087f00ec 1129 // Set up useful information about the location blocks
34917198 1130 $locationBlocks = self::getLocationBlockInfo();
087f00ec 1131
1a90ac89 1132 $locations = ['main' => [], 'other' => []];
6a488035 1133
087f00ec 1134 foreach ($locationBlocks as $blockName => $blockInfo) {
6a488035 1135
087f00ec
J
1136 // Collect existing fields from both 'main' and 'other' contacts first
1137 // This allows us to match up location/types when building the table rows
1a90ac89 1138 $locations['main'][$blockName] = self::buildLocationBlockForContact($mainId, $blockInfo, $blockName);
1139 $locations['other'][$blockName] = self::buildLocationBlockForContact($otherId, $blockInfo, $blockName);
6a488035 1140
087f00ec
J
1141 // Now, build the table rows appropriately, based off the information on
1142 // the 'other' contact
34917198
J
1143 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1144 foreach ($locations['other'][$blockName] as $count => $value) {
6a488035 1145
087f00ec 1146 $displayValue = $value[$blockInfo['displayField']];
65a35632 1147
087f00ec
J
1148 // Add this value to the table rows
1149 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
65a35632 1150
087f00ec
J
1151 // CRM-17556 Only display 'main' contact value if it's the same location + type
1152 // Look it up from main values...
65a35632 1153
087f00ec
J
1154 $lookupLocation = FALSE;
1155 if ($blockInfo['hasLocation']) {
1156 $lookupLocation = $value['location_type_id'];
1157 }
65a35632 1158
087f00ec
J
1159 $lookupType = FALSE;
1160 if ($blockInfo['hasType']) {
13cc4cac 1161 $lookupType = CRM_Utils_Array::value($blockInfo['hasType'], $value);
087f00ec 1162 }
65a35632 1163
34917198
J
1164 // Hold ID of main contact's matching block
1165 $mainContactBlockId = 0;
1166
087f00ec
J
1167 if (!empty($locations['main'][$blockName])) {
1168 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1169 // No location/type, or matching location and type
1170 if (
1171 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
1172 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
1173 ) {
34917198 1174 // Set this value as the default against the 'other' contact value
087f00ec 1175 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
041d6d6b 1176 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
86b14b59 1177 $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
34917198 1178 $mainContactBlockId = $mainValueCheck['id'];
087f00ec
J
1179 break;
1180 }
6a488035 1181 }
087f00ec 1182 }
65a35632 1183
087f00ec 1184 // Add checkbox to migrate data from 'other' to 'main'
2c16165a 1185 $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
65a35632 1186
abd0b852 1187 // Add checkbox to set the 'other' location as primary
2c16165a 1188 $elements[] = [
1189 'advcheckbox',
1190 "location_blocks[$blockName][$count][set_other_primary]",
1191 NULL,
1192 ts('Set as primary'),
1193 ];
abd0b852 1194
087f00ec
J
1195 // Flag up this field to skipMerge function (@todo: do we need to?)
1196 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
65a35632 1197
34917198 1198 // Add a hidden field to store the ID of the target main contact block
2c16165a 1199 $elements[] = [
1200 'hidden',
1201 "location_blocks[$blockName][$count][mainContactBlockId]",
1202 $mainContactBlockId,
1203 ];
34917198 1204
087f00ec
J
1205 // Setup variables
1206 $thisTypeId = FALSE;
1207 $thisLocId = FALSE;
65a35632 1208
087f00ec
J
1209 // Provide a select drop-down for the location's location type
1210 // eg: Home, Work...
65a35632 1211
087f00ec
J
1212 if ($blockInfo['hasLocation']) {
1213
5b28be84 1214 // Load the location options for this entity
2c16165a 1215 $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
5b28be84 1216
087f00ec
J
1217 $thisLocId = $value['location_type_id'];
1218
1219 // Put this field's location type at the top of the list
5b28be84 1220 $tmpIdList = $locationOptions['values'];
2c16165a 1221 $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
087f00ec
J
1222 unset($tmpIdList[$thisLocId]);
1223
1224 // Add the element
2c16165a 1225 $elements[] = [
eb61dc07 1226 'select',
972947a7 1227 "location_blocks[$blockName][$count][locTypeId]",
eb61dc07 1228 NULL,
087f00ec 1229 $defaultLocId + $tmpIdList,
2c16165a 1230 ];
087f00ec
J
1231
1232 // Add the relevant information to the $migrationInfo
1233 // Keep location-type-id same as that of other-contact
1234 // @todo Check this logic out
1235 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
abb422f9 1236 if ($blockName != 'address') {
2c16165a 1237 $elements[] = [
1238 'advcheckbox',
1239 "location_blocks[{$blockName}][$count][operation]",
1240 NULL,
1241 ts('Add new'),
1242 ];
087f00ec 1243 // always use add operation
abb422f9 1244 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
6a488035 1245 }
087f00ec 1246
6a488035 1247 }
6a488035 1248
087f00ec
J
1249 // Provide a select drop-down for the location's type/provider
1250 // eg websites: Google+, Facebook...
1251
087f00ec
J
1252 if ($blockInfo['hasType']) {
1253
5b28be84 1254 // Load the type options for this entity
2c16165a 1255 $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
5b28be84 1256
13cc4cac 1257 $thisTypeId = CRM_Utils_Array::value($blockInfo['hasType'], $value);
087f00ec
J
1258
1259 // Put this field's location type at the top of the list
5b28be84 1260 $tmpIdList = $typeOptions['values'];
2c16165a 1261 $defaultTypeId = [$thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList)];
087f00ec
J
1262 unset($tmpIdList[$thisTypeId]);
1263
1264 // Add the element
2c16165a 1265 $elements[] = [
65a35632 1266 'select',
972947a7 1267 "location_blocks[$blockName][$count][typeTypeId]",
65a35632 1268 NULL,
087f00ec 1269 $defaultTypeId + $tmpIdList,
2c16165a 1270 ];
65a35632 1271
1e3e0eed 1272 // Add the information to the migrationInfo
34917198 1273 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
65a35632 1274
6a488035 1275 }
087f00ec
J
1276
1277 // Set the label for this row
34917198
J
1278 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
1279 if (!empty($thisLocId)) {
5b28be84 1280 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
6a488035 1281 }
34917198 1282 if (!empty($thisTypeId)) {
5b28be84 1283 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
34917198
J
1284 }
1285 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
65a35632 1286
34917198 1287 } // End loop through 'other' locations of this type
087f00ec 1288
34917198 1289 } // End if 'other' location for this type exists
6a488035 1290
34917198 1291 } // End loop through each location block entity
6a488035
TO
1292
1293 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1294 $config = CRM_Core_Config::singleton();
1295 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1296 $mainUser = NULL;
1297 if ($mainUfId) {
1298 // d6 compatible
1299 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1300 $mainUser = user_load($mainUfId);
1301 }
1302 elseif ($config->userFramework == 'Joomla') {
1303 $mainUser = JFactory::getUser($mainUfId);
1304 }
1305 }
1306 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1307 $otherUser = NULL;
1308 if ($otherUfId) {
1309 // d6 compatible
1310 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1311 $otherUser = user_load($otherUfId);
1312 }
1313 elseif ($config->userFramework == 'Joomla') {
1314 $otherUser = JFactory::getUser($otherUfId);
1315 }
1316 }
1317
1318 $relTables = CRM_Dedupe_Merger::relTables();
1319 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1320 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1321 foreach ($relTables as $name => $null) {
1322 if (!in_array($name, $activeRelTables) &&
1323 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1324 ) {
1325 unset($relTables[$name]);
1326 continue;
1327 }
1328
2c16165a 1329 $relTableElements[] = ['checkbox', "move_$name"];
6a488035
TO
1330 $migrationInfo["move_$name"] = 1;
1331
1332 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1333 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1334 if ($name == 'rel_table_users') {
1335 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1336 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
2c16165a 1337 $find = ['$ufid', '$ufname'];
6a488035 1338 if ($mainUser) {
2c16165a 1339 $replace = [$mainUfId, $mainUser->name];
6a488035
TO
1340 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1341 }
1342 if ($otherUser) {
2c16165a 1343 $replace = [$otherUfId, $otherUser->name];
6a488035
TO
1344 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1345 }
1346 }
1347 if ($name == 'rel_table_memberships') {
7d84a47d
JP
1348 //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
1349 $attributes = ['checked' => 'checked'];
1350 $otherContactMemberships = CRM_Member_BAO_Membership::getAllContactMembership($otherId);
1351 foreach ($otherContactMemberships as $membership) {
1352 $mainMembership = CRM_Member_BAO_Membership::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
1353 if ($mainMembership) {
1354 $attributes = [];
1355 }
1356 }
2c16165a 1357 $elements[] = [
1358 'checkbox',
1359 "operation[move_{$name}][add]",
1360 NULL,
1361 ts('add new'),
1362 $attributes,
1363 ];
6a488035
TO
1364 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1365 }
1366 }
1367 foreach ($relTables as $name => $null) {
1368 $relTables["move_$name"] = $relTables[$name];
1369 unset($relTables[$name]);
1370 }
1371
1372 // handle custom fields
201057c0 1373 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1,
1374 CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035 1375 );
0b330e6d 1376 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1,
201057c0 1377 CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035 1378 );
6a488035
TO
1379
1380 foreach ($otherTree as $gid => $group) {
1381 $foundField = FALSE;
1382 if (!isset($group['fields'])) {
1383 continue;
1384 }
1385
1386 foreach ($group['fields'] as $fid => $field) {
4eea8606 1387 if (in_array($fid, $compareFields['custom'])) {
6a488035
TO
1388 if (!$foundField) {
1389 $rows["custom_group_$gid"]['title'] = $group['title'];
1390 $foundField = TRUE;
1391 }
a7488080 1392 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
6a488035 1393 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
51a3717f 1394 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1395 }
1396 }
1397 $value = "null";
a7488080 1398 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
6a488035 1399 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
51a3717f 1400 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1401 if ($values['data'] === 0 || $values['data'] === '0') {
1402 $values['data'] = $qfZeroBug;
d58a19a1 1403 }
6a488035 1404 $value = ($values['data']) ? $values['data'] : $value;
d58a19a1 1405 }
6a488035
TO
1406 }
1407 $rows["move_custom_$fid"]['title'] = $field['label'];
1408
2c16165a 1409 $elements[] = [
1410 'advcheckbox',
1411 "move_custom_$fid",
1412 NULL,
1413 NULL,
1414 NULL,
1415 $value,
1416 ];
6a488035
TO
1417 $migrationInfo["move_custom_$fid"] = $value;
1418 }
1419 }
1420 }
abb422f9 1421
2c16165a 1422 $result = [
6a488035
TO
1423 'rows' => $rows,
1424 'elements' => $elements,
1425 'rel_table_elements' => $relTableElements,
6a488035
TO
1426 'rel_tables' => $relTables,
1427 'main_details' => $main,
1428 'other_details' => $other,
1429 'migration_info' => $migrationInfo,
2c16165a 1430 ];
6a488035 1431
34917198
J
1432 $result['main_details']['location_blocks'] = $locations['main'];
1433 $result['other_details']['location_blocks'] = $locations['other'];
6a488035
TO
1434
1435 return $result;
1436 }
1437
1438 /**
1439 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1440 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1441 * A superset of moveContactBelongings() function.
1442 *
98997235
TO
1443 * @param int $mainId
1444 * Main contact with whom merge has to happen.
1445 * @param int $otherId
1446 * Duplicate contact which would be deleted after merge operation.
77b97be7 1447 *
1600a9c0 1448 * @param array $migrationInfo
6a488035 1449 *
3058f4d9 1450 * @param bool $checkPermissions
1451 * Respect logged in user permissions.
1452 *
77b97be7 1453 * @return bool
1600a9c0 1454 * @throws \CiviCRM_API3_Exception
6a488035 1455 */
3058f4d9 1456 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
6a488035
TO
1457 if (empty($migrationInfo)) {
1458 return FALSE;
1459 }
119664d6 1460 // Encapsulate in a transaction to avoid half-merges.
1461 $transaction = new CRM_Core_Transaction();
6a488035 1462
1acd98ec 1463 $contactType = $migrationInfo['main_details']['contact_type'];
6a488035 1464 $relTables = CRM_Dedupe_Merger::relTables();
35e0e03e 1465 $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
ae2346d4 1466
54ed517e 1467 self::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
6a488035 1468 foreach ($migrationInfo as $key => $value) {
08b00099
CR
1469
1470 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
6a488035 1471 $submitted[substr($key, 5)] = $value;
ae2346d4 1472 $submittedCustomFields[] = substr($key, 12);
6a488035 1473 }
08b00099 1474 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) {
6a488035
TO
1475 $submitted[substr($key, 5)] = $value;
1476 }
6a488035
TO
1477 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1478 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1479 if (array_key_exists('operation', $migrationInfo)) {
1480 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1481 if (array_key_exists($key, $migrationInfo['operation'])) {
1482 $tableOperations[$table] = $migrationInfo['operation'][$key];
1483 }
1484 }
1485 }
1486 }
4099a9c5
AP
1487 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
1488 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1489 }
6a488035 1490 }
35e0e03e 1491 self::mergeLocations($mainId, $otherId, $migrationInfo);
6a488035 1492
6a488035 1493 // **** Do contact related migrations
ae2346d4 1494 $customTablesToCopyValues = self::getAffectedCustomTables($submittedCustomFields);
1600a9c0 1495 // @todo - move all custom field processing to the move class & eventually have an
1496 // overridable DAO class for it.
1497 $customFieldBAO = new CRM_Core_BAO_CustomField();
1498 $customFieldBAO->move($otherId, $mainId, $submittedCustomFields);
0556db5d
CR
1499 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1500 unset($moveTables, $tableOperations);
6a488035 1501
4099a9c5
AP
1502 // **** Do table related removals
1503 if (!empty($removeTables)) {
1504 // **** CRM-20421
1505 CRM_Dedupe_Merger::removeContactBelongings($otherId, $removeTables);
2c16165a 1506 $removeTables = [];
4099a9c5
AP
1507 }
1508
6a488035 1509 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
2c16165a 1510 $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
1511 $names['individual_prefix'] = [
1512 'newName' => 'prefix_id',
1513 'groupName' => 'individual_prefix',
1514 ];
1515 $names['individual_suffix'] = [
1516 'newName' => 'suffix_id',
1517 'groupName' => 'individual_suffix',
1518 ];
1519 $names['communication_style'] = [
1520 'newName' => 'communication_style_id',
1521 'groupName' => 'communication_style',
1522 ];
1523 $names['addressee'] = [
1524 'newName' => 'addressee_id',
1525 'groupName' => 'addressee',
1526 ];
1527 $names['email_greeting'] = [
1528 'newName' => 'email_greeting_id',
1529 'groupName' => 'email_greeting',
1530 ];
1531 $names['postal_greeting'] = [
1532 'newName' => 'postal_greeting_id',
1533 'groupName' => 'postal_greeting',
1534 ];
6a488035 1535 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
6a488035 1536 // fix custom fields so they're edible by createProfileContact()
f941d73a 1537 $cFields = self::getCustomFieldMetadata($contactType);
6a488035
TO
1538
1539 if (!isset($submitted)) {
2c16165a 1540 $submitted = [];
6a488035
TO
1541 }
1542 foreach ($submitted as $key => $value) {
1600a9c0 1543 list($cFields, $submitted) = self::processCustomFields($mainId, $key, $cFields, $submitted, $value);
6a488035
TO
1544 }
1545
6a488035 1546 // move view only custom fields CRM-5362
2c16165a 1547 $viewOnlyCustomFields = [];
6a488035 1548 foreach ($submitted as $key => $value) {
ca38a45b 1549 $fid = CRM_Core_BAO_CustomField::getKeyID($key);
1550 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1551 ) {
6a488035
TO
1552 $viewOnlyCustomFields[$key] = $value;
1553 }
1554 }
6a488035
TO
1555 // special case to set values for view only, CRM-5362
1556 if (!empty($viewOnlyCustomFields)) {
1557 $viewOnlyCustomFields['entityID'] = $mainId;
1558 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1559 }
1560
1f0138dd
SL
1561 // dev/core#996 Ensure that the earliest created date is stored against the kept contact id
1562 $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [
1563 'id' => $mainId,
1564 'return' => ['created_date'],
1565 ])['created_date'];
1566 $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [
1567 'id' => $otherId,
1568 'return' => ['created_date'],
1569 ])['created_date'];
1570 if ($otherCreatedDate < $mainCreatedDate) {
1571 CRM_Core_DAO::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [
1572 1 => [$otherCreatedDate, 'String'],
1573 2 => [$mainId, 'Positive'],
1574 ]);
1575 }
1576
3058f4d9 1577 if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') &&
2c16165a 1578 CRM_Core_Permission::check('delete contacts'))
6a488035
TO
1579 ) {
1580 // if ext id is submitted then set it null for contact to be deleted
a7488080 1581 if (!empty($submitted['external_identifier'])) {
6a488035
TO
1582 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1583 CRM_Core_DAO::executeQuery($query);
1584 }
2c16165a 1585 civicrm_api3('contact', 'delete', ['id' => $otherId]);
6a488035 1586 }
6a488035 1587
4d5f18cc 1588 // CRM-15681 merge sub_types
35522279
J
1589 if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) {
1590 if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) {
481a74f4 1591 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
0db6c3e1
TO
1592 }
1593 else {
4d5f18cc 1594 $submitted['contact_sub_type'] = $other_sub_types;
1595 }
1596 }
1597
6a488035
TO
1598 // **** Update contact related info for the main contact
1599 if (!empty($submitted)) {
1600 $submitted['contact_id'] = $mainId;
1601
1602 //update current employer field
1603 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1604 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1605 $submitted['current_employer'] = $submitted['current_employer_id'];
0db6c3e1
TO
1606 }
1607 else {
6a488035
TO
1608 $submitted['current_employer'] = '';
1609 }
1610 unset($submitted['current_employer_id']);
1611 }
1612
00f3da2e 1613 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
481a74f4 1614 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
00f3da2e
BS
1615 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1616 }
481a74f4 1617 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
00f3da2e
BS
1618 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1619 }
9b0e7e51 1620 $null = [];
1621 CRM_Contact_BAO_Contact::createProfileContact($submitted, $null, $mainId);
6a488035 1622 }
119664d6 1623 $transaction->commit();
1273d77c 1624 CRM_Utils_Hook::post('merge', 'Contact', $mainId);
f00283b5 1625 self::createMergeActivities($mainId, $otherId);
5ea06a7b 1626
6a488035
TO
1627 return TRUE;
1628 }
16254ae1 1629
ae2346d4
CR
1630 /**
1631 * Builds an Array of Custom tables for given custom field ID's.
1632 *
1633 * @param $customFieldIDs
1634 *
1635 * @return array
1636 * Array of custom table names
1637 */
1638 private static function getAffectedCustomTables($customFieldIDs) {
2c16165a 1639 $customTableToCopyValues = [];
ae2346d4
CR
1640
1641 foreach ($customFieldIDs as $fieldID) {
1642 if (!empty($fieldID)) {
2c16165a 1643 $customField = civicrm_api3('custom_field', 'getsingle', [
08b00099
CR
1644 'id' => $fieldID,
1645 'is_active' => TRUE,
2c16165a 1646 ]);
08b00099 1647 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
2c16165a 1648 $customGroup = civicrm_api3('custom_group', 'getsingle', [
08b00099 1649 'id' => $customField['custom_group_id'],
ae2346d4 1650 'is_active' => TRUE,
2c16165a 1651 ]);
ae2346d4
CR
1652
1653 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1654 $customTableToCopyValues[] = $customGroup['table_name'];
1655 }
1656 }
1657 }
1658 }
1659
1660 return $customTableToCopyValues;
1661 }
1662
16254ae1 1663 /**
f00283b5 1664 * Get fields in the contact table suitable for merging.
1665 *
a6c01b45 1666 * @return array
f00283b5 1667 * Array of field names to be potentially merged.
16254ae1 1668 */
00be9182 1669 public static function getContactFields() {
16254ae1 1670 $contactFields = CRM_Contact_DAO_Contact::fields();
2c16165a 1671 $invalidFields = [
353ffa53 1672 'api_key',
353ffa53
TO
1673 'created_date',
1674 'display_name',
1675 'hash',
1676 'id',
1677 'modified_date',
1678 'primary_contact_id',
1679 'sort_name',
c301f76e 1680 'user_unique_id',
2c16165a 1681 ];
bdd7870e
RN
1682 foreach ($contactFields as $field => $value) {
1683 if (in_array($field, $invalidFields)) {
1684 unset($contactFields[$field]);
1685 }
1686 }
16254ae1
ARW
1687 return array_keys($contactFields);
1688 }
ada104d5
AW
1689
1690 /**
1691 * Added for CRM-12695
c301f76e 1692 * Based on the contactID provided
ada104d5
AW
1693 * add/update membership(s) to related contacts
1694 *
c301f76e 1695 * @param int $contactID
ada104d5 1696 */
00be9182 1697 public static function addMembershipToRealtedContacts($contactID) {
ada104d5
AW
1698 $dao = new CRM_Member_DAO_Membership();
1699 $dao->contact_id = $contactID;
1700 $dao->is_test = 0;
1701 $dao->find();
1702
1703 //checks membership of contact itself
1704 while ($dao->fetch()) {
1705 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1706 if ($relationshipTypeId) {
2c16165a 1707 $membershipParams = [
ada104d5
AW
1708 'id' => $dao->id,
1709 'contact_id' => $dao->contact_id,
1710 'membership_type_id' => $dao->membership_type_id,
1711 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1712 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1713 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1714 'source' => $dao->source,
21dfd5f5 1715 'status_id' => $dao->status_id,
2c16165a 1716 ];
ada104d5
AW
1717 // create/update membership(s) for related contact(s)
1718 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1719 } // end of if relationshipTypeId
1720 }
1721 }
96025800 1722
f00283b5 1723 /**
1724 * Create activities tracking the merge on affected contacts.
1725 *
1726 * @param int $mainId
1727 * @param int $otherId
1728 *
1729 * @throws \CiviCRM_API3_Exception
1730 */
1731 public static function createMergeActivities($mainId, $otherId) {
2c16165a 1732 $params = [
f00283b5 1733 1 => $otherId,
1734 2 => $mainId,
2c16165a 1735 ];
1736 $activity = civicrm_api3('activity', 'create', [
dc33398e 1737 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
518fa0ee 1738 $mainId,
f00283b5 1739 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1740 'target_contact_id' => $mainId,
1741 'activity_type_id' => 'Contact Merged',
1742 'status_id' => 'Completed',
2c16165a 1743 ]);
1744 if (civicrm_api3('Setting', 'getvalue', [
1745 'name' => 'contact_undelete',
1746 'group' => 'CiviCRM Preferences',
1747 ])) {
1748 civicrm_api3('activity', 'create', [
dc33398e 1749 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
518fa0ee 1750 $otherId,
4d834a99 1751 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1752 'target_contact_id' => $otherId,
1753 'activity_type_id' => 'Contact Deleted by Merge',
1754 'parent_id' => $activity['id'],
1755 'status_id' => 'Completed',
2c16165a 1756 ]);
4d834a99 1757 }
f00283b5 1758 }
1759
2988f5c7 1760 /**
1761 * Get Duplicate Pairs based on a rule for a group.
1762 *
1763 * @param int $rule_group_id
1764 * @param int $group_id
1765 * @param bool $reloadCacheIfEmpty
917acf6f 1766 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
2988f5c7 1767 * @param int $batchLimit
1768 * @param bool $isSelected
5721d85e 1769 * Limit to selected pairs.
66eceb0b 1770 * @param bool $includeConflicts
e23e26ec 1771 * @param array $criteria
1772 * Additional criteria to narrow down the merge group.
2988f5c7 1773 *
3058f4d9 1774 * @param bool $checkPermissions
1775 * Respect logged in user permissions.
1776 *
21a95d83 1777 * @param int $searchLimit
1778 * Limit to searching for matches against this many contacts.
1779 *
c41f68a5 1780 * @param int $isForceNewSearch
1781 * Should a new search be forced, bypassing any cache retrieval.
1782 *
2988f5c7 1783 * @return array
518fa0ee 1784 * Array of matches meeting the criteria.
9c5fe572 1785 *
1786 * @throws \CRM_Core_Exception
1787 * @throws \CiviCRM_API3_Exception
2988f5c7 1788 */
c41f68a5 1789 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0, $isForceNewSearch = 0) {
1790 $dupePairs = $isForceNewSearch ? [] : self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit);
2988f5c7 1791 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1792 // If we haven't found any dupes, probably cache is empty.
66eceb0b 1793 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1794 // until we have done some processing.
e1e24a57 1795 CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit);
997a03fe 1796 return self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions, $searchLimit);
2988f5c7 1797 }
1798 return $dupePairs;
1799 }
1800
2ae26001 1801 /**
1802 * Get the cache key string for the merge action.
1803 *
1804 * @param int $rule_group_id
1805 * @param int $group_id
e23e26ec 1806 * @param array $criteria
1807 * Additional criteria to narrow down the merge group.
1808 * Currently we are only supporting the key 'contact' within it.
3058f4d9 1809 * @param bool $checkPermissions
1810 * Respect the users permissions.
997a03fe 1811 * @param int $searchLimit
1812 * Number of contacts to seek dupes for (we need this because if
1813 * we change it the results won't be refreshed otherwise. Changing the limit
1814 * from 100 to 1000 SHOULD result in a new dedupe search).
3058f4d9 1815 *
2ae26001 1816 * @return string
1817 */
997a03fe 1818 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit) {
2ae26001 1819 $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
9d2f6d53 1820 $cacheKeyString = "merge_{$contactType}";
2ae26001 1821 $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
1822 $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
997a03fe 1823 $cacheKeyString .= '_' . (int) $searchLimit;
629dd4f3 1824 $cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0';
3058f4d9 1825 if ($checkPermissions) {
1826 $contactID = CRM_Core_Session::getLoggedInContactID();
1827 if (!$contactID) {
1828 // Distinguish between no permission check & no logged in user.
1829 $contactID = 'null';
1830 }
1831 $cacheKeyString .= '_' . $contactID;
1832 }
1833 else {
1834 $cacheKeyString .= '_0';
1835 }
2ae26001 1836 return $cacheKeyString;
1837 }
1838
74a6069d 1839 /**
1840 * Get the metadata for the merge fields.
1841 *
1842 * This is basically the contact metadata, augmented with fields to
1843 * represent email greeting, postal greeting & addressee.
1844 *
1845 * @return array
1846 */
1847 public static function getMergeFieldsMetadata() {
1848 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) {
1849 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1850 }
1851 $fields = CRM_Contact_DAO_Contact::fields();
2c16165a 1852 static $optionValueFields = [];
74a6069d 1853 if (empty($optionValueFields)) {
1854 $optionValueFields = CRM_Core_OptionValue::getFields();
1855 }
1856 foreach ($optionValueFields as $field => $params) {
1857 $fields[$field]['title'] = $params['title'];
1858 }
1859 \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields;
1860 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1861 }
1862
1863 /**
1864 * Get the details of the contact to be merged.
1865 *
1866 * @param int $contact_id
74a6069d 1867 *
1868 * @return array
1869 *
1870 * @throws CRM_Core_Exception
1871 */
fcc3d8ee 1872 public static function getMergeContactDetails($contact_id) {
2c16165a 1873 $params = [
74a6069d 1874 'contact_id' => $contact_id,
1875 'version' => 3,
2c16165a 1876 'return' => array_merge(['display_name'], self::getContactFields()),
1877 ];
74a6069d 1878 $result = civicrm_api('contact', 'get', $params);
1879
1880 // CRM-18480: Cancel the process if the contact is already deleted
1881 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
2c16165a 1882 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
fcc3d8ee 1883 1 => $contact_id,
2c16165a 1884 ]));
74a6069d 1885 }
1886
1887 return $result['values'][$contact_id];
1888 }
1889
92a77772 1890 /**
1891 * Merge location.
1892 *
1893 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
1894 *
1895 * The data is in the format received from the merge form (which is a fairly confusing format).
1896 *
1897 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
1898 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
1899 * been calculated and before saving because
1900 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
1901 * - passing to a hook right before save means calculations only have to be done once
1902 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
1903 * ugly.
1904 *
1905 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
16d4e0b7 1906 * is likely to be significant data in merge hooks.
92a77772 1907 *
1908 * @param int $mainId
1909 * @param int $otherId
92a77772 1910 *
1911 * @param array $migrationInfo
1912 * Migration info for the merge. This is passed to the hook as informational only.
1913 */
35e0e03e 1914 public static function mergeLocations($mainId, $otherId, $migrationInfo) {
1915 foreach ($migrationInfo as $key => $value) {
1916 $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL);
1917 if (!$isLocationField) {
1918 continue;
1919 }
92a77772 1920 $locField = explode('_', $key);
1921 $fieldName = $locField[2];
1922 $fieldCount = $locField[3];
1923
1924 // Set up the operation type (add/overwrite)
1925 // Ignore operation for websites
1926 // @todo Tidy this up
1927 $operation = 0;
1928 if ($fieldName != 'website') {
1929 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1930 }
1931 // default operation is overwrite.
1932 if (!$operation) {
1933 $operation = 2;
1934 }
1935 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1936 }
2c16165a 1937 $blocksDAO = [];
92a77772 1938
1939 // @todo Handle OpenID (not currently in API).
1940 if (!empty($locBlocks)) {
1941 $locationBlocks = self::getLocationBlockInfo();
1942
2c16165a 1943 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_primary' => 1]);
1944 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_billing' => 1]);
92a77772 1945
1946 foreach ($locBlocks as $name => $block) {
2c16165a 1947 $blocksDAO[$name] = ['delete' => [], 'update' => []];
92a77772 1948 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1949 continue;
1950 }
1951 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
abd0b852 1952 $changePrimary = FALSE;
92a77772 1953 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1954 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1955
1956 foreach ($block as $blkCount => $values) {
1957 $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
1958 $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1959 if (!$otherBlockId) {
1960 continue;
1961 }
1962
1963 // For the block which belongs to other-contact, link the location block to main-contact
1964 $otherBlockDAO = new $daoName();
1965 $otherBlockDAO->contact_id = $mainId;
1966
1967 // Get the ID of this block on the 'other' contact, otherwise skip
1968 $otherBlockDAO->id = $otherBlockId;
1969
1970 // Add/update location and type information from the form, if applicable
1971 if ($locationBlocks[$name]['hasLocation']) {
1972 $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1973 $otherBlockDAO->location_type_id = $locTypeId;
1974 }
1975 if ($locationBlocks[$name]['hasType']) {
1976 $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1977 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
1978 }
1979
abd0b852
J
1980 // If we're deliberately setting this as primary then add the flag
1981 // and remove it from the current primary location (if there is one).
1982 // But only once for each entity.
1983 $set_primary = CRM_Utils_Array::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
9e848fc4 1984 if (!$changePrimary && $set_primary == "1") {
abd0b852
J
1985 $otherBlockDAO->is_primary = 1;
1986 if ($primaryDAOId) {
1987 $removePrimaryDAO = new $daoName();
1988 $removePrimaryDAO->id = $primaryDAOId;
1989 $removePrimaryDAO->is_primary = 0;
1990 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
1991 }
1992 $changePrimary = TRUE;
1993 }
1994 // Otherwise, if main contact already has primary, set it to 0.
1995 elseif ($primaryDAOId) {
92a77772 1996 $otherBlockDAO->is_primary = 0;
1997 }
abd0b852
J
1998
1999 // If the main contact already has a billing location, set this to 0.
92a77772 2000 if ($billingDAOId) {
2001 $otherBlockDAO->is_billing = 0;
2002 }
2003
2004 $operation = CRM_Utils_Array::value('operation', $values, 2);
2005 // overwrite - need to delete block which belongs to main-contact.
2006 if (!empty($mainBlockId) && ($operation == 2)) {
2007 $deleteDAO = new $daoName();
2008 $deleteDAO->id = $mainBlockId;
2009 $deleteDAO->find(TRUE);
2010
2011 // if we about to delete a primary / billing block, set the flags for new block
2012 // that we going to assign to main-contact
2013 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
2014 $otherBlockDAO->is_primary = 1;
2015 }
2016 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
2017 $otherBlockDAO->is_billing = 1;
2018 }
2019 $blocksDAO[$name]['delete'][$deleteDAO->id] = $deleteDAO;
2020 }
2021 $blocksDAO[$name]['update'][$otherBlockDAO->id] = $otherBlockDAO;
2022 }
2023 }
2024 }
2025
2026 CRM_Utils_Hook::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2027 foreach ($blocksDAO as $blockDAOs) {
2028 if (!empty($blockDAOs['update'])) {
2029 foreach ($blockDAOs['update'] as $blockDAO) {
2030 $blockDAO->save();
2031 }
2032 }
2033 if (!empty($blockDAOs['delete'])) {
2034 foreach ($blockDAOs['delete'] as $blockDAO) {
2035 $blockDAO->delete();
2036 }
2037 }
2038 }
2039 }
2040
e4e1db4b 2041 /**
2042 * Dedupe a pair of contacts.
2043 *
b068bfde 2044 * @param array $dupes
e4e1db4b 2045 * @param string $mode
2046 * @param bool $checkPermissions
e4e1db4b 2047 * @param string $cacheKeyString
37cd9336 2048 *
b068bfde 2049 * @return bool|array
37cd9336 2050 * @throws \CRM_Core_Exception
2051 * @throws \CiviCRM_API3_Exception
ffa59d18 2052 * @throws \API_Exception
e4e1db4b 2053 */
b068bfde 2054 protected static function dedupePair($dupes, $mode = 'safe', $checkPermissions = TRUE, $cacheKeyString = NULL) {
2055 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
2056 $mainId = $dupes['dstID'];
2057 $otherId = $dupes['srcID'];
2058 $resultStats = [];
2059
2060 if (!$mainId || !$otherId) {
2061 // return error
2062 return FALSE;
2063 }
aefc291e 2064 $migrationInfo = [];
2c16165a 2065 $conflicts = [];
e4e1db4b 2066 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2067 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2c16165a 2068 $resultStats['merged'][] = [
e4e1db4b 2069 'main_id' => $mainId,
2070 'other_id' => $otherId,
2c16165a 2071 ];
e4e1db4b 2072 }
2073 else {
2c16165a 2074 $resultStats['skipped'][] = [
e4e1db4b 2075 'main_id' => $mainId,
2076 'other_id' => $otherId,
2c16165a 2077 ];
e4e1db4b 2078 }
2079
2080 // store any conflicts
2081 if (!empty($conflicts)) {
ffa59d18 2082 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode);
e4e1db4b 2083 }
2084 else {
c131d228 2085 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString);
e4e1db4b 2086 }
b068bfde 2087 return $resultStats;
e4e1db4b 2088 }
2089
54ed517e 2090 /**
2091 * Replace the pseudo QFKey with zero if it is present.
2092 *
2093 * @todo - on the slim chance this is still relevant it should be moved to the form layer.
2094 *
2095 * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
2096 * can still help.
2097 *
2098 * @param array $migrationInfo
2099 */
2100 protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
2101 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
2102 foreach ($migrationInfo as $key => &$value) {
2103 if ($value == $qfZeroBug) {
2104 $value = '0';
2105 }
2106 }
2107 }
2108
830ee2be 2109 /**
2110 * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
2111 *
1600a9c0 2112 * Update this function formats fields in preparation for them to be submitted to the
2113 * 'ProfileContactCreate action. This is a lot of code to do this & for
2114 * - for some fields it fails - e.g Country - per testMergeCustomFields.
2115 *
2116 * Goal is to move all custom field handling into 'move' functions on the various BAO
2117 * with an underlying DAO function. For custom fields it has been started on the BAO.
2118 *
830ee2be 2119 * @param $mainId
2120 * @param $key
2121 * @param $cFields
830ee2be 2122 * @param $submitted
2123 * @param $value
2124 *
2125 * @return array
1600a9c0 2126 * @throws \Exception
830ee2be 2127 */
1600a9c0 2128 protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) {
830ee2be 2129 if (substr($key, 0, 7) == 'custom_') {
2130 $fid = (int) substr($key, 7);
2131 if (empty($cFields[$fid])) {
1600a9c0 2132 return [$cFields, $submitted];
830ee2be 2133 }
2134 $htmlType = $cFields[$fid]['attributes']['html_type'];
2135 switch ($htmlType) {
2136 case 'File':
1600a9c0 2137 // Handled in CustomField->move(). Tested in testMergeCustomFields.
830ee2be 2138 unset($submitted["custom_$fid"]);
2139 break;
2140
2141 case 'Select Country':
1600a9c0 2142 // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move().
830ee2be 2143 case 'Select State/Province':
2144 $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
2145 break;
2146
2147 case 'Select Date':
2148 if ($cFields[$fid]['attributes']['is_view']) {
2149 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
2150 }
2151 break;
2152
2153 case 'CheckBox':
2154 case 'Multi-Select':
2155 case 'Multi-Select Country':
2156 case 'Multi-Select State/Province':
2157 // Merge values from both contacts for multivalue fields, CRM-4385
2158 // get the existing custom values from db.
2159 $customParams = ['entityID' => $mainId, $key => TRUE];
2160 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
2161 if (!empty($customfieldValues[$key])) {
2162 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
2163 if (is_array($existingValue) && !empty($existingValue)) {
2164 $mergeValue = $submittedCustomFields = [];
2165 if ($value == 'null') {
2166 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
2167 $submitted[$key] = $value;
2168 }
2169 else {
2170 if ($value) {
2171 $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2172 }
2173
2174 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
2175 // custom field value stored at $submittedCustomValue.
2176 foreach ($submittedCustomFields as $k => $v) {
2177 if ($v != '' && !in_array($v, $mergeValue)) {
2178 $mergeValue[] = $v;
2179 }
2180 }
2181
2182 //keep state and country as array format.
2183 //for checkbox and m-select format w/ VALUE_SEPARATOR
2184 if (in_array($htmlType, [
2185 'CheckBox',
2186 'Multi-Select',
2187 ])) {
2188 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
2189 $mergeValue
2190 ) . CRM_Core_DAO::VALUE_SEPARATOR;
2191 }
2192 else {
2193 $submitted[$key] = $mergeValue;
2194 }
2195 }
2196 }
2197 }
2198 elseif (in_array($htmlType, [
2199 'Multi-Select Country',
2200 'Multi-Select State/Province',
2201 ])) {
2202 //we require submitted values should be in array format
2203 if ($value) {
2204 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2205 //hack to remove null values from array.
2206 $mergeValue = [];
2207 foreach ($mergeValueArray as $k => $v) {
2208 if ($v != '') {
2209 $mergeValue[] = $v;
2210 }
2211 }
2212 $submitted[$key] = $mergeValue;
2213 }
2214 }
2215 break;
2216
2217 default:
2218 break;
2219 }
2220 }
1600a9c0 2221 return [$cFields, $submitted];
830ee2be 2222 }
2223
f941d73a 2224 /**
2225 * Get metadata for the custom fields for the merge.
2226 *
2227 * @param string $contactType
2228 *
2229 * @return array
2230 */
2231 protected static function getCustomFieldMetadata($contactType) {
2232 $treeCache = [];
2233 if (!array_key_exists($contactType, $treeCache)) {
2234 $treeCache[$contactType] = CRM_Core_BAO_CustomGroup::getTree(
2235 $contactType,
2236 NULL,
2237 NULL,
2238 -1,
2239 [],
2240 NULL,
2241 TRUE,
2242 NULL,
2243 FALSE,
2244 FALSE
2245 );
2246 }
2247
2248 $cFields = [];
2249 foreach ($treeCache[$contactType] as $key => $group) {
2250 if (!isset($group['fields'])) {
2251 continue;
2252 }
2253 foreach ($group['fields'] as $fid => $field) {
2254 $cFields[$fid]['attributes'] = $field;
2255 }
2256 }
2257 return $cFields;
2258 }
2259
a2abc387 2260 /**
2261 * Get conflicts for proposed merge pair.
2262 *
2263 * @param array $migrationInfo
2264 * This is primarily to inform hooks. The can also modify it which feels
2265 * pretty fragile to do it here - but it is historical.
2266 * @param int $mainId
2267 * Main contact with whom merge has to happen.
2268 * @param int $otherId
2269 * Duplicate contact which would be deleted after merge operation.
2270 * @param string $mode
2271 * Helps decide how to behave when there are conflicts.
2272 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
2273 * - Does a force merge otherwise (aggressive mode).
2274 *
2275 * @return array
aefc291e 2276 *
2277 * @throws \CRM_Core_Exception
2278 * @throws \CiviCRM_API3_Exception
a2abc387 2279 */
2280 public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) {
2281 $conflicts = [];
aefc291e 2282 // Generate var $migrationInfo. The variable structure is exactly same as
2283 // $formValues submitted during a UI merge for a pair of contacts.
2284 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, FALSE);
2285 // add additional details that we might need to resolve conflicts
2286 $migrationInfo = $rowsElementsAndInfo['migration_info'];
2287 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
2288 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
2289 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
2290 // go ahead with merge if there is no conflict
a2abc387 2291 $originalMigrationInfo = $migrationInfo;
2292 foreach ($migrationInfo as $key => $val) {
2293 if ($val === "null") {
2294 // Rule: Never overwrite with an empty value (in any mode)
2295 unset($migrationInfo[$key]);
2296 continue;
2297 }
2298 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
2299 substr($key, 0, 12) == 'move_custom_'
2300 ) and $val != NULL
2301 ) {
2302 // Rule: If both main-contact, and other-contact have a field with a
2303 // different value, then let $mode decide if to merge it or not
2304 if (
2305 (!empty($migrationInfo['rows'][$key]['main'])
2306 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
2307 // is probably true for other fields too - e.g. 'do_not_email' but
2308 // leaving that investigation as a @todo - until tests can be written.
2309 // Note the handling of this has test coverage - although the data-typing
2310 // of '0' feels flakey we have insurance.
2311 || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
2312 )
2313 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
2314 ) {
2315
2316 // note it down & lets wait for response from the hook.
2317 // For no response $mode will decide if to skip this merge
2318 $conflicts[$key] = NULL;
2319 }
2320 }
2321 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
2322 $locField = explode('_', $key);
2323 $fieldName = $locField[2];
2324 $fieldCount = $locField[3];
2325
2326 // Rule: Catch address conflicts (same address type on both contacts)
2327 if (
2328 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
2329 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
2330 ) {
2331
2332 // Load the address we're inspecting from the 'other' contact
2333 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
2334 $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord);
2335
2336 // If it exists on the 'main' contact already, skip it. Otherwise
2337 // if the location type exists already, log a conflict.
2338 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
2339 if (self::locationIsSame($addressRecord, $mainAddressRecord)) {
2340 unset($migrationInfo[$key]);
2341 break;
2342 }
2343 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
2344 $conflicts[$key] = NULL;
2345 break;
2346 }
2347 }
2348 }
2349
2350 // For other locations, don't merge/add if the values are the same
2351 elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
2352 unset($migrationInfo[$key]);
2353 }
2354 }
2355 }
2356
2357 // A hook to implement other algorithms for choosing which contact to bias to when
2358 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
2359 // merge happens with new values filled in here. For a particular field / row not to be merged
2360 // field should be unset from fields_in_conflict.
2361 $migrationData = [
2362 'old_migration_info' => $originalMigrationInfo,
2363 'mode' => $mode,
2364 'fields_in_conflict' => $conflicts,
2365 'merge_mode' => $mode,
2366 'migration_info' => $migrationInfo,
2367 ];
2368 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
2369 $conflicts = $migrationData['fields_in_conflict'];
2370 // allow hook to override / manipulate migrationInfo as well
2371 $migrationInfo = $migrationData['migration_info'];
ffa59d18 2372 foreach ($conflicts as $key => $val) {
2373 if ($val !== NULL || $mode !== 'safe') {
2374 // copy over the resolved values
2375 $migrationInfo[$key] = $val;
2376 unset($conflicts[$key]);
2377 }
2378 }
2379 $migrationInfo['skip_merge'] = $migrationData['skip_merge'] ?? !empty($conflicts);
2380 return self::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId);
2381 }
2382
2383 /**
2384 * @param array $conflicts
2385 * @param array $migrationInfo
2386 * @param $toKeepContactLocationBlocks
2387 * @param $toRemoveContactLocationBlocks
2388 * @param $toKeepID
2389 * @param $toRemoveID
2390 *
2391 * @return mixed
2392 * @throws \CRM_Core_Exception
2393 */
2394 protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID) {
2395 $return = [];
2396 foreach (array_keys($conflicts) as $index) {
2397 if (substr($index, 0, 14) === 'move_location_') {
2398 $parts = explode('_', $index);
2399 $entity = $parts[2];
2400 $blockIndex = $parts[3];
2401 $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id'];
2402 $entityConflicts = [
2403 'location_type_id' => $locationTypeID,
2404 'title' => $migrationInfo[$index]['title'],
2405 ];
2406 foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) {
2407 if (in_array($fieldName, self::ignoredFields())) {
2408 continue;
2409 }
2410 $toRemoveValue = CRM_Utils_Array::value($fieldName, $toRemoveContactLocationBlocks[$entity][$blockIndex]);
2411 if ($fieldValue !== $toRemoveValue) {
2412 $entityConflicts[$fieldName] = [
2413 $toKeepID => $fieldValue,
2414 $toRemoveID => $toRemoveValue,
2415 ];
2416 }
2417 }
2418 $return[$entity][] = $entityConflicts;
2419 }
2420 elseif (substr($index, 0, 5) === 'move_') {
2421 $contactFieldsToCompare[] = str_replace('move_', '', $index);
2422 $return['contact'][str_replace('move_', '', $index)] = [
2423 'title' => $migrationInfo[$index]['title'],
2424 $toKeepID => $migrationInfo[$index]['main'],
2425 $toRemoveID => $migrationInfo[$index]['other'],
2426 ];
2427 }
2428 else {
2429 // Can't think of why this would be the case but perhaps it's ensuring it isn't as we
2430 // refactor this.
2431 throw new CRM_Core_Exception(ts('Unknown parameter') . $index);
2432 }
2433 }
2434 return $return;
a2abc387 2435 }
2436
4107e11e 2437 /**
e1e24a57 2438 * Get any duplicate merge pairs that have been previously cached.
2439 *
2440 * @param int $rule_group_id
2441 * @param int $group_id
2442 * @param int $batchLimit
2443 * @param bool $isSelected
2444 * @param bool $includeConflicts
2445 * @param array $criteria
2446 * @param int $checkPermissions
997a03fe 2447 * @param int $searchLimit
4107e11e 2448 *
2449 * @return array
2450 */
997a03fe 2451 protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit = 0) {
4107e11e 2452 return CRM_Core_BAO_PrevNextCache::retrieve(
997a03fe 2453 self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit),
4107e11e 2454 self::getJoinOnDedupeTable(),
2455 self::getWhereString($isSelected),
2456 0, $batchLimit,
2457 [], '',
2458 $includeConflicts
2459 );
2460 }
2461
ffa59d18 2462 /**
2463 * @return array
2464 */
2465 protected static function ignoredFields(): array {
2466 $keysToIgnore = [
2467 'id',
2468 'is_primary',
2469 'is_billing',
2470 'manual_geo_code',
2471 'contact_id',
2472 'reset_date',
2473 'hold_date',
2474 ];
2475 return $keysToIgnore;
2476 }
2477
6704a926 2478 /**
2479 * Get the field value & label for the given field.
2480 *
2481 * @param $field
2482 * @param $contact
2483 *
2484 * @return array
2485 * @throws \Exception
2486 */
2487 private static function getFieldValueAndLabel($field, $contact): array {
2488 $fields = self::getMergeFieldsMetadata();
2489 $value = $label = CRM_Utils_Array::value($field, $contact);
2490 $fieldSpec = $fields[$field];
2491 if (!empty($fieldSpec['serialize']) && is_array($value)) {
2492 // In practice this only applies to preferred_communication_method as the sub types are skipped above
2493 // and no others are serialized.
2494 $labels = [];
2495 foreach ($value as $individualValue) {
2496 $labels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue);
2497 }
2498 $label = implode(', ', $labels);
2499 // We serialize this due to historic handling but it's likely that if we just left it as an
2500 // array all would be well & we would have less code.
2501 $value = CRM_Core_DAO::serializeField($value, $fieldSpec['serialize']);
2502 }
2503 elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type::T_DATE) {
2504 if ($value) {
2505 $value = str_replace('-', '', $value);
2506 $label = CRM_Utils_Date::customFormat($label);
2507 }
2508 else {
2509 $value = "null";
2510 }
2511 }
2512 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
2513 if ($label === '0') {
2514 $label = ts('[ ]');
2515 }
2516 if ($label === '1') {
2517 $label = ts('[x]');
2518 }
2519 }
2520 elseif (!empty($fieldSpec['pseudoconstant'])) {
2521 $label = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $value);
2522 }
2523 elseif ($field == 'current_employer_id' && !empty($value)) {
2524 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
2525 }
2fd72602 2526 return ['label' => $label, 'value' => $value];
6704a926 2527 }
2528
1a90ac89 2529 /**
2530 * Build up the location block for the contact in dedupe-screen display format.
2531 *
2532 * @param integer $cid
2533 * @param array $blockInfo
2534 * @param string $blockName
2535 *
2536 * @return array
2537 *
2538 * @throws \CiviCRM_API3_Exception
2539 */
2540 private static function buildLocationBlockForContact($cid, $blockInfo, $blockName): array {
2541 $searchParams = [
2542 'contact_id' => $cid,
2543 // CRM-17556 Order by field-specific criteria
2544 'options' => [
2545 'sort' => $blockInfo['sortString'],
2546 ],
2547 ];
2548 $locationBlock = [];
2549 $values = civicrm_api3($blockName, 'get', $searchParams);
2550 if ($values['count']) {
2551 $cnt = 0;
2552 foreach ($values['values'] as $value) {
2553 $locationBlock[$cnt] = $value;
2554 // Fix address display
2555 if ($blockName == 'address') {
2556 // For performance avoid geocoding while merging https://issues.civicrm.org/jira/browse/CRM-21786
2557 // we can expect existing geocode values to be retained.
2558 $value['skip_geocode'] = TRUE;
2559 CRM_Core_BAO_Address::fixAddress($value);
2560 unset($value['skip_geocode']);
2561 $locationBlock[$cnt]['display'] = CRM_Utils_Address::format($value);
2562 }
2563 // Fix email display
2564 elseif ($blockName == 'email') {
2565 $locationBlock[$cnt]['display'] = CRM_Utils_Mail::format($value);
2566 }
2567
2568 $cnt++;
2569 }
2570 }
2571 return $locationBlock;
2572 }
2573
6a488035 2574}