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