Merge pull request #14098 from eileenmcnaughton/event_income
[civicrm-core.git] / CRM / Dedupe / Merger.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
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
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
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);
674920ca 507 $customTables = array_keys($customTables);
6a488035 508 }
674920ca
ES
509
510 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
0556db5d
CR
511
512 // if there aren't any specific tables, don't affect the ones handled by relTables()
513 // also don't affect tables in locTables() CRM-15658
514 $relTables = self::relTables();
515 $handled = self::locTables();
516
517 foreach ($relTables as $params) {
518 $handled = array_merge($handled, $params['tables']);
6a488035 519 }
0556db5d 520 $affected = array_diff($affected, $handled);
e3159b07 521 $affected = array_unique(array_merge($affected, $tables));
6a488035
TO
522
523 $mainId = (int) $mainId;
524 $otherId = (int) $otherId;
06f4969c 525 $multi_value_tables = array_keys(CRM_Dedupe_Merger::getMultiValueCustomSets('cidRefs'));
6a488035 526
2c16165a 527 $sqls = [];
6a488035 528 foreach ($affected as $table) {
06f4969c 529 // skipping non selected single-value custom table's value migration
530 if (!in_array($table, $multi_value_tables)) {
531 if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
532 continue;
533 }
b35800bd 534 }
674920ca 535
6a488035
TO
536 // Call custom processing function for objects that require it
537 if (isset($cpTables[$table])) {
538 foreach ($cpTables[$table] as $className => $fnName) {
43d4ad93 539 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
6a488035
TO
540 }
541 // Skip normal processing
542 continue;
543 }
b3fdbf3d 544
6a488035
TO
545 // use UPDATE IGNORE + DELETE query pair to skip on situations when
546 // there's a UNIQUE restriction on ($field, some_other_field) pair
547 if (isset($cidRefs[$table])) {
548 foreach ($cidRefs[$table] as $field) {
549 // carry related contributions CRM-5359
550 if (in_array($table, $paymentTables)) {
6a488035
TO
551 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
552 $sqls = array_merge($sqls, $paymentSqls);
71560cf3
C
553
554 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
555 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
556 $sqls = array_merge($sqls, $payOprSqls);
557 }
6a488035
TO
558 }
559
560 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
561 $sqls = array_merge($sqls, $preOperationSqls);
562
ae2346d4
CR
563 if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self::customRecordExists($mainId, $table, $field)) {
564 $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
565 }
6a488035
TO
566 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
567 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
568 }
569 }
ae2346d4 570
6a488035
TO
571 if (isset($eidRefs[$table])) {
572 foreach ($eidRefs[$table] as $entityTable => $entityId) {
573 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
574 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
575 }
576 }
577 }
578
579 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
580 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
581
6a488035 582 foreach ($sqls as $sql) {
2c16165a 583 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE);
6a488035 584 }
0556db5d 585 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
6a488035
TO
586 }
587
4f751978
CR
588 /**
589 * Given a contact ID, will check if a record exists in given table.
590 *
591 * @param $contactID
592 * @param $table
593 * @param $idField
594 * Field where the contact's ID is stored in the table
595 *
596 * @return bool
597 * True if a record is found for the given contact ID, false otherwise
598 */
ae2346d4
CR
599 private static function customRecordExists($contactID, $table, $idField) {
600 $sql = "
601 SELECT COUNT(*) AS count
602 FROM $table
603 WHERE $idField = $contactID
604 ";
605 $dbResult = CRM_Core_DAO::executeQuery($sql);
606 $dbResult->fetch();
607
608 if ($dbResult->count > 0) {
ee3b1d86 609 return TRUE;
ae2346d4
CR
610 }
611
ee3b1d86 612 return FALSE;
ae2346d4
CR
613 }
614
6a488035 615 /**
4eea8606 616 * Load all non-empty fields for the contacts
b3fdbf3d 617 *
98997235
TO
618 * @param array $main
619 * Contact details.
620 * @param array $other
621 * Contact details.
6a488035 622 *
77b97be7 623 * @return array
6a488035 624 */
4eea8606 625 public static function retrieveFields($main, $other) {
2c16165a 626 $result = [
627 'contact' => [],
628 'custom' => [],
629 ];
16254ae1 630 foreach (self::getContactFields() as $validField) {
eb61dc07
J
631 // CRM-17556 Get all non-empty fields, to make comparison easier
632 if (!empty($main[$validField]) || !empty($other[$validField])) {
6a488035
TO
633 $result['contact'][] = $validField;
634 }
635 }
636
637 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
638 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
639 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
640 foreach ($keys as $key) {
76c53278
CW
641 // Exclude multi-value fields CRM-13836
642 if (strpos($key, '_')) {
643 continue;
644 }
6a488035
TO
645 $key1 = CRM_Utils_Array::value($key, $mainEvs);
646 $key2 = CRM_Utils_Array::value($key, $otherEvs);
26b7ff28 647 // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
648 // However I can't think of a case where an empty string is more meaningful than null
649 // or where it would be FALSE or something else nullish.
650 $valuesToIgnore = [NULL, '', []];
651 if (!in_array($key1, $valuesToIgnore, TRUE) || !in_array($key2, $valuesToIgnore, TRUE)) {
6a488035
TO
652 $result['custom'][] = $key;
653 }
654 }
655 return $result;
656 }
657
658 /**
100fef9d 659 * Batch merge a set of contacts based on rule-group and group.
6a488035 660 *
98997235
TO
661 * @param int $rgid
662 * Rule group id.
663 * @param int $gid
664 * Group id.
665 * @param string $mode
666 * Helps decide how to behave when there are conflicts.
15a793bb
EM
667 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
668 * mode does a force merge.
f931b74c 669 * @param int $batchLimit number of merges to carry out in one batch.
670 * @param int $isSelected if records with is_selected column needs to be processed.
bb22928b 671 * Note the option of '2' is only used in conjunction with $redirectForPerformance
b5a6c6c5 672 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
673 * out in favour of explicitly passing in $reloadCacheIfEmpty
6a488035 674 *
e23e26ec 675 * @param array $criteria
676 * Criteria to use in the filter.
677 *
3058f4d9 678 * @param bool $checkPermissions
679 * Respect logged in user permissions.
bb22928b 680 * @param bool|NULL $reloadCacheIfEmpty
681 * If not set explicitly this is calculated but it is preferred that it be set
682 * per comments on isSelected above.
3058f4d9 683 *
77b97be7 684 * @return array|bool
6a488035 685 */
2c16165a 686 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL) {
63ef778e 687 $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
bb22928b 688
689 if (!isset($reloadCacheIfEmpty)) {
690 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
691 }
692 if ($isSelected !== 0 && $isSelected !== 1) {
693 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
694 $isSelected = NULL;
695 }
9c5fe572 696 $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode == 'aggressive'), $criteria, $checkPermissions);
6a488035 697
2c16165a 698 $cacheParams = [
3058f4d9 699 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
2988f5c7 700 // @todo stop passing these parameters in & instead calculate them in the merge function based
701 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
702 'join' => self::getJoinOnDedupeTable(),
ed3c1599 703 'where' => self::getWhereString($isSelected),
704 'limit' => (int) $batchLimit,
2c16165a 705 ];
d238756a 706 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
6a488035
TO
707 }
708
2ae26001 709 /**
710 * Get the string to join the prevnext cache to the dedupe table.
711 *
712 * @return string
713 * The join string to join prevnext cache on the dedupe table.
714 */
715 public static function getJoinOnDedupeTable() {
716 return "
717 LEFT JOIN civicrm_dedupe_exception de
718 ON (
719 pn.entity_id1 = de.contact_id1
720 AND pn.entity_id2 = de.contact_id2 )
721 ";
722 }
723
2988f5c7 724 /**
725 * Get where string for dedupe join.
726 *
2988f5c7 727 * @param bool $isSelected
728 *
729 * @return string
730 */
ed3c1599 731 protected static function getWhereString($isSelected) {
2988f5c7 732 $where = "de.id IS NULL";
733 if ($isSelected === 0 || $isSelected === 1) {
734 $where .= " AND pn.is_selected = {$isSelected}";
735 }
2988f5c7 736 return $where;
737 }
738
bc854509 739 /**
740 * Update the statistics for the merge set.
741 *
742 * @param string $cacheKeyString
743 * @param array $result
744 */
2c16165a 745 public static function updateMergeStats($cacheKeyString, $result = []) {
63ef778e 746 // gather latest stats
2c16165a 747 $merged = count($result['merged']);
63ef778e 748 $skipped = count($result['skipped']);
749
750 if ($merged <= 0 && $skipped <= 0) {
751 return;
752 }
753
754 // get previous stats
e13fa54b 755 $previousStats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
63ef778e 756 if (!empty($previousStats)) {
e13fa54b 757 if ($previousStats['merged']) {
758 $merged = $merged + $previousStats['merged'];
63ef778e 759 }
e13fa54b 760 if ($previousStats['skipped']) {
761 $skipped = $skipped + $previousStats['skipped'];
63ef778e 762 }
763 }
764
765 // delete old stats
766 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
767
768 // store the updated stats
2c16165a 769 $data = [
770 'merged' => $merged,
63ef778e 771 'skipped' => $skipped,
2c16165a 772 ];
63ef778e 773 $data = CRM_Core_DAO::escapeString(serialize($data));
774
2c16165a 775 $values = [];
63ef778e 776 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
777 CRM_Core_BAO_PrevNextCache::setItem($values);
778 }
779
ae6455b2 780 /**
781 * Delete information about merges for the given string.
782 *
783 * @param $cacheKeyString
784 */
f931b74c 785 public static function resetMergeStats($cacheKeyString) {
ae6455b2 786 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
63ef778e 787 }
788
bc854509 789 /**
790 * Get merge outcome statistics.
791 *
792 * @param string $cacheKeyString
793 *
794 * @return array
795 * Array of how many were merged and how many were skipped.
e13fa54b 796 *
797 * @throws \CiviCRM_API3_Exception
bc854509 798 */
f931b74c 799 public static function getMergeStats($cacheKeyString) {
e13fa54b 800 $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values'];
63ef778e 801 if (!empty($stats)) {
e13fa54b 802 return $stats[0]['data'];
63ef778e 803 }
e13fa54b 804 return [];
63ef778e 805 }
806
bc854509 807 /**
808 * Get merge statistics message.
809 *
3743fd3d 810 * @param array $stats
bc854509 811 *
812 * @return string
813 */
3743fd3d
CW
814 public static function getMergeStatsMsg($stats) {
815 $msg = '';
63ef778e 816 if (!empty($stats['merged'])) {
2c16165a 817 $msg = '<p>' . ts('One contact merged.', [
518fa0ee
SL
818 'count' => $stats['merged'],
819 'plural' => '%count contacts merged.',
820 ]) . '</p>';
63ef778e 821 }
822 if (!empty($stats['skipped'])) {
2c16165a 823 $msg .= '<p>' . ts('One contact was skipped.', [
518fa0ee
SL
824 'count' => $stats['skipped'],
825 'plural' => '%count contacts were skipped.',
826 ]) . '</p>';
63ef778e 827 }
828 return $msg;
829 }
830
6a488035 831 /**
100fef9d 832 * Merge given set of contacts. Performs core operation.
6a488035 833 *
98997235
TO
834 * @param array $dupePairs
835 * Set of pair of contacts for whom merge is to be done.
836 * @param array $cacheParams
837 * Prev-next-cache params based on which next pair of contacts are computed.
6a488035 838 * Generally used with batch-merge.
98997235
TO
839 * @param string $mode
840 * Helps decide how to behave when there are conflicts.
6a488035
TO
841 * A 'safe' value skips the merge if there are any un-resolved conflicts.
842 * Does a force merge otherwise (aggressive mode).
6a488035 843 *
77b97be7 844 * @param bool $redirectForPerformance
3058f4d9 845 * Redirect to a url for batch processing.
846 *
847 * @param bool $checkPermissions
848 * Respect logged in user permissions.
77b97be7
EM
849 *
850 * @return array|bool
6a488035 851 */
2c16165a 852 public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe',
853 $redirectForPerformance = FALSE, $checkPermissions = TRUE
6a488035
TO
854 ) {
855 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
2c16165a 856 $resultStats = ['merged' => [], 'skipped' => []];
6a488035
TO
857
858 // we don't want dupe caching to get reset after every-merge, and therefore set the
0626851e 859 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
2c16165a 860 $deletedContacts = [];
6a488035
TO
861
862 while (!empty($dupePairs)) {
78272750 863 foreach ($dupePairs as $index => $dupes) {
864 if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) {
865 unset($dupePairs[$index]);
866 continue;
867 }
1cf05c3e 868 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
6a488035
TO
869 $mainId = $dupes['dstID'];
870 $otherId = $dupes['srcID'];
e67dcaf8 871
6a488035
TO
872 if (!$mainId || !$otherId) {
873 // return error
874 return FALSE;
875 }
6a488035
TO
876 // Generate var $migrationInfo. The variable structure is exactly same as
877 // $formValues submitted during a UI merge for a pair of contacts.
201057c0 878 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions);
6a488035 879 // add additional details that we might need to resolve conflicts
e4e1db4b 880 $rowsElementsAndInfo['migration_info']['main_details'] = &$rowsElementsAndInfo['main_details'];
881 $rowsElementsAndInfo['migration_info']['other_details'] = &$rowsElementsAndInfo['other_details'];
882 $rowsElementsAndInfo['migration_info']['rows'] = &$rowsElementsAndInfo['rows'];
6a488035 883
e4e1db4b 884 self::dedupePair($rowsElementsAndInfo['migration_info'], $resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString);
6a488035
TO
885 }
886
887 if ($cacheKeyString && !$redirectForPerformance) {
888 // retrieve next pair of dupes
2988f5c7 889 // @todo call getDuplicatePairs.
6a488035
TO
890 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
891 $cacheParams['join'],
66eceb0b 892 $cacheParams['where'],
893 0,
ed3c1599 894 $cacheParams['limit'],
2c16165a 895 [],
66eceb0b 896 '',
897 FALSE
6a488035
TO
898 );
899 }
900 else {
901 // do not proceed. Terminate the loop
902 unset($dupePairs);
903 }
904 }
63ef778e 905
906 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
6a488035
TO
907 return $resultStats;
908 }
909
910 /**
911 * A function which uses various rules / algorithms for choosing which contact to bias to
912 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
913 *
98997235
TO
914 * @param int $mainId
915 * Main contact with whom merge has to happen.
916 * @param int $otherId
917 * Duplicate contact which would be deleted after merge operation.
918 * @param array $migrationInfo
919 * Array of information about which elements to merge.
920 * @param string $mode
921 * Helps decide how to behave when there are conflicts.
13919cf8
J
922 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
923 * - Does a force merge otherwise (aggressive mode).
6a488035 924 *
ad37ac8e 925 * @param array $conflicts
a2abc387 926 * An empty array to be filed with conflict information.
ad37ac8e 927 *
77b97be7 928 * @return bool
6a488035 929 */
2c16165a 930 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) {
0971143c 931
a2abc387 932 $conflicts = self::getConflicts($migrationInfo, $mainId, $otherId, $mode);
6a488035
TO
933
934 if (!empty($conflicts)) {
935 foreach ($conflicts as $key => $val) {
936 if ($val === NULL and $mode == 'safe') {
63ef778e 937 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
6a488035
TO
938 return TRUE;
939 }
940 else {
941 // copy over the resolved values
942 $migrationInfo[$key] = $val;
943 }
944 }
fd630ef9 945 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
a2abc387 946 return (bool) $migrationInfo['skip_merge'];
6a488035
TO
947 }
948 return FALSE;
949 }
950
d48ad2c0 951 /**
952 * Compare 2 addresses to see if they are the same.
953 *
954 * @param array $mainAddress
955 * @param array $comparisonAddress
956 *
957 * @return bool
958 */
518fa0ee 959 public static function locationIsSame($mainAddress, $comparisonAddress) {
2c16165a 960 $keysToIgnore = [
961 'id',
962 'is_primary',
963 'is_billing',
964 'manual_geo_code',
965 'contact_id',
966 'reset_date',
967 'hold_date',
968 ];
d48ad2c0 969 foreach ($comparisonAddress as $field => $value) {
970 if (in_array($field, $keysToIgnore)) {
971 continue;
972 }
00443529 973 if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
d48ad2c0 974 return FALSE;
975 }
976 }
977 return TRUE;
978 }
979
34917198
J
980 /**
981 * A function to build an array of information about location blocks that is
982 * required when merging location fields
983 *
984 * @return array
985 */
986 public static function getLocationBlockInfo() {
2c16165a 987 $locationBlocks = [
988 'address' => [
34917198
J
989 'label' => 'Address',
990 'displayField' => 'display',
991 'sortString' => 'location_type_id',
992 'hasLocation' => TRUE,
993 'hasType' => FALSE,
2c16165a 994 ],
995 'email' => [
34917198 996 'label' => 'Email',
2a7e1ddc 997 'displayField' => 'display',
34917198
J
998 'sortString' => 'location_type_id',
999 'hasLocation' => TRUE,
1000 'hasType' => FALSE,
2c16165a 1001 ],
1002 'im' => [
34917198
J
1003 'label' => 'IM',
1004 'displayField' => 'name',
1005 'sortString' => 'location_type_id,provider_id',
1006 'hasLocation' => TRUE,
1007 'hasType' => 'provider_id',
2c16165a 1008 ],
1009 'phone' => [
34917198
J
1010 'label' => 'Phone',
1011 'displayField' => 'phone',
1012 'sortString' => 'location_type_id,phone_type_id',
1013 'hasLocation' => TRUE,
1014 'hasType' => 'phone_type_id',
2c16165a 1015 ],
1016 'website' => [
34917198
J
1017 'label' => 'Website',
1018 'displayField' => 'url',
1019 'sortString' => 'website_type_id',
1020 'hasLocation' => FALSE,
1021 'hasType' => 'website_type_id',
2c16165a 1022 ],
1023 ];
34917198
J
1024 return $locationBlocks;
1025 }
1026
6a488035
TO
1027 /**
1028 * A function to build an array of information required by merge function and the merge UI.
1029 *
98997235
TO
1030 * @param int $mainId
1031 * Main contact with whom merge has to happen.
1032 * @param int $otherId
1033 * Duplicate contact which would be deleted after merge operation.
201057c0 1034 * @param bool $checkPermissions
1035 * Should the logged in user's permissions be ignore. Setting this to false is
1036 * highly risky as it could cause data to be lost due to conflicts not showing up.
1037 * OTOH there is a risk a merger might view custom data they do not have permission to.
1038 * Hence for now only making this really explicit and making it reflect perms in
1039 * an api call.
1040 *
1041 * @todo review permissions issue!
6a488035 1042 *
77b97be7 1043 * @return array|bool|int
1e3e0eed
J
1044 *
1045 * rows => An array of arrays, each is row of merge information for the table
1046 * Format: move_fieldname, eg: move_contact_type
1047 * main => Value associated with the main contact
1048 * other => Value associated with the other contact
1049 * title => The title of the field to display in the merge table
1050 *
1051 * elements => An array of form elements for the merge UI
1052 *
1053 * rel_table_elements => An array of form elements for the merge UI for
1054 * entities related to the contact (eg: checkbox to move 'mailings')
1055 *
1e3e0eed
J
1056 * rel_tables => Stores the tables that have related entities for the contact
1057 * for example mailings, groups
1058 *
1059 * main_details => An array of core contact field values, eg: first_name, etc.
1060 * location_blocks => An array of location block data for the main contact
1061 * stored as the 'result' of an API call.
1062 * eg: main_details['location_blocks']['address'][0]['id']
1063 * eg: main_details['location_blocks']['email'][1]['id']
1064 *
1065 * other_details => As above, but for the 'other' contact
1066 *
1067 * migration_info => Stores the 'default' merge actions for each field which
1068 * is used when programatically merging contacts. It contains instructions
1069 * to move all fields from the 'other' contact to the 'main' contact, as
1070 * though the form had been submitted with those options.
1071 *
3058f4d9 1072 * @throws \CRM_Core_Exception
1073 * @throws \CiviCRM_API3_Exception
1074 * @throws \Exception
6a488035 1075 */
201057c0 1076 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
6a488035 1077 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
74a6069d 1078 $fields = self::getMergeFieldsMetadata();
6a488035 1079
fcc3d8ee 1080 $main = self::getMergeContactDetails($mainId);
1081 $other = self::getMergeContactDetails($otherId);
6a488035 1082
4eea8606 1083 $compareFields = self::retrieveFields($main, $other);
6a488035 1084
2c16165a 1085 $rows = $elements = $relTableElements = $migrationInfo = [];
6a488035 1086
4eea8606 1087 foreach ($compareFields['contact'] as $field) {
4d5f18cc 1088 if ($field == 'contact_sub_type') {
1089 // CRM-15681 don't display sub-types in UI
1090 continue;
1091 }
47019034 1092 foreach (['main' => $main, 'other' => $other] as $moniker => $contact) {
045b2167 1093 $value = $label = CRM_Utils_Array::value($field, $contact);
1094 $fieldSpec = $fields[$field];
1095 if (!empty($fieldSpec['serialize']) && is_array($value)) {
1096 // In practice this only applies to preferred_communication_method as the sub types are skipped above
1097 // and no others are serialized.
1098 $labels = [];
1099 foreach ($value as $individualValue) {
1100 $labels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue);
1101 }
1102 $label = implode(', ', $labels);
1103 // We serialize this due to historic handling but it's likely that if we just left it as an
1104 // array all would be well & we would have less code.
1105 $value = CRM_Core_DAO::serializeField($value, $fieldSpec['serialize']);
6a488035 1106 }
045b2167 1107 elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type::T_DATE) {
6a488035
TO
1108 if ($value) {
1109 $value = str_replace('-', '', $value);
1110 $label = CRM_Utils_Date::customFormat($label);
1111 }
1112 else {
1113 $value = "null";
1114 }
1115 }
a7488080 1116 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
6a488035
TO
1117 if ($label === '0') {
1118 $label = ts('[ ]');
1119 }
1120 if ($label === '1') {
1121 $label = ts('[x]');
1122 }
00f3da2e 1123 }
045b2167 1124 elseif (!empty($fieldSpec['pseudoconstant'])) {
1125 $label = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $value);
4f88c9cf
C
1126 }
1127 elseif ($field == 'current_employer_id' && !empty($value)) {
1128 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
1129 }
6a488035
TO
1130 $rows["move_$field"][$moniker] = $label;
1131 if ($moniker == 'other') {
7154d2a4
BS
1132 //CRM-14334
1133 if ($value === NULL || $value == '') {
6a488035
TO
1134 $value = 'null';
1135 }
1136 if ($value === 0 or $value === '0') {
1137 $value = $qfZeroBug;
1138 }
8cc574cf 1139 if (is_array($value) && empty($value[1])) {
6a488035
TO
1140 $value[1] = NULL;
1141 }
13919cf8
J
1142
1143 // Display a checkbox to migrate, only if the values are different
1144 if ($value != $main[$field]) {
2c16165a 1145 $elements[] = [
1146 'advcheckbox',
1147 "move_$field",
1148 NULL,
1149 NULL,
1150 NULL,
1151 $value,
1152 ];
13919cf8
J
1153 }
1154
6a488035
TO
1155 $migrationInfo["move_$field"] = $value;
1156 }
1157 }
1158 $rows["move_$field"]['title'] = $fields[$field]['title'];
1159 }
1160
eb61dc07
J
1161 // Handle location blocks.
1162 // @todo OpenID not in API yet, so is not supported here.
65a35632 1163
087f00ec 1164 // Set up useful information about the location blocks
34917198 1165 $locationBlocks = self::getLocationBlockInfo();
087f00ec 1166
2c16165a 1167 $locations = [
1168 'main' => [],
1169 'other' => [],
1170 ];
b814df56 1171
087f00ec 1172 // @todo This could probably be defined and used earlier
2c16165a 1173 $mergeTargets = [
087f00ec
J
1174 'main' => $mainId,
1175 'other' => $otherId,
2c16165a 1176 ];
6a488035 1177
087f00ec 1178 foreach ($locationBlocks as $blockName => $blockInfo) {
6a488035 1179
087f00ec
J
1180 // Collect existing fields from both 'main' and 'other' contacts first
1181 // This allows us to match up location/types when building the table rows
1182 foreach ($mergeTargets as $moniker => $cid) {
2c16165a 1183 $searchParams = [
b932e89e 1184 'contact_id' => $cid,
087f00ec 1185 // CRM-17556 Order by field-specific criteria
2c16165a 1186 'options' => [
087f00ec 1187 'sort' => $blockInfo['sortString'],
2c16165a 1188 ],
1189 ];
0b50eca0 1190 $values = civicrm_api3($blockName, 'get', $searchParams);
087f00ec
J
1191 if ($values['count']) {
1192 $cnt = 0;
bf588234 1193 foreach ($values['values'] as $value) {
087f00ec
J
1194 $locations[$moniker][$blockName][$cnt] = $value;
1195 // Fix address display
eb61dc07 1196 if ($blockName == 'address') {
087f00ec 1197 CRM_Core_BAO_Address::fixAddress($value);
ae6455b2 1198 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address::format($value);
6a488035 1199 }
2a7e1ddc
TS
1200 // Fix email display
1201 elseif ($blockName == 'email') {
1202 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Mail::format($value);
1203 }
abb422f9 1204
087f00ec 1205 $cnt++;
6a488035
TO
1206 }
1207 }
1208 }
6a488035 1209
087f00ec
J
1210 // Now, build the table rows appropriately, based off the information on
1211 // the 'other' contact
34917198
J
1212 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1213 foreach ($locations['other'][$blockName] as $count => $value) {
6a488035 1214
087f00ec 1215 $displayValue = $value[$blockInfo['displayField']];
65a35632 1216
087f00ec
J
1217 // Add this value to the table rows
1218 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
65a35632 1219
087f00ec
J
1220 // CRM-17556 Only display 'main' contact value if it's the same location + type
1221 // Look it up from main values...
65a35632 1222
087f00ec
J
1223 $lookupLocation = FALSE;
1224 if ($blockInfo['hasLocation']) {
1225 $lookupLocation = $value['location_type_id'];
1226 }
65a35632 1227
087f00ec
J
1228 $lookupType = FALSE;
1229 if ($blockInfo['hasType']) {
13cc4cac 1230 $lookupType = CRM_Utils_Array::value($blockInfo['hasType'], $value);
087f00ec 1231 }
65a35632 1232
34917198
J
1233 // Hold ID of main contact's matching block
1234 $mainContactBlockId = 0;
1235
087f00ec
J
1236 if (!empty($locations['main'][$blockName])) {
1237 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1238 // No location/type, or matching location and type
1239 if (
1240 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
1241 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
1242 ) {
34917198 1243 // Set this value as the default against the 'other' contact value
087f00ec 1244 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
041d6d6b 1245 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
86b14b59 1246 $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
34917198 1247 $mainContactBlockId = $mainValueCheck['id'];
087f00ec
J
1248 break;
1249 }
6a488035 1250 }
087f00ec 1251 }
65a35632 1252
087f00ec 1253 // Add checkbox to migrate data from 'other' to 'main'
2c16165a 1254 $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
65a35632 1255
abd0b852 1256 // Add checkbox to set the 'other' location as primary
2c16165a 1257 $elements[] = [
1258 'advcheckbox',
1259 "location_blocks[$blockName][$count][set_other_primary]",
1260 NULL,
1261 ts('Set as primary'),
1262 ];
abd0b852 1263
087f00ec
J
1264 // Flag up this field to skipMerge function (@todo: do we need to?)
1265 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
65a35632 1266
34917198 1267 // Add a hidden field to store the ID of the target main contact block
2c16165a 1268 $elements[] = [
1269 'hidden',
1270 "location_blocks[$blockName][$count][mainContactBlockId]",
1271 $mainContactBlockId,
1272 ];
34917198 1273
087f00ec
J
1274 // Setup variables
1275 $thisTypeId = FALSE;
1276 $thisLocId = FALSE;
65a35632 1277
087f00ec
J
1278 // Provide a select drop-down for the location's location type
1279 // eg: Home, Work...
65a35632 1280
087f00ec
J
1281 if ($blockInfo['hasLocation']) {
1282
5b28be84 1283 // Load the location options for this entity
2c16165a 1284 $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
5b28be84 1285
087f00ec
J
1286 $thisLocId = $value['location_type_id'];
1287
1288 // Put this field's location type at the top of the list
5b28be84 1289 $tmpIdList = $locationOptions['values'];
2c16165a 1290 $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
087f00ec
J
1291 unset($tmpIdList[$thisLocId]);
1292
1293 // Add the element
2c16165a 1294 $elements[] = [
eb61dc07 1295 'select',
972947a7 1296 "location_blocks[$blockName][$count][locTypeId]",
eb61dc07 1297 NULL,
087f00ec 1298 $defaultLocId + $tmpIdList,
2c16165a 1299 ];
087f00ec
J
1300
1301 // Add the relevant information to the $migrationInfo
1302 // Keep location-type-id same as that of other-contact
1303 // @todo Check this logic out
1304 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
abb422f9 1305 if ($blockName != 'address') {
2c16165a 1306 $elements[] = [
1307 'advcheckbox',
1308 "location_blocks[{$blockName}][$count][operation]",
1309 NULL,
1310 ts('Add new'),
1311 ];
087f00ec 1312 // always use add operation
abb422f9 1313 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
6a488035 1314 }
087f00ec 1315
6a488035 1316 }
6a488035 1317
087f00ec
J
1318 // Provide a select drop-down for the location's type/provider
1319 // eg websites: Google+, Facebook...
1320
087f00ec
J
1321 if ($blockInfo['hasType']) {
1322
5b28be84 1323 // Load the type options for this entity
2c16165a 1324 $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
5b28be84 1325
13cc4cac 1326 $thisTypeId = CRM_Utils_Array::value($blockInfo['hasType'], $value);
087f00ec
J
1327
1328 // Put this field's location type at the top of the list
5b28be84 1329 $tmpIdList = $typeOptions['values'];
2c16165a 1330 $defaultTypeId = [$thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList)];
087f00ec
J
1331 unset($tmpIdList[$thisTypeId]);
1332
1333 // Add the element
2c16165a 1334 $elements[] = [
65a35632 1335 'select',
972947a7 1336 "location_blocks[$blockName][$count][typeTypeId]",
65a35632 1337 NULL,
087f00ec 1338 $defaultTypeId + $tmpIdList,
2c16165a 1339 ];
65a35632 1340
1e3e0eed 1341 // Add the information to the migrationInfo
34917198 1342 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
65a35632 1343
6a488035 1344 }
087f00ec
J
1345
1346 // Set the label for this row
34917198
J
1347 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
1348 if (!empty($thisLocId)) {
5b28be84 1349 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
6a488035 1350 }
34917198 1351 if (!empty($thisTypeId)) {
5b28be84 1352 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
34917198
J
1353 }
1354 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
65a35632 1355
34917198 1356 } // End loop through 'other' locations of this type
087f00ec 1357
34917198 1358 } // End if 'other' location for this type exists
6a488035 1359
34917198 1360 } // End loop through each location block entity
6a488035
TO
1361
1362 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1363 $config = CRM_Core_Config::singleton();
1364 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1365 $mainUser = NULL;
1366 if ($mainUfId) {
1367 // d6 compatible
1368 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1369 $mainUser = user_load($mainUfId);
1370 }
1371 elseif ($config->userFramework == 'Joomla') {
1372 $mainUser = JFactory::getUser($mainUfId);
1373 }
1374 }
1375 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1376 $otherUser = NULL;
1377 if ($otherUfId) {
1378 // d6 compatible
1379 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1380 $otherUser = user_load($otherUfId);
1381 }
1382 elseif ($config->userFramework == 'Joomla') {
1383 $otherUser = JFactory::getUser($otherUfId);
1384 }
1385 }
1386
1387 $relTables = CRM_Dedupe_Merger::relTables();
1388 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1389 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1390 foreach ($relTables as $name => $null) {
1391 if (!in_array($name, $activeRelTables) &&
1392 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1393 ) {
1394 unset($relTables[$name]);
1395 continue;
1396 }
1397
2c16165a 1398 $relTableElements[] = ['checkbox', "move_$name"];
6a488035
TO
1399 $migrationInfo["move_$name"] = 1;
1400
1401 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1402 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1403 if ($name == 'rel_table_users') {
1404 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1405 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
2c16165a 1406 $find = ['$ufid', '$ufname'];
6a488035 1407 if ($mainUser) {
2c16165a 1408 $replace = [$mainUfId, $mainUser->name];
6a488035
TO
1409 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1410 }
1411 if ($otherUser) {
2c16165a 1412 $replace = [$otherUfId, $otherUser->name];
6a488035
TO
1413 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1414 }
1415 }
1416 if ($name == 'rel_table_memberships') {
7d84a47d
JP
1417 //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
1418 $attributes = ['checked' => 'checked'];
1419 $otherContactMemberships = CRM_Member_BAO_Membership::getAllContactMembership($otherId);
1420 foreach ($otherContactMemberships as $membership) {
1421 $mainMembership = CRM_Member_BAO_Membership::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
1422 if ($mainMembership) {
1423 $attributes = [];
1424 }
1425 }
2c16165a 1426 $elements[] = [
1427 'checkbox',
1428 "operation[move_{$name}][add]",
1429 NULL,
1430 ts('add new'),
1431 $attributes,
1432 ];
6a488035
TO
1433 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1434 }
1435 }
1436 foreach ($relTables as $name => $null) {
1437 $relTables["move_$name"] = $relTables[$name];
1438 unset($relTables[$name]);
1439 }
1440
1441 // handle custom fields
201057c0 1442 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1,
1443 CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035 1444 );
0b330e6d 1445 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1,
201057c0 1446 CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035 1447 );
6a488035
TO
1448
1449 foreach ($otherTree as $gid => $group) {
1450 $foundField = FALSE;
1451 if (!isset($group['fields'])) {
1452 continue;
1453 }
1454
1455 foreach ($group['fields'] as $fid => $field) {
4eea8606 1456 if (in_array($fid, $compareFields['custom'])) {
6a488035
TO
1457 if (!$foundField) {
1458 $rows["custom_group_$gid"]['title'] = $group['title'];
1459 $foundField = TRUE;
1460 }
a7488080 1461 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
6a488035 1462 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
51a3717f 1463 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1464 }
1465 }
1466 $value = "null";
a7488080 1467 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
6a488035 1468 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
51a3717f 1469 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1470 if ($values['data'] === 0 || $values['data'] === '0') {
1471 $values['data'] = $qfZeroBug;
d58a19a1 1472 }
6a488035 1473 $value = ($values['data']) ? $values['data'] : $value;
d58a19a1 1474 }
6a488035
TO
1475 }
1476 $rows["move_custom_$fid"]['title'] = $field['label'];
1477
2c16165a 1478 $elements[] = [
1479 'advcheckbox',
1480 "move_custom_$fid",
1481 NULL,
1482 NULL,
1483 NULL,
1484 $value,
1485 ];
6a488035
TO
1486 $migrationInfo["move_custom_$fid"] = $value;
1487 }
1488 }
1489 }
abb422f9 1490
2c16165a 1491 $result = [
6a488035
TO
1492 'rows' => $rows,
1493 'elements' => $elements,
1494 'rel_table_elements' => $relTableElements,
6a488035
TO
1495 'rel_tables' => $relTables,
1496 'main_details' => $main,
1497 'other_details' => $other,
1498 'migration_info' => $migrationInfo,
2c16165a 1499 ];
6a488035 1500
34917198
J
1501 $result['main_details']['location_blocks'] = $locations['main'];
1502 $result['other_details']['location_blocks'] = $locations['other'];
6a488035
TO
1503
1504 return $result;
1505 }
1506
1507 /**
1508 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1509 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1510 * A superset of moveContactBelongings() function.
1511 *
98997235
TO
1512 * @param int $mainId
1513 * Main contact with whom merge has to happen.
1514 * @param int $otherId
1515 * Duplicate contact which would be deleted after merge operation.
77b97be7
EM
1516 *
1517 * @param $migrationInfo
6a488035 1518 *
3058f4d9 1519 * @param bool $checkPermissions
1520 * Respect logged in user permissions.
1521 *
77b97be7 1522 * @return bool
6a488035 1523 */
3058f4d9 1524 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
6a488035
TO
1525 if (empty($migrationInfo)) {
1526 return FALSE;
1527 }
119664d6 1528 // Encapsulate in a transaction to avoid half-merges.
1529 $transaction = new CRM_Core_Transaction();
6a488035 1530
1acd98ec 1531 $contactType = $migrationInfo['main_details']['contact_type'];
6a488035 1532 $relTables = CRM_Dedupe_Merger::relTables();
35e0e03e 1533 $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
ae2346d4 1534
54ed517e 1535 self::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
6a488035 1536 foreach ($migrationInfo as $key => $value) {
08b00099
CR
1537
1538 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
6a488035 1539 $submitted[substr($key, 5)] = $value;
ae2346d4 1540 $submittedCustomFields[] = substr($key, 12);
6a488035 1541 }
08b00099 1542 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) {
6a488035
TO
1543 $submitted[substr($key, 5)] = $value;
1544 }
6a488035
TO
1545 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1546 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1547 if (array_key_exists('operation', $migrationInfo)) {
1548 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1549 if (array_key_exists($key, $migrationInfo['operation'])) {
1550 $tableOperations[$table] = $migrationInfo['operation'][$key];
1551 }
1552 }
1553 }
1554 }
4099a9c5
AP
1555 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
1556 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1557 }
6a488035 1558 }
35e0e03e 1559 self::mergeLocations($mainId, $otherId, $migrationInfo);
6a488035 1560
6a488035 1561 // **** Do contact related migrations
ae2346d4 1562 $customTablesToCopyValues = self::getAffectedCustomTables($submittedCustomFields);
0556db5d
CR
1563 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1564 unset($moveTables, $tableOperations);
6a488035 1565
4099a9c5
AP
1566 // **** Do table related removals
1567 if (!empty($removeTables)) {
1568 // **** CRM-20421
1569 CRM_Dedupe_Merger::removeContactBelongings($otherId, $removeTables);
2c16165a 1570 $removeTables = [];
4099a9c5
AP
1571 }
1572
6a488035 1573 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
2c16165a 1574 $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
1575 $names['individual_prefix'] = [
1576 'newName' => 'prefix_id',
1577 'groupName' => 'individual_prefix',
1578 ];
1579 $names['individual_suffix'] = [
1580 'newName' => 'suffix_id',
1581 'groupName' => 'individual_suffix',
1582 ];
1583 $names['communication_style'] = [
1584 'newName' => 'communication_style_id',
1585 'groupName' => 'communication_style',
1586 ];
1587 $names['addressee'] = [
1588 'newName' => 'addressee_id',
1589 'groupName' => 'addressee',
1590 ];
1591 $names['email_greeting'] = [
1592 'newName' => 'email_greeting_id',
1593 'groupName' => 'email_greeting',
1594 ];
1595 $names['postal_greeting'] = [
1596 'newName' => 'postal_greeting_id',
1597 'groupName' => 'postal_greeting',
1598 ];
6a488035 1599 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
6a488035 1600 // fix custom fields so they're edible by createProfileContact()
f941d73a 1601 $cFields = self::getCustomFieldMetadata($contactType);
6a488035
TO
1602
1603 if (!isset($submitted)) {
2c16165a 1604 $submitted = [];
6a488035 1605 }
830ee2be 1606 $customFiles = [];
6a488035 1607 foreach ($submitted as $key => $value) {
830ee2be 1608 list($cFields, $customFiles, $submitted) = self::processCustomFields($mainId, $key, $cFields, $customFiles, $submitted, $value);
6a488035
TO
1609 }
1610
49580579 1611 self::processCustomFieldFiles($mainId, $otherId, $customFiles);
6a488035
TO
1612
1613 // move view only custom fields CRM-5362
2c16165a 1614 $viewOnlyCustomFields = [];
6a488035 1615 foreach ($submitted as $key => $value) {
ca38a45b 1616 $fid = CRM_Core_BAO_CustomField::getKeyID($key);
1617 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1618 ) {
6a488035
TO
1619 $viewOnlyCustomFields[$key] = $value;
1620 }
1621 }
6a488035
TO
1622 // special case to set values for view only, CRM-5362
1623 if (!empty($viewOnlyCustomFields)) {
1624 $viewOnlyCustomFields['entityID'] = $mainId;
1625 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1626 }
1627
3058f4d9 1628 if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') &&
2c16165a 1629 CRM_Core_Permission::check('delete contacts'))
6a488035
TO
1630 ) {
1631 // if ext id is submitted then set it null for contact to be deleted
a7488080 1632 if (!empty($submitted['external_identifier'])) {
6a488035
TO
1633 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1634 CRM_Core_DAO::executeQuery($query);
1635 }
2c16165a 1636 civicrm_api3('contact', 'delete', ['id' => $otherId]);
6a488035 1637 }
6a488035 1638
4d5f18cc 1639 // CRM-15681 merge sub_types
35522279
J
1640 if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) {
1641 if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) {
481a74f4 1642 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
0db6c3e1
TO
1643 }
1644 else {
4d5f18cc 1645 $submitted['contact_sub_type'] = $other_sub_types;
1646 }
1647 }
1648
6a488035
TO
1649 // **** Update contact related info for the main contact
1650 if (!empty($submitted)) {
1651 $submitted['contact_id'] = $mainId;
1652
1653 //update current employer field
1654 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1655 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1656 $submitted['current_employer'] = $submitted['current_employer_id'];
0db6c3e1
TO
1657 }
1658 else {
6a488035
TO
1659 $submitted['current_employer'] = '';
1660 }
1661 unset($submitted['current_employer_id']);
1662 }
1663
00f3da2e 1664 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
481a74f4 1665 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
00f3da2e
BS
1666 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1667 }
481a74f4 1668 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
00f3da2e
BS
1669 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1670 }
1671
6a488035 1672 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
6a488035 1673 }
119664d6 1674 $transaction->commit();
1273d77c 1675 CRM_Utils_Hook::post('merge', 'Contact', $mainId);
f00283b5 1676 self::createMergeActivities($mainId, $otherId);
5ea06a7b 1677
6a488035
TO
1678 return TRUE;
1679 }
16254ae1 1680
ae2346d4
CR
1681 /**
1682 * Builds an Array of Custom tables for given custom field ID's.
1683 *
1684 * @param $customFieldIDs
1685 *
1686 * @return array
1687 * Array of custom table names
1688 */
1689 private static function getAffectedCustomTables($customFieldIDs) {
2c16165a 1690 $customTableToCopyValues = [];
ae2346d4
CR
1691
1692 foreach ($customFieldIDs as $fieldID) {
1693 if (!empty($fieldID)) {
2c16165a 1694 $customField = civicrm_api3('custom_field', 'getsingle', [
08b00099
CR
1695 'id' => $fieldID,
1696 'is_active' => TRUE,
2c16165a 1697 ]);
08b00099 1698 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
2c16165a 1699 $customGroup = civicrm_api3('custom_group', 'getsingle', [
08b00099 1700 'id' => $customField['custom_group_id'],
ae2346d4 1701 'is_active' => TRUE,
2c16165a 1702 ]);
ae2346d4
CR
1703
1704 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1705 $customTableToCopyValues[] = $customGroup['table_name'];
1706 }
1707 }
1708 }
1709 }
1710
1711 return $customTableToCopyValues;
1712 }
1713
16254ae1 1714 /**
f00283b5 1715 * Get fields in the contact table suitable for merging.
1716 *
a6c01b45 1717 * @return array
f00283b5 1718 * Array of field names to be potentially merged.
16254ae1 1719 */
00be9182 1720 public static function getContactFields() {
16254ae1 1721 $contactFields = CRM_Contact_DAO_Contact::fields();
2c16165a 1722 $invalidFields = [
353ffa53 1723 'api_key',
353ffa53
TO
1724 'created_date',
1725 'display_name',
1726 'hash',
1727 'id',
1728 'modified_date',
1729 'primary_contact_id',
1730 'sort_name',
c301f76e 1731 'user_unique_id',
2c16165a 1732 ];
bdd7870e
RN
1733 foreach ($contactFields as $field => $value) {
1734 if (in_array($field, $invalidFields)) {
1735 unset($contactFields[$field]);
1736 }
1737 }
16254ae1
ARW
1738 return array_keys($contactFields);
1739 }
ada104d5
AW
1740
1741 /**
1742 * Added for CRM-12695
c301f76e 1743 * Based on the contactID provided
ada104d5
AW
1744 * add/update membership(s) to related contacts
1745 *
c301f76e 1746 * @param int $contactID
ada104d5 1747 */
00be9182 1748 public static function addMembershipToRealtedContacts($contactID) {
ada104d5
AW
1749 $dao = new CRM_Member_DAO_Membership();
1750 $dao->contact_id = $contactID;
1751 $dao->is_test = 0;
1752 $dao->find();
1753
1754 //checks membership of contact itself
1755 while ($dao->fetch()) {
1756 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1757 if ($relationshipTypeId) {
2c16165a 1758 $membershipParams = [
ada104d5
AW
1759 'id' => $dao->id,
1760 'contact_id' => $dao->contact_id,
1761 'membership_type_id' => $dao->membership_type_id,
1762 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1763 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1764 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1765 'source' => $dao->source,
21dfd5f5 1766 'status_id' => $dao->status_id,
2c16165a 1767 ];
ada104d5
AW
1768 // create/update membership(s) for related contact(s)
1769 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1770 } // end of if relationshipTypeId
1771 }
1772 }
96025800 1773
f00283b5 1774 /**
1775 * Create activities tracking the merge on affected contacts.
1776 *
1777 * @param int $mainId
1778 * @param int $otherId
1779 *
1780 * @throws \CiviCRM_API3_Exception
1781 */
1782 public static function createMergeActivities($mainId, $otherId) {
2c16165a 1783 $params = [
f00283b5 1784 1 => $otherId,
1785 2 => $mainId,
2c16165a 1786 ];
1787 $activity = civicrm_api3('activity', 'create', [
dc33398e 1788 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
518fa0ee 1789 $mainId,
f00283b5 1790 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1791 'target_contact_id' => $mainId,
1792 'activity_type_id' => 'Contact Merged',
1793 'status_id' => 'Completed',
2c16165a 1794 ]);
1795 if (civicrm_api3('Setting', 'getvalue', [
1796 'name' => 'contact_undelete',
1797 'group' => 'CiviCRM Preferences',
1798 ])) {
1799 civicrm_api3('activity', 'create', [
dc33398e 1800 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
518fa0ee 1801 $otherId,
4d834a99 1802 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1803 'target_contact_id' => $otherId,
1804 'activity_type_id' => 'Contact Deleted by Merge',
1805 'parent_id' => $activity['id'],
1806 'status_id' => 'Completed',
2c16165a 1807 ]);
4d834a99 1808 }
f00283b5 1809 }
1810
2988f5c7 1811 /**
1812 * Get Duplicate Pairs based on a rule for a group.
1813 *
1814 * @param int $rule_group_id
1815 * @param int $group_id
1816 * @param bool $reloadCacheIfEmpty
917acf6f 1817 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
2988f5c7 1818 * @param int $batchLimit
1819 * @param bool $isSelected
5721d85e 1820 * Limit to selected pairs.
66eceb0b 1821 * @param bool $includeConflicts
e23e26ec 1822 * @param array $criteria
1823 * Additional criteria to narrow down the merge group.
2988f5c7 1824 *
3058f4d9 1825 * @param bool $checkPermissions
1826 * Respect logged in user permissions.
1827 *
21a95d83 1828 * @param int $searchLimit
1829 * Limit to searching for matches against this many contacts.
1830 *
2988f5c7 1831 * @return array
518fa0ee 1832 * Array of matches meeting the criteria.
9c5fe572 1833 *
1834 * @throws \CRM_Core_Exception
1835 * @throws \CiviCRM_API3_Exception
2988f5c7 1836 */
9c5fe572 1837 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0) {
4107e11e 1838 $dupePairs = self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions);
2988f5c7 1839 if (empty($dupePairs) && $reloadCacheIfEmpty) {
4107e11e 1840 $cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions);
2988f5c7 1841 // If we haven't found any dupes, probably cache is empty.
66eceb0b 1842 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1843 // until we have done some processing.
21a95d83 1844 CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions, $searchLimit);
4107e11e 1845 return self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions);
2988f5c7 1846 }
1847 return $dupePairs;
1848 }
1849
2ae26001 1850 /**
1851 * Get the cache key string for the merge action.
1852 *
1853 * @param int $rule_group_id
1854 * @param int $group_id
e23e26ec 1855 * @param array $criteria
1856 * Additional criteria to narrow down the merge group.
1857 * Currently we are only supporting the key 'contact' within it.
2ae26001 1858 *
3058f4d9 1859 * @param bool $checkPermissions
1860 * Respect the users permissions.
1861 *
2ae26001 1862 * @return string
1863 */
2c16165a 1864 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = [], $checkPermissions = TRUE) {
2ae26001 1865 $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
9d2f6d53 1866 $cacheKeyString = "merge_{$contactType}";
2ae26001 1867 $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
1868 $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
629dd4f3 1869 $cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0';
3058f4d9 1870 if ($checkPermissions) {
1871 $contactID = CRM_Core_Session::getLoggedInContactID();
1872 if (!$contactID) {
1873 // Distinguish between no permission check & no logged in user.
1874 $contactID = 'null';
1875 }
1876 $cacheKeyString .= '_' . $contactID;
1877 }
1878 else {
1879 $cacheKeyString .= '_0';
1880 }
2ae26001 1881 return $cacheKeyString;
1882 }
1883
74a6069d 1884 /**
1885 * Get the metadata for the merge fields.
1886 *
1887 * This is basically the contact metadata, augmented with fields to
1888 * represent email greeting, postal greeting & addressee.
1889 *
1890 * @return array
1891 */
1892 public static function getMergeFieldsMetadata() {
1893 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) {
1894 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1895 }
1896 $fields = CRM_Contact_DAO_Contact::fields();
2c16165a 1897 static $optionValueFields = [];
74a6069d 1898 if (empty($optionValueFields)) {
1899 $optionValueFields = CRM_Core_OptionValue::getFields();
1900 }
1901 foreach ($optionValueFields as $field => $params) {
1902 $fields[$field]['title'] = $params['title'];
1903 }
1904 \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields;
1905 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1906 }
1907
1908 /**
1909 * Get the details of the contact to be merged.
1910 *
1911 * @param int $contact_id
74a6069d 1912 *
1913 * @return array
1914 *
1915 * @throws CRM_Core_Exception
1916 */
fcc3d8ee 1917 public static function getMergeContactDetails($contact_id) {
2c16165a 1918 $params = [
74a6069d 1919 'contact_id' => $contact_id,
1920 'version' => 3,
2c16165a 1921 'return' => array_merge(['display_name'], self::getContactFields()),
1922 ];
74a6069d 1923 $result = civicrm_api('contact', 'get', $params);
1924
1925 // CRM-18480: Cancel the process if the contact is already deleted
1926 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
2c16165a 1927 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
fcc3d8ee 1928 1 => $contact_id,
2c16165a 1929 ]));
74a6069d 1930 }
1931
1932 return $result['values'][$contact_id];
1933 }
1934
92a77772 1935 /**
1936 * Merge location.
1937 *
1938 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
1939 *
1940 * The data is in the format received from the merge form (which is a fairly confusing format).
1941 *
1942 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
1943 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
1944 * been calculated and before saving because
1945 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
1946 * - passing to a hook right before save means calculations only have to be done once
1947 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
1948 * ugly.
1949 *
1950 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
16d4e0b7 1951 * is likely to be significant data in merge hooks.
92a77772 1952 *
1953 * @param int $mainId
1954 * @param int $otherId
92a77772 1955 *
1956 * @param array $migrationInfo
1957 * Migration info for the merge. This is passed to the hook as informational only.
1958 */
35e0e03e 1959 public static function mergeLocations($mainId, $otherId, $migrationInfo) {
1960 foreach ($migrationInfo as $key => $value) {
1961 $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL);
1962 if (!$isLocationField) {
1963 continue;
1964 }
92a77772 1965 $locField = explode('_', $key);
1966 $fieldName = $locField[2];
1967 $fieldCount = $locField[3];
1968
1969 // Set up the operation type (add/overwrite)
1970 // Ignore operation for websites
1971 // @todo Tidy this up
1972 $operation = 0;
1973 if ($fieldName != 'website') {
1974 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1975 }
1976 // default operation is overwrite.
1977 if (!$operation) {
1978 $operation = 2;
1979 }
1980 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1981 }
2c16165a 1982 $blocksDAO = [];
92a77772 1983
1984 // @todo Handle OpenID (not currently in API).
1985 if (!empty($locBlocks)) {
1986 $locationBlocks = self::getLocationBlockInfo();
1987
2c16165a 1988 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_primary' => 1]);
1989 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_billing' => 1]);
92a77772 1990
1991 foreach ($locBlocks as $name => $block) {
2c16165a 1992 $blocksDAO[$name] = ['delete' => [], 'update' => []];
92a77772 1993 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1994 continue;
1995 }
1996 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
abd0b852 1997 $changePrimary = FALSE;
92a77772 1998 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1999 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
2000
2001 foreach ($block as $blkCount => $values) {
2002 $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
2003 $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
2004 if (!$otherBlockId) {
2005 continue;
2006 }
2007
2008 // For the block which belongs to other-contact, link the location block to main-contact
2009 $otherBlockDAO = new $daoName();
2010 $otherBlockDAO->contact_id = $mainId;
2011
2012 // Get the ID of this block on the 'other' contact, otherwise skip
2013 $otherBlockDAO->id = $otherBlockId;
2014
2015 // Add/update location and type information from the form, if applicable
2016 if ($locationBlocks[$name]['hasLocation']) {
2017 $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2018 $otherBlockDAO->location_type_id = $locTypeId;
2019 }
2020 if ($locationBlocks[$name]['hasType']) {
2021 $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2022 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
2023 }
2024
abd0b852
J
2025 // If we're deliberately setting this as primary then add the flag
2026 // and remove it from the current primary location (if there is one).
2027 // But only once for each entity.
2028 $set_primary = CRM_Utils_Array::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
9e848fc4 2029 if (!$changePrimary && $set_primary == "1") {
abd0b852
J
2030 $otherBlockDAO->is_primary = 1;
2031 if ($primaryDAOId) {
2032 $removePrimaryDAO = new $daoName();
2033 $removePrimaryDAO->id = $primaryDAOId;
2034 $removePrimaryDAO->is_primary = 0;
2035 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
2036 }
2037 $changePrimary = TRUE;
2038 }
2039 // Otherwise, if main contact already has primary, set it to 0.
2040 elseif ($primaryDAOId) {
92a77772 2041 $otherBlockDAO->is_primary = 0;
2042 }
abd0b852
J
2043
2044 // If the main contact already has a billing location, set this to 0.
92a77772 2045 if ($billingDAOId) {
2046 $otherBlockDAO->is_billing = 0;
2047 }
2048
2049 $operation = CRM_Utils_Array::value('operation', $values, 2);
2050 // overwrite - need to delete block which belongs to main-contact.
2051 if (!empty($mainBlockId) && ($operation == 2)) {
2052 $deleteDAO = new $daoName();
2053 $deleteDAO->id = $mainBlockId;
2054 $deleteDAO->find(TRUE);
2055
2056 // if we about to delete a primary / billing block, set the flags for new block
2057 // that we going to assign to main-contact
2058 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
2059 $otherBlockDAO->is_primary = 1;
2060 }
2061 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
2062 $otherBlockDAO->is_billing = 1;
2063 }
2064 $blocksDAO[$name]['delete'][$deleteDAO->id] = $deleteDAO;
2065 }
2066 $blocksDAO[$name]['update'][$otherBlockDAO->id] = $otherBlockDAO;
2067 }
2068 }
2069 }
2070
2071 CRM_Utils_Hook::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2072 foreach ($blocksDAO as $blockDAOs) {
2073 if (!empty($blockDAOs['update'])) {
2074 foreach ($blockDAOs['update'] as $blockDAO) {
2075 $blockDAO->save();
2076 }
2077 }
2078 if (!empty($blockDAOs['delete'])) {
2079 foreach ($blockDAOs['delete'] as $blockDAO) {
2080 $blockDAO->delete();
2081 }
2082 }
2083 }
2084 }
2085
e4e1db4b 2086 /**
2087 * Dedupe a pair of contacts.
2088 *
2089 * @param array $migrationInfo
2090 * @param array $resultStats
2091 * @param array $deletedContacts
2092 * @param string $mode
2093 * @param bool $checkPermissions
2094 * @param int $mainId
2095 * @param int $otherId
2096 * @param string $cacheKeyString
2097 */
2098 protected static function dedupePair(&$migrationInfo, &$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) {
2099
2100 // go ahead with merge if there is no conflict
2c16165a 2101 $conflicts = [];
e4e1db4b 2102 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2103 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2c16165a 2104 $resultStats['merged'][] = [
e4e1db4b 2105 'main_id' => $mainId,
2106 'other_id' => $otherId,
2c16165a 2107 ];
e4e1db4b 2108 $deletedContacts[] = $otherId;
2109 }
2110 else {
2c16165a 2111 $resultStats['skipped'][] = [
e4e1db4b 2112 'main_id' => $mainId,
2113 'other_id' => $otherId,
2c16165a 2114 ];
e4e1db4b 2115 }
2116
2117 // store any conflicts
2118 if (!empty($conflicts)) {
2119 foreach ($conflicts as $key => $dnc) {
2120 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
2121 }
2122 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
2123 }
2124 else {
c131d228 2125 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString);
e4e1db4b 2126 }
e4e1db4b 2127 }
2128
54ed517e 2129 /**
2130 * Replace the pseudo QFKey with zero if it is present.
2131 *
2132 * @todo - on the slim chance this is still relevant it should be moved to the form layer.
2133 *
2134 * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
2135 * can still help.
2136 *
2137 * @param array $migrationInfo
2138 */
2139 protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
2140 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
2141 foreach ($migrationInfo as $key => &$value) {
2142 if ($value == $qfZeroBug) {
2143 $value = '0';
2144 }
2145 }
2146 }
2147
830ee2be 2148 /**
2149 * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
2150 *
2151 * @param $mainId
2152 * @param $key
2153 * @param $cFields
2154 * @param $customFiles
2155 * @param $submitted
2156 * @param $value
2157 *
2158 * @return array
2159 */
2160 protected static function processCustomFields($mainId, $key, $cFields, $customFiles, $submitted, $value) {
2161 if (substr($key, 0, 7) == 'custom_') {
2162 $fid = (int) substr($key, 7);
2163 if (empty($cFields[$fid])) {
2164 return [$cFields, $customFiles, $submitted];
2165 }
2166 $htmlType = $cFields[$fid]['attributes']['html_type'];
2167 switch ($htmlType) {
2168 case 'File':
2169 $customFiles[] = $fid;
2170 unset($submitted["custom_$fid"]);
2171 break;
2172
2173 case 'Select Country':
2174 case 'Select State/Province':
2175 $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
2176 break;
2177
2178 case 'Select Date':
2179 if ($cFields[$fid]['attributes']['is_view']) {
2180 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
2181 }
2182 break;
2183
2184 case 'CheckBox':
2185 case 'Multi-Select':
2186 case 'Multi-Select Country':
2187 case 'Multi-Select State/Province':
2188 // Merge values from both contacts for multivalue fields, CRM-4385
2189 // get the existing custom values from db.
2190 $customParams = ['entityID' => $mainId, $key => TRUE];
2191 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
2192 if (!empty($customfieldValues[$key])) {
2193 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
2194 if (is_array($existingValue) && !empty($existingValue)) {
2195 $mergeValue = $submittedCustomFields = [];
2196 if ($value == 'null') {
2197 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
2198 $submitted[$key] = $value;
2199 }
2200 else {
2201 if ($value) {
2202 $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2203 }
2204
2205 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
2206 // custom field value stored at $submittedCustomValue.
2207 foreach ($submittedCustomFields as $k => $v) {
2208 if ($v != '' && !in_array($v, $mergeValue)) {
2209 $mergeValue[] = $v;
2210 }
2211 }
2212
2213 //keep state and country as array format.
2214 //for checkbox and m-select format w/ VALUE_SEPARATOR
2215 if (in_array($htmlType, [
2216 'CheckBox',
2217 'Multi-Select',
2218 ])) {
2219 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
2220 $mergeValue
2221 ) . CRM_Core_DAO::VALUE_SEPARATOR;
2222 }
2223 else {
2224 $submitted[$key] = $mergeValue;
2225 }
2226 }
2227 }
2228 }
2229 elseif (in_array($htmlType, [
2230 'Multi-Select Country',
2231 'Multi-Select State/Province',
2232 ])) {
2233 //we require submitted values should be in array format
2234 if ($value) {
2235 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2236 //hack to remove null values from array.
2237 $mergeValue = [];
2238 foreach ($mergeValueArray as $k => $v) {
2239 if ($v != '') {
2240 $mergeValue[] = $v;
2241 }
2242 }
2243 $submitted[$key] = $mergeValue;
2244 }
2245 }
2246 break;
2247
2248 default:
2249 break;
2250 }
2251 }
2252 return [$cFields, $customFiles, $submitted];
2253 }
2254
f941d73a 2255 /**
2256 * Get metadata for the custom fields for the merge.
2257 *
2258 * @param string $contactType
2259 *
2260 * @return array
2261 */
2262 protected static function getCustomFieldMetadata($contactType) {
2263 $treeCache = [];
2264 if (!array_key_exists($contactType, $treeCache)) {
2265 $treeCache[$contactType] = CRM_Core_BAO_CustomGroup::getTree(
2266 $contactType,
2267 NULL,
2268 NULL,
2269 -1,
2270 [],
2271 NULL,
2272 TRUE,
2273 NULL,
2274 FALSE,
2275 FALSE
2276 );
2277 }
2278
2279 $cFields = [];
2280 foreach ($treeCache[$contactType] as $key => $group) {
2281 if (!isset($group['fields'])) {
2282 continue;
2283 }
2284 foreach ($group['fields'] as $fid => $field) {
2285 $cFields[$fid]['attributes'] = $field;
2286 }
2287 }
2288 return $cFields;
2289 }
2290
a2abc387 2291 /**
2292 * Get conflicts for proposed merge pair.
2293 *
2294 * @param array $migrationInfo
2295 * This is primarily to inform hooks. The can also modify it which feels
2296 * pretty fragile to do it here - but it is historical.
2297 * @param int $mainId
2298 * Main contact with whom merge has to happen.
2299 * @param int $otherId
2300 * Duplicate contact which would be deleted after merge operation.
2301 * @param string $mode
2302 * Helps decide how to behave when there are conflicts.
2303 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
2304 * - Does a force merge otherwise (aggressive mode).
2305 *
2306 * @return array
2307 */
2308 public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) {
2309 $conflicts = [];
2310 $originalMigrationInfo = $migrationInfo;
2311 foreach ($migrationInfo as $key => $val) {
2312 if ($val === "null") {
2313 // Rule: Never overwrite with an empty value (in any mode)
2314 unset($migrationInfo[$key]);
2315 continue;
2316 }
2317 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
2318 substr($key, 0, 12) == 'move_custom_'
2319 ) and $val != NULL
2320 ) {
2321 // Rule: If both main-contact, and other-contact have a field with a
2322 // different value, then let $mode decide if to merge it or not
2323 if (
2324 (!empty($migrationInfo['rows'][$key]['main'])
2325 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
2326 // is probably true for other fields too - e.g. 'do_not_email' but
2327 // leaving that investigation as a @todo - until tests can be written.
2328 // Note the handling of this has test coverage - although the data-typing
2329 // of '0' feels flakey we have insurance.
2330 || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
2331 )
2332 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
2333 ) {
2334
2335 // note it down & lets wait for response from the hook.
2336 // For no response $mode will decide if to skip this merge
2337 $conflicts[$key] = NULL;
2338 }
2339 }
2340 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
2341 $locField = explode('_', $key);
2342 $fieldName = $locField[2];
2343 $fieldCount = $locField[3];
2344
2345 // Rule: Catch address conflicts (same address type on both contacts)
2346 if (
2347 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
2348 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
2349 ) {
2350
2351 // Load the address we're inspecting from the 'other' contact
2352 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
2353 $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord);
2354
2355 // If it exists on the 'main' contact already, skip it. Otherwise
2356 // if the location type exists already, log a conflict.
2357 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
2358 if (self::locationIsSame($addressRecord, $mainAddressRecord)) {
2359 unset($migrationInfo[$key]);
2360 break;
2361 }
2362 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
2363 $conflicts[$key] = NULL;
2364 break;
2365 }
2366 }
2367 }
2368
2369 // For other locations, don't merge/add if the values are the same
2370 elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
2371 unset($migrationInfo[$key]);
2372 }
2373 }
2374 }
2375
2376 // A hook to implement other algorithms for choosing which contact to bias to when
2377 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
2378 // merge happens with new values filled in here. For a particular field / row not to be merged
2379 // field should be unset from fields_in_conflict.
2380 $migrationData = [
2381 'old_migration_info' => $originalMigrationInfo,
2382 'mode' => $mode,
2383 'fields_in_conflict' => $conflicts,
2384 'merge_mode' => $mode,
2385 'migration_info' => $migrationInfo,
2386 ];
2387 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
2388 $conflicts = $migrationData['fields_in_conflict'];
2389 // allow hook to override / manipulate migrationInfo as well
2390 $migrationInfo = $migrationData['migration_info'];
2391 $migrationInfo['skip_merge'] = CRM_Utils_Array::value('skip_merge', $migrationData);
2392 return $conflicts;
2393 }
2394
49580579 2395 /**
2396 * Do file custom fields related migrations.
2397 * FIXME: move this someplace else (one of the BAOs) after discussing
2398 * where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
2399 * like, delete a file...
2400 *
2401 * Note outstanding bug https://lab.civicrm.org/dev/core/issues/723
2402 * relates to this code....
2403 *
2404 * @param $mainId
2405 * @param $otherId
2406 * @param $customFiles
2407 */
2408 protected static function processCustomFieldFiles($mainId, $otherId, $customFiles) {
2409 foreach ($customFiles as $customId) {
2410 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
2411
2412 // get the contact_id -> file_id mapping
2413 $fileIds = [];
2414 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
2415 $dao = CRM_Core_DAO::executeQuery($sql);
2416 while ($dao->fetch()) {
119664d6 2417 // @todo - this is actually broken - fix & or remove - see testMergeCustomFields
49580579 2418 $fileIds[$dao->entity_id] = $dao->file_id;
2419 if ($dao->entity_id == $mainId) {
2420 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
2421 }
2422 }
2423
2424 // move the other contact's file to main contact
2425 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
2426 if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
2427 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
2428 }
2429 else {
2430 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
2431 }
2432 CRM_Core_DAO::executeQuery($sql);
2433
2434 if (CRM_Core_DAO::singleValueQuery("
2435 SELECT id
2436 FROM civicrm_entity_file
2437 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
2438 ) {
2439 $sql = "
2440 UPDATE civicrm_entity_file
2441 SET entity_id = {$mainId}
2442 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
2443 }
2444 else {
2445 $sql = "
2446 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
2447 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
2448 }
2449 CRM_Core_DAO::executeQuery($sql);
2450 }
2451 }
2452
4107e11e 2453 /**
2454 * @param $rule_group_id
2455 * @param $group_id
2456 * @param $batchLimit
2457 * @param $isSelected
2458 * @param $includeConflicts
2459 * @param $criteria
2460 * @param $checkPermissions
2461 *
2462 * @return array
2463 */
2464 protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions) {
2465 return CRM_Core_BAO_PrevNextCache::retrieve(
2466 self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions),
2467 self::getJoinOnDedupeTable(),
2468 self::getWhereString($isSelected),
2469 0, $batchLimit,
2470 [], '',
2471 $includeConflicts
2472 );
2473 }
2474
6a488035 2475}