3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Dedupe_Merger
{
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
41 public static function relTables() {
43 if (!isset(Civi
::$statics[__CLASS__
]['relTables'])) {
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 = '';
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', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
56 elseif ($config->userFramework
== 'Joomla') {
57 $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';
58 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
62 'rel_table_contributions' => array(
63 'title' => ts('Contributions'),
64 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
65 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
67 'rel_table_contribution_page' => array(
68 'title' => ts('Contribution Pages'),
69 'tables' => array('civicrm_contribution_page'),
70 'url' => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
72 'rel_table_memberships' => array(
73 'title' => ts('Memberships'),
74 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
75 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
77 'rel_table_participants' => array(
78 'title' => ts('Participants'),
79 'tables' => array('civicrm_participant'),
80 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
82 'rel_table_events' => array(
83 'title' => ts('Events'),
84 'tables' => array('civicrm_event'),
85 'url' => CRM_Utils_System
::url('civicrm/event/manage', 'reset=1&cid=$cid'),
87 'rel_table_activities' => array(
88 'title' => ts('Activities'),
89 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
90 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
92 'rel_table_relationships' => array(
93 'title' => ts('Relationships'),
94 'tables' => array('civicrm_relationship'),
95 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
97 'rel_table_custom_groups' => array(
98 'title' => ts('Custom Groups'),
99 'tables' => array('civicrm_custom_group'),
100 'url' => CRM_Utils_System
::url('civicrm/admin/custom/group', 'reset=1'),
102 'rel_table_uf_groups' => array(
103 'title' => ts('Profiles'),
104 'tables' => array('civicrm_uf_group'),
105 'url' => CRM_Utils_System
::url('civicrm/admin/uf/group', 'reset=1'),
107 'rel_table_groups' => array(
108 'title' => ts('Groups'),
109 'tables' => array('civicrm_group_contact'),
110 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
112 'rel_table_notes' => array(
113 'title' => ts('Notes'),
114 'tables' => array('civicrm_note'),
115 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
117 'rel_table_tags' => array(
118 'title' => ts('Tags'),
119 'tables' => array('civicrm_entity_tag'),
120 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
122 'rel_table_mailings' => array(
123 'title' => ts('Mailings'),
124 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
125 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
127 'rel_table_cases' => array(
128 'title' => ts('Cases'),
129 'tables' => array('civicrm_case_contact'),
130 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
132 'rel_table_grants' => array(
133 'title' => ts('Grants'),
134 'tables' => array('civicrm_grant'),
135 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
137 'rel_table_pcp' => array(
138 'title' => ts('PCPs'),
139 'tables' => array('civicrm_pcp'),
140 'url' => CRM_Utils_System
::url('civicrm/contribute/pcp/manage', 'reset=1'),
142 'rel_table_pledges' => array(
143 'title' => ts('Pledges'),
144 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
145 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
147 'rel_table_users' => array(
149 'tables' => array('civicrm_uf_match'),
150 'url' => $userRecordUrl,
154 $relTables +
= self
::getMultiValueCustomSets('relTables');
156 // Allow hook_civicrm_merge() to adjust $relTables
157 CRM_Utils_Hook
::merge('relTables', $relTables);
159 // Cache the results in a static variable
160 Civi
::$statics[__CLASS__
]['relTables'] = $relTables;
163 return Civi
::$statics[__CLASS__
]['relTables'];
167 * Returns the related tables groups for which a contact has any info entered.
173 public static function getActiveRelTables($cid) {
177 $relTables = self
::relTables();
178 $cidRefs = self
::cidRefs();
179 $eidRefs = self
::eidRefs();
180 foreach ($relTables as $group => $params) {
182 foreach ($params['tables'] as $table) {
183 if (isset($cidRefs[$table])) {
184 foreach ($cidRefs[$table] as $field) {
185 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
188 if (isset($eidRefs[$table])) {
189 foreach ($eidRefs[$table] as $entityTable => $entityId) {
190 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
193 foreach ($sqls as $sql) {
194 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
200 return array_unique($groups);
204 * Get array tables and fields that reference civicrm_contact.id.
206 * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call.
207 * The entityTypes hook is the recommended way to add tables to this result.
209 * I thought about adding another hook to alter tableReferences but decided it was unclear if there
210 * are use cases not covered by entityTables and instead we should wait & see.
212 public static function cidRefs() {
213 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
214 return \Civi
::$statics[__CLASS__
]['contact_references'];
217 $contactReferences = $coreReferences = CRM_Core_DAO
::getReferencesToContactTable();
219 CRM_Utils_Hook
::merge('cidRefs', $contactReferences);
220 if ($contactReferences !== $coreReferences) {
221 Civi
::log()->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", array('civi.tag' => 'deprecated'));
223 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
224 return \Civi
::$statics[__CLASS__
]['contact_references'];
228 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
230 public static function eidRefs() {
233 // FIXME: this should be generated dynamically from the schema
234 // tables that reference contacts with entity_{id,table}
236 'civicrm_acl' => array('entity_table' => 'entity_id'),
237 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
238 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
239 'civicrm_log' => array('entity_table' => 'entity_id'),
240 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
241 'civicrm_note' => array('entity_table' => 'entity_id'),
244 // Allow hook_civicrm_merge() to adjust $eidRefs
245 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
251 * Return tables using locations.
253 public static function locTables() {
256 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
258 // Allow hook_civicrm_merge() to adjust $locTables
259 CRM_Utils_Hook
::merge('locTables', $locTables);
265 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
266 * @param string $request
267 * 'relTables' or 'cidRefs'.
271 public static function getMultiValueCustomSets($request) {
273 if (!isset(Civi
::$statics[__CLASS__
]['multiValueCustomSets'])) {
275 'relTables' => array(),
276 'cidRefs' => array(),
278 $result = civicrm_api3('custom_group', 'get', array(
280 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
281 'return' => array('id', 'title', 'table_name', 'style'),
283 foreach ($result['values'] as $custom) {
284 $data['cidRefs'][$custom['table_name']] = array('entity_id');
285 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
286 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
287 'title' => $custom['title'],
288 'tables' => array($custom['table_name']),
289 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
293 // Store the result in a static variable cache
294 Civi
::$statics[__CLASS__
]['multiValueCustomSets'] = $data;
297 return Civi
::$statics[__CLASS__
]['multiValueCustomSets'][$request];
301 * Tables which require custom processing should declare functions to call here.
302 * Doing so will override normal processing.
304 public static function cpTables() {
308 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
309 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
310 // Empty array == do nothing - this table is handled by mergeGroupContact
311 'civicrm_subscription_history' => array(),
312 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
313 'civicrm_membership' => array('CRM_Member_BAO_Membership' => 'mergeMemberships'),
320 * Return payment related table.
322 public static function paymentTables() {
325 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
331 * Return payment update Query.
333 * @param string $tableName
334 * @param int $mainContactId
335 * @param int $otherContactId
339 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
341 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
345 $paymentTables = self
::paymentTables();
346 if (!in_array($tableName, $paymentTables)) {
350 switch ($tableName) {
351 case 'civicrm_pledge':
353 UPDATE IGNORE civicrm_contribution contribution
354 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
355 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
356 SET contribution.contact_id = $mainContactId
357 WHERE pledge.contact_id = $otherContactId";
360 case 'civicrm_membership':
362 UPDATE IGNORE civicrm_contribution contribution
363 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
364 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
365 SET contribution.contact_id = $mainContactId
366 WHERE membership.contact_id = $otherContactId";
369 case 'civicrm_participant':
371 UPDATE IGNORE civicrm_contribution contribution
372 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
373 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
374 SET contribution.contact_id = $mainContactId
375 WHERE participant.contact_id = $otherContactId";
384 * @param int $otherId
385 * @param string $tableName
386 * @param array $tableOperations
387 * @param string $mode
391 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
393 if (!$tableName ||
!$mainId ||
!$otherId) {
397 switch ($tableName) {
398 case 'civicrm_membership':
399 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
402 if ($mode == 'add') {
404 DELETE membership1.* FROM civicrm_membership membership1
405 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
406 AND membership1.contact_id = {$mainId}
407 AND membership2.contact_id = {$otherId} ";
409 if ($mode == 'payment') {
411 DELETE contribution.* FROM civicrm_contribution contribution
412 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
413 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
414 AND membership1.contact_id = {$mainId}
415 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
416 AND membership2.contact_id = {$otherId}";
420 case 'civicrm_uf_match':
421 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
422 // failing to meet intended result. Therefore we introduce this additional query:
423 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
431 * Based on the provided two contact_ids and a set of tables, remove the
432 * belongings of the other contact and of their relations.
434 * @param int $otherID
435 * @param bool $tables
437 public static function removeContactBelongings($otherID, $tables) {
438 // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
439 if (in_array("civicrm_membership", $tables)) {
440 $membershipIDs = CRM_Utils_Array
::collect('id',
441 CRM_Utils_Array
::value('values',
442 civicrm_api3("Membership", "get", array(
443 "contact_id" => $otherID,
449 if (!empty($membershipIDs)) {
450 civicrm_api3("Membership", "get", array(
451 'owner_membership_id' => array('IN' => $membershipIDs),
452 'api.Membership.delete' => array('id' => '$value.id'),
459 * Based on the provided two contact_ids and a set of tables, move the
460 * belongings of the other contact to the main one.
463 * @param int $otherId
464 * @param bool $tables
465 * @param array $tableOperations
466 * @param array $customTableToCopyFrom
468 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array(), $customTableToCopyFrom = NULL) {
469 $cidRefs = self
::cidRefs();
470 $eidRefs = self
::eidRefs();
471 $cpTables = self
::cpTables();
472 $paymentTables = self
::paymentTables();
474 // getting all custom tables
475 $customTables = array();
476 if ($customTableToCopyFrom !== NULL) {
477 // @todo this duplicates cidRefs?
478 CRM_Core_DAO
::appendCustomTablesExtendingContacts($customTables);
479 $customTables = array_keys($customTables);
482 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
484 // if there aren't any specific tables, don't affect the ones handled by relTables()
485 // also don't affect tables in locTables() CRM-15658
486 $relTables = self
::relTables();
487 $handled = self
::locTables();
489 foreach ($relTables as $params) {
490 $handled = array_merge($handled, $params['tables']);
492 $affected = array_diff($affected, $handled);
493 $affected = array_unique(array_merge($affected, $tables));
495 $mainId = (int) $mainId;
496 $otherId = (int) $otherId;
497 $multi_value_tables = array_keys(CRM_Dedupe_Merger
::getMultiValueCustomSets('cidRefs'));
500 foreach ($affected as $table) {
501 // skipping non selected single-value custom table's value migration
502 if (!in_array($table, $multi_value_tables)) {
503 if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
508 // Call custom processing function for objects that require it
509 if (isset($cpTables[$table])) {
510 foreach ($cpTables[$table] as $className => $fnName) {
511 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
513 // Skip normal processing
517 // use UPDATE IGNORE + DELETE query pair to skip on situations when
518 // there's a UNIQUE restriction on ($field, some_other_field) pair
519 if (isset($cidRefs[$table])) {
520 foreach ($cidRefs[$table] as $field) {
521 // carry related contributions CRM-5359
522 if (in_array($table, $paymentTables)) {
523 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
524 $sqls = array_merge($sqls, $paymentSqls);
526 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
527 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
528 $sqls = array_merge($sqls, $payOprSqls);
532 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
533 $sqls = array_merge($sqls, $preOperationSqls);
535 if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self
::customRecordExists($mainId, $table, $field)) {
536 $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
538 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
539 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
543 if (isset($eidRefs[$table])) {
544 foreach ($eidRefs[$table] as $entityTable => $entityId) {
545 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
546 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
551 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
552 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
554 // call the SQL queries in one transaction
555 $transaction = new CRM_Core_Transaction();
556 foreach ($sqls as $sql) {
557 CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, TRUE);
559 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
560 $transaction->commit();
564 * Given a contact ID, will check if a record exists in given table.
569 * Field where the contact's ID is stored in the table
572 * True if a record is found for the given contact ID, false otherwise
574 private static function customRecordExists($contactID, $table, $idField) {
576 SELECT COUNT(*) AS count
578 WHERE $idField = $contactID
580 $dbResult = CRM_Core_DAO
::executeQuery($sql);
583 if ($dbResult->count
> 0) {
591 * Load all non-empty fields for the contacts
595 * @param array $other
600 public static function retrieveFields($main, $other) {
602 'contact' => array(),
605 foreach (self
::getContactFields() as $validField) {
606 // CRM-17556 Get all non-empty fields, to make comparison easier
607 if (!empty($main[$validField]) ||
!empty($other[$validField])) {
608 $result['contact'][] = $validField;
612 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
613 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
614 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
615 foreach ($keys as $key) {
616 // Exclude multi-value fields CRM-13836
617 if (strpos($key, '_')) {
620 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
621 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
622 // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
623 // However I can't think of a case where an empty string is more meaningful than null
624 // or where it would be FALSE or something else nullish.
625 $valuesToIgnore = [NULL, '', []];
626 if (!in_array($key1, $valuesToIgnore, TRUE) ||
!in_array($key2, $valuesToIgnore, TRUE)) {
627 $result['custom'][] = $key;
634 * Batch merge a set of contacts based on rule-group and group.
640 * @param string $mode
641 * Helps decide how to behave when there are conflicts.
642 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
643 * mode does a force merge.
644 * @param int $batchLimit number of merges to carry out in one batch.
645 * @param int $isSelected if records with is_selected column needs to be processed.
646 * Note the option of '2' is only used in conjunction with $redirectForPerformance
647 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
648 * out in favour of explicitly passing in $reloadCacheIfEmpty
650 * @param array $criteria
651 * Criteria to use in the filter.
653 * @param bool $checkPermissions
654 * Respect logged in user permissions.
655 * @param bool|NULL $reloadCacheIfEmpty
656 * If not set explicitly this is calculated but it is preferred that it be set
657 * per comments on isSelected above.
661 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = array(), $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL) {
662 $redirectForPerformance = ($batchLimit > 1) ?
TRUE : FALSE;
664 if (!isset($reloadCacheIfEmpty)) {
665 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
667 if ($isSelected !== 0 && $isSelected !== 1) {
668 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
671 $dupePairs = self
::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, '', ($mode == 'aggressive'), $criteria, $checkPermissions);
673 $cacheParams = array(
674 'cache_key_string' => self
::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
675 // @todo stop passing these parameters in & instead calculate them in the merge function based
676 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
677 'join' => self
::getJoinOnDedupeTable(),
678 'where' => self
::getWhereString($isSelected),
679 'limit' => (int) $batchLimit,
681 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
685 * Get the string to join the prevnext cache to the dedupe table.
688 * The join string to join prevnext cache on the dedupe table.
690 public static function getJoinOnDedupeTable() {
692 LEFT JOIN civicrm_dedupe_exception de
694 pn.entity_id1 = de.contact_id1
695 AND pn.entity_id2 = de.contact_id2 )
700 * Get where string for dedupe join.
702 * @param bool $isSelected
706 protected static function getWhereString($isSelected) {
707 $where = "de.id IS NULL";
708 if ($isSelected === 0 ||
$isSelected === 1) {
709 $where .= " AND pn.is_selected = {$isSelected}";
715 * Update the statistics for the merge set.
717 * @param string $cacheKeyString
718 * @param array $result
720 public static function updateMergeStats($cacheKeyString, $result = array()) {
721 // gather latest stats
722 $merged = count($result['merged']);
723 $skipped = count($result['skipped']);
725 if ($merged <= 0 && $skipped <= 0) {
729 // get previous stats
730 $previousStats = CRM_Core_BAO_PrevNextCache
::retrieve("{$cacheKeyString}_stats");
731 if (!empty($previousStats)) {
732 if ($previousStats[0]['merged']) {
733 $merged = $merged +
$previousStats[0]['merged'];
735 if ($previousStats[0]['skipped']) {
736 $skipped = $skipped +
$previousStats[0]['skipped'];
741 CRM_Dedupe_Merger
::resetMergeStats($cacheKeyString);
743 // store the updated stats
746 'skipped' => $skipped,
748 $data = CRM_Core_DAO
::escapeString(serialize($data));
751 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
752 CRM_Core_BAO_PrevNextCache
::setItem($values);
756 * Delete information about merges for the given string.
758 * @param $cacheKeyString
760 public static function resetMergeStats($cacheKeyString) {
761 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, "{$cacheKeyString}_stats");
765 * Get merge outcome statistics.
767 * @param string $cacheKeyString
770 * Array of how many were merged and how many were skipped.
772 public static function getMergeStats($cacheKeyString) {
773 $stats = CRM_Core_BAO_PrevNextCache
::retrieve("{$cacheKeyString}_stats");
774 if (!empty($stats)) {
781 * Get merge statistics message.
783 * @param array $stats
787 public static function getMergeStatsMsg($stats) {
789 if (!empty($stats['merged'])) {
790 $msg = '<p>' . ts('One contact merged.', array('count' => $stats['merged'], 'plural' => '%count contacts merged.')) . '</p>';
792 if (!empty($stats['skipped'])) {
793 $msg .= '<p>' . ts('One contact was skipped.', array('count' => $stats['skipped'], 'plural' => '%count contacts were skipped.')) . '</p>';
799 * Merge given set of contacts. Performs core operation.
801 * @param array $dupePairs
802 * Set of pair of contacts for whom merge is to be done.
803 * @param array $cacheParams
804 * Prev-next-cache params based on which next pair of contacts are computed.
805 * Generally used with batch-merge.
806 * @param string $mode
807 * Helps decide how to behave when there are conflicts.
808 * A 'safe' value skips the merge if there are any un-resolved conflicts.
809 * Does a force merge otherwise (aggressive mode).
811 * @param bool $redirectForPerformance
812 * Redirect to a url for batch processing.
814 * @param bool $checkPermissions
815 * Respect logged in user permissions.
819 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
820 $redirectForPerformance = FALSE, $checkPermissions = TRUE
822 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
823 $resultStats = array('merged' => array(), 'skipped' => array());
825 // we don't want dupe caching to get reset after every-merge, and therefore set the
826 CRM_Core_Config
::setPermitCacheFlushMode(FALSE);
827 $deletedContacts = array();
829 while (!empty($dupePairs)) {
830 foreach ($dupePairs as $index => $dupes) {
831 if (in_array($dupes['dstID'], $deletedContacts) ||
in_array($dupes['srcID'], $deletedContacts)) {
832 unset($dupePairs[$index]);
835 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
836 $mainId = $dupes['dstID'];
837 $otherId = $dupes['srcID'];
839 if (!$mainId ||
!$otherId) {
843 // Generate var $migrationInfo. The variable structure is exactly same as
844 // $formValues submitted during a UI merge for a pair of contacts.
845 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions);
846 // add additional details that we might need to resolve conflicts
847 $rowsElementsAndInfo['migration_info']['main_details'] = &$rowsElementsAndInfo['main_details'];
848 $rowsElementsAndInfo['migration_info']['other_details'] = &$rowsElementsAndInfo['other_details'];
849 $rowsElementsAndInfo['migration_info']['rows'] = &$rowsElementsAndInfo['rows'];
851 self
::dedupePair($rowsElementsAndInfo['migration_info'], $resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString);
854 if ($cacheKeyString && !$redirectForPerformance) {
855 // retrieve next pair of dupes
856 // @todo call getDuplicatePairs.
857 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
858 $cacheParams['join'],
859 $cacheParams['where'],
861 $cacheParams['limit'],
868 // do not proceed. Terminate the loop
873 CRM_Dedupe_Merger
::updateMergeStats($cacheKeyString, $resultStats);
878 * A function which uses various rules / algorithms for choosing which contact to bias to
879 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
882 * Main contact with whom merge has to happen.
883 * @param int $otherId
884 * Duplicate contact which would be deleted after merge operation.
885 * @param array $migrationInfo
886 * Array of information about which elements to merge.
887 * @param string $mode
888 * Helps decide how to behave when there are conflicts.
889 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
890 * - Does a force merge otherwise (aggressive mode).
892 * @param array $conflicts
896 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
898 $originalMigrationInfo = $migrationInfo;
899 foreach ($migrationInfo as $key => $val) {
900 if ($val === "null") {
901 // Rule: Never overwrite with an empty value (in any mode)
902 unset($migrationInfo[$key]);
905 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
906 substr($key, 0, 12) == 'move_custom_'
909 // Rule: If both main-contact, and other-contact have a field with a
910 // different value, then let $mode decide if to merge it or not
912 (!empty($migrationInfo['rows'][$key]['main'])
913 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
914 // is probably true for other fields too - e.g. 'do_not_email' but
915 // leaving that investigation as a @todo - until tests can be written.
916 // Note the handling of this has test coverage - although the data-typing
917 // of '0' feels flakey we have insurance.
918 ||
($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
920 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
923 // note it down & lets wait for response from the hook.
924 // For no response $mode will decide if to skip this merge
925 $conflicts[$key] = NULL;
928 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
929 $locField = explode('_', $key);
930 $fieldName = $locField[2];
931 $fieldCount = $locField[3];
933 // Rule: Catch address conflicts (same address type on both contacts)
935 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
936 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
939 // Load the address we're inspecting from the 'other' contact
940 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
941 $addressRecordLocTypeId = CRM_Utils_Array
::value('location_type_id', $addressRecord);
943 // If it exists on the 'main' contact already, skip it. Otherwise
944 // if the location type exists already, log a conflict.
945 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
946 if (self
::locationIsSame($addressRecord, $mainAddressRecord)) {
947 unset($migrationInfo[$key]);
950 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
951 $conflicts[$key] = NULL;
957 // For other locations, don't merge/add if the values are the same
958 elseif (CRM_Utils_Array
::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
959 unset($migrationInfo[$key]);
964 // A hook to implement other algorithms for choosing which contact to bias to when
965 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
966 // merge happens with new values filled in here. For a particular field / row not to be merged
967 // field should be unset from fields_in_conflict.
968 $migrationData = array(
969 'old_migration_info' => $originalMigrationInfo,
971 'fields_in_conflict' => $conflicts,
972 'merge_mode' => $mode,
973 'migration_info' => $migrationInfo,
975 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
976 $conflicts = $migrationData['fields_in_conflict'];
977 // allow hook to override / manipulate migrationInfo as well
978 $migrationInfo = $migrationData['migration_info'];
980 if (!empty($conflicts)) {
981 foreach ($conflicts as $key => $val) {
982 if ($val === NULL and $mode == 'safe') {
983 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
987 // copy over the resolved values
988 $migrationInfo[$key] = $val;
991 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
992 if (array_key_exists('skip_merge', $migrationData)) {
993 return (bool) $migrationData['skip_merge'];
1000 * Compare 2 addresses to see if they are the same.
1002 * @param array $mainAddress
1003 * @param array $comparisonAddress
1007 static public function locationIsSame($mainAddress, $comparisonAddress) {
1008 $keysToIgnore = array('id', 'is_primary', 'is_billing', 'manual_geo_code', 'contact_id', 'reset_date', 'hold_date');
1009 foreach ($comparisonAddress as $field => $value) {
1010 if (in_array($field, $keysToIgnore)) {
1013 if ((!empty($value) ||
$value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
1021 * A function to build an array of information about location blocks that is
1022 * required when merging location fields
1026 public static function getLocationBlockInfo() {
1027 $locationBlocks = array(
1029 'label' => 'Address',
1030 'displayField' => 'display',
1031 'sortString' => 'location_type_id',
1032 'hasLocation' => TRUE,
1037 'displayField' => 'display',
1038 'sortString' => 'location_type_id',
1039 'hasLocation' => TRUE,
1044 'displayField' => 'name',
1045 'sortString' => 'location_type_id,provider_id',
1046 'hasLocation' => TRUE,
1047 'hasType' => 'provider_id',
1051 'displayField' => 'phone',
1052 'sortString' => 'location_type_id,phone_type_id',
1053 'hasLocation' => TRUE,
1054 'hasType' => 'phone_type_id',
1057 'label' => 'Website',
1058 'displayField' => 'url',
1059 'sortString' => 'website_type_id',
1060 'hasLocation' => FALSE,
1061 'hasType' => 'website_type_id',
1064 return $locationBlocks;
1068 * A function to build an array of information required by merge function and the merge UI.
1070 * @param int $mainId
1071 * Main contact with whom merge has to happen.
1072 * @param int $otherId
1073 * Duplicate contact which would be deleted after merge operation.
1074 * @param bool $checkPermissions
1075 * Should the logged in user's permissions be ignore. Setting this to false is
1076 * highly risky as it could cause data to be lost due to conflicts not showing up.
1077 * OTOH there is a risk a merger might view custom data they do not have permission to.
1078 * Hence for now only making this really explicit and making it reflect perms in
1081 * @todo review permissions issue!
1083 * @return array|bool|int
1085 * rows => An array of arrays, each is row of merge information for the table
1086 * Format: move_fieldname, eg: move_contact_type
1087 * main => Value associated with the main contact
1088 * other => Value associated with the other contact
1089 * title => The title of the field to display in the merge table
1091 * elements => An array of form elements for the merge UI
1093 * rel_table_elements => An array of form elements for the merge UI for
1094 * entities related to the contact (eg: checkbox to move 'mailings')
1096 * rel_tables => Stores the tables that have related entities for the contact
1097 * for example mailings, groups
1099 * main_details => An array of core contact field values, eg: first_name, etc.
1100 * location_blocks => An array of location block data for the main contact
1101 * stored as the 'result' of an API call.
1102 * eg: main_details['location_blocks']['address'][0]['id']
1103 * eg: main_details['location_blocks']['email'][1]['id']
1105 * other_details => As above, but for the 'other' contact
1107 * migration_info => Stores the 'default' merge actions for each field which
1108 * is used when programatically merging contacts. It contains instructions
1109 * to move all fields from the 'other' contact to the 'main' contact, as
1110 * though the form had been submitted with those options.
1112 * @throws \CRM_Core_Exception
1113 * @throws \CiviCRM_API3_Exception
1114 * @throws \Exception
1116 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1117 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1118 $fields = self
::getMergeFieldsMetadata();
1120 $main = self
::getMergeContactDetails($mainId);
1121 $other = self
::getMergeContactDetails($otherId);
1122 $specialValues['main'] = self
::getSpecialValues($main);
1123 $specialValues['other'] = self
::getSpecialValues($other);
1125 $compareFields = self
::retrieveFields($main, $other);
1127 $rows = $elements = $relTableElements = $migrationInfo = array();
1129 foreach ($compareFields['contact'] as $field) {
1130 if ($field == 'contact_sub_type') {
1131 // CRM-15681 don't display sub-types in UI
1134 foreach (array('main', 'other') as $moniker) {
1135 $contact = &$
$moniker;
1136 $value = CRM_Utils_Array
::value($field, $contact);
1137 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
1138 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1140 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
1141 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
1143 $value = str_replace('-', '', $value);
1144 $label = CRM_Utils_Date
::customFormat($label);
1150 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
1151 if ($label === '0') {
1154 if ($label === '1') {
1158 elseif ($field == 'prefix_id') {
1159 $label = CRM_Utils_Array
::value('individual_prefix', $contact);
1161 elseif ($field == 'suffix_id') {
1162 $label = CRM_Utils_Array
::value('individual_suffix', $contact);
1164 elseif ($field == 'gender_id' && !empty($value)) {
1165 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
1166 $label = $genderOptions['values'][$value];
1168 elseif ($field == 'current_employer_id' && !empty($value)) {
1169 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
1171 $rows["move_$field"][$moniker] = $label;
1172 if ($moniker == 'other') {
1174 if ($value === NULL ||
$value == '') {
1177 if ($value === 0 or $value === '0') {
1178 $value = $qfZeroBug;
1180 if (is_array($value) && empty($value[1])) {
1184 // Display a checkbox to migrate, only if the values are different
1185 if ($value != $main[$field]) {
1186 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1189 $migrationInfo["move_$field"] = $value;
1192 $rows["move_$field"]['title'] = $fields[$field]['title'];
1195 // Handle location blocks.
1196 // @todo OpenID not in API yet, so is not supported here.
1198 // Set up useful information about the location blocks
1199 $locationBlocks = self
::getLocationBlockInfo();
1206 // @todo This could probably be defined and used earlier
1207 $mergeTargets = array(
1209 'other' => $otherId,
1212 foreach ($locationBlocks as $blockName => $blockInfo) {
1214 // Collect existing fields from both 'main' and 'other' contacts first
1215 // This allows us to match up location/types when building the table rows
1216 foreach ($mergeTargets as $moniker => $cid) {
1217 $searchParams = array(
1218 'contact_id' => $cid,
1219 // CRM-17556 Order by field-specific criteria
1221 'sort' => $blockInfo['sortString'],
1224 $values = civicrm_api3($blockName, 'get', $searchParams);
1225 if ($values['count']) {
1227 foreach ($values['values'] as $value) {
1228 $locations[$moniker][$blockName][$cnt] = $value;
1229 // Fix address display
1230 if ($blockName == 'address') {
1231 CRM_Core_BAO_Address
::fixAddress($value);
1232 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address
::format($value);
1234 // Fix email display
1235 elseif ($blockName == 'email') {
1236 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Mail
::format($value);
1244 // Now, build the table rows appropriately, based off the information on
1245 // the 'other' contact
1246 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1247 foreach ($locations['other'][$blockName] as $count => $value) {
1249 $displayValue = $value[$blockInfo['displayField']];
1251 // Add this value to the table rows
1252 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1254 // CRM-17556 Only display 'main' contact value if it's the same location + type
1255 // Look it up from main values...
1257 $lookupLocation = FALSE;
1258 if ($blockInfo['hasLocation']) {
1259 $lookupLocation = $value['location_type_id'];
1262 $lookupType = FALSE;
1263 if ($blockInfo['hasType']) {
1264 $lookupType = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
1267 // Hold ID of main contact's matching block
1268 $mainContactBlockId = 0;
1270 if (!empty($locations['main'][$blockName])) {
1271 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1272 // No location/type, or matching location and type
1274 (empty($lookupLocation) ||
$lookupLocation == $mainValueCheck['location_type_id'])
1275 && (empty($lookupType) ||
$lookupType == $mainValueCheck[$blockInfo['hasType']])
1277 // Set this value as the default against the 'other' contact value
1278 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1279 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
1280 $mainContactBlockId = $mainValueCheck['id'];
1286 // Add checkbox to migrate data from 'other' to 'main'
1287 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
1289 // Add checkbox to set the 'other' location as primary
1290 $elements[] = array('advcheckbox', "location_blocks[$blockName][$count][set_other_primary]", NULL, ts('Set as primary'));
1292 // Flag up this field to skipMerge function (@todo: do we need to?)
1293 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1295 // Add a hidden field to store the ID of the target main contact block
1296 $elements[] = array('hidden', "location_blocks[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
1299 $thisTypeId = FALSE;
1302 // Provide a select drop-down for the location's location type
1303 // eg: Home, Work...
1305 if ($blockInfo['hasLocation']) {
1307 // Load the location options for this entity
1308 $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
1310 $thisLocId = $value['location_type_id'];
1312 // Put this field's location type at the top of the list
1313 $tmpIdList = $locationOptions['values'];
1314 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1315 unset($tmpIdList[$thisLocId]);
1318 $elements[] = array(
1320 "location_blocks[$blockName][$count][locTypeId]",
1322 $defaultLocId +
$tmpIdList,
1325 // Add the relevant information to the $migrationInfo
1326 // Keep location-type-id same as that of other-contact
1327 // @todo Check this logic out
1328 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1329 if ($blockName != 'address') {
1330 $elements[] = array('advcheckbox', "location_blocks[{$blockName}][$count][operation]", NULL, ts('Add new'));
1331 // always use add operation
1332 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1337 // Provide a select drop-down for the location's type/provider
1338 // eg websites: Google+, Facebook...
1340 if ($blockInfo['hasType']) {
1342 // Load the type options for this entity
1343 $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
1345 $thisTypeId = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
1347 // Put this field's location type at the top of the list
1348 $tmpIdList = $typeOptions['values'];
1349 $defaultTypeId = array($thisTypeId => CRM_Utils_Array
::value($thisTypeId, $tmpIdList));
1350 unset($tmpIdList[$thisTypeId]);
1353 $elements[] = array(
1355 "location_blocks[$blockName][$count][typeTypeId]",
1357 $defaultTypeId +
$tmpIdList,
1360 // Add the information to the migrationInfo
1361 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1365 // Set the label for this row
1366 $rowTitle = $blockInfo['label'] . ' ' . ($count +
1);
1367 if (!empty($thisLocId)) {
1368 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1370 if (!empty($thisTypeId)) {
1371 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1373 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1375 } // End loop through 'other' locations of this type
1377 } // End if 'other' location for this type exists
1379 } // End loop through each location block entity
1381 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1382 $config = CRM_Core_Config
::singleton();
1383 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1387 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1388 $mainUser = user_load($mainUfId);
1390 elseif ($config->userFramework
== 'Joomla') {
1391 $mainUser = JFactory
::getUser($mainUfId);
1394 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1398 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1399 $otherUser = user_load($otherUfId);
1401 elseif ($config->userFramework
== 'Joomla') {
1402 $otherUser = JFactory
::getUser($otherUfId);
1406 $relTables = CRM_Dedupe_Merger
::relTables();
1407 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1408 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1409 foreach ($relTables as $name => $null) {
1410 if (!in_array($name, $activeRelTables) &&
1411 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1413 unset($relTables[$name]);
1417 $relTableElements[] = array('checkbox', "move_$name");
1418 $migrationInfo["move_$name"] = 1;
1420 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1421 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1422 if ($name == 'rel_table_users') {
1423 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1424 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1425 $find = array('$ufid', '$ufname');
1427 $replace = array($mainUfId, $mainUser->name
);
1428 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1431 $replace = array($otherUfId, $otherUser->name
);
1432 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1435 if ($name == 'rel_table_memberships') {
1436 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1437 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1440 foreach ($relTables as $name => $null) {
1441 $relTables["move_$name"] = $relTables[$name];
1442 unset($relTables[$name]);
1445 // handle custom fields
1446 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $mainId, -1,
1447 CRM_Utils_Array
::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
1449 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $otherId, -1,
1450 CRM_Utils_Array
::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
1453 foreach ($otherTree as $gid => $group) {
1454 $foundField = FALSE;
1455 if (!isset($group['fields'])) {
1459 foreach ($group['fields'] as $fid => $field) {
1460 if (in_array($fid, $compareFields['custom'])) {
1462 $rows["custom_group_$gid"]['title'] = $group['title'];
1465 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1466 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1467 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1471 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1472 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1473 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1474 if ($values['data'] === 0 ||
$values['data'] === '0') {
1475 $values['data'] = $qfZeroBug;
1477 $value = ($values['data']) ?
$values['data'] : $value;
1480 $rows["move_custom_$fid"]['title'] = $field['label'];
1482 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1483 $migrationInfo["move_custom_$fid"] = $value;
1490 'elements' => $elements,
1491 'rel_table_elements' => $relTableElements,
1492 'rel_tables' => $relTables,
1493 'main_details' => $main,
1494 'other_details' => $other,
1495 'migration_info' => $migrationInfo,
1498 $result['main_details']['location_blocks'] = $locations['main'];
1499 $result['other_details']['location_blocks'] = $locations['other'];
1505 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1506 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1507 * A superset of moveContactBelongings() function.
1509 * @param int $mainId
1510 * Main contact with whom merge has to happen.
1511 * @param int $otherId
1512 * Duplicate contact which would be deleted after merge operation.
1514 * @param $migrationInfo
1516 * @param bool $checkPermissions
1517 * Respect logged in user permissions.
1521 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1522 if (empty($migrationInfo)) {
1526 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1527 $relTables = CRM_Dedupe_Merger
::relTables();
1528 $submittedCustomFields = $moveTables = $locationMigrationInfo = $tableOperations = $removeTables = array();
1530 foreach ($migrationInfo as $key => $value) {
1531 if ($value == $qfZeroBug) {
1535 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
1536 $submitted[substr($key, 5)] = $value;
1537 $submittedCustomFields[] = substr($key, 12);
1539 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) && $value != NULL) {
1540 $submitted[substr($key, 5)] = $value;
1542 // Set up initial information for handling migration of location blocks
1543 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1544 $locationMigrationInfo[$key] = $value;
1546 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1547 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1548 if (array_key_exists('operation', $migrationInfo)) {
1549 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1550 if (array_key_exists($key, $migrationInfo['operation'])) {
1551 $tableOperations[$table] = $migrationInfo['operation'][$key];
1556 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
1557 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1560 self
::mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo);
1562 // **** Do contact related migrations
1563 $customTablesToCopyValues = self
::getAffectedCustomTables($submittedCustomFields);
1564 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1565 unset($moveTables, $tableOperations);
1567 // **** Do table related removals
1568 if (!empty($removeTables)) {
1570 CRM_Dedupe_Merger
::removeContactBelongings($otherId, $removeTables);
1571 $removeTables = array();
1574 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1575 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1576 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1577 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1578 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1579 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1580 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1581 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1582 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1584 // fix custom fields so they're edible by createProfileContact()
1585 $treeCache = array();
1586 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1587 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree(
1588 $migrationInfo['main_details']['contact_type'],
1602 foreach ($treeCache[$migrationInfo['main_details']['contact_type']] as $key => $group) {
1603 if (!isset($group['fields'])) {
1606 foreach ($group['fields'] as $fid => $field) {
1607 $cFields[$fid]['attributes'] = $field;
1611 if (!isset($submitted)) {
1612 $submitted = array();
1614 foreach ($submitted as $key => $value) {
1615 if (substr($key, 0, 7) == 'custom_') {
1616 $fid = (int) substr($key, 7);
1617 if (empty($cFields[$fid])) {
1620 $htmlType = $cFields[$fid]['attributes']['html_type'];
1621 switch ($htmlType) {
1623 $customFiles[] = $fid;
1624 unset($submitted["custom_$fid"]);
1627 case 'Select Country':
1628 case 'Select State/Province':
1629 $submitted[$key] = CRM_Core_BAO_CustomField
::displayValue($value, $fid);
1633 if ($cFields[$fid]['attributes']['is_view']) {
1634 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
1639 case 'Multi-Select':
1640 case 'Multi-Select Country':
1641 case 'Multi-Select State/Province':
1642 // Merge values from both contacts for multivalue fields, CRM-4385
1643 // get the existing custom values from db.
1644 $customParams = array('entityID' => $mainId, $key => TRUE);
1645 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1646 if (!empty($customfieldValues[$key])) {
1647 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1648 if (is_array($existingValue) && !empty($existingValue)) {
1649 $mergeValue = $submittedCustomFields = array();
1650 if ($value == 'null') {
1651 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
1652 $submitted[$key] = $value;
1656 $submittedCustomFields = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1659 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
1660 // custom field value stored at $submittedCustomValue.
1661 foreach ($submittedCustomFields as $k => $v) {
1662 if ($v != '' && !in_array($v, $mergeValue)) {
1667 //keep state and country as array format.
1668 //for checkbox and m-select format w/ VALUE_SEPARATOR
1669 if (in_array($htmlType, array(
1673 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1675 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1678 $submitted[$key] = $mergeValue;
1683 elseif (in_array($htmlType, array(
1684 'Multi-Select Country',
1685 'Multi-Select State/Province',
1687 //we require submitted values should be in array format
1689 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1690 //hack to remove null values from array.
1691 $mergeValue = array();
1692 foreach ($mergeValueArray as $k => $v) {
1697 $submitted[$key] = $mergeValue;
1708 // **** Do file custom fields related migrations
1709 // FIXME: move this someplace else (one of the BAOs) after discussing
1710 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1711 // like, delete a file...
1713 if (!isset($customFiles)) {
1714 $customFiles = array();
1716 foreach ($customFiles as $customId) {
1717 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1719 // get the contact_id -> file_id mapping
1721 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1722 $dao = CRM_Core_DAO
::executeQuery($sql);
1723 while ($dao->fetch()) {
1724 $fileIds[$dao->entity_id
] = $dao->file_id
;
1725 if ($dao->entity_id
== $mainId) {
1726 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1731 // move the other contact's file to main contact
1732 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1733 if (CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
1734 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1737 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1739 CRM_Core_DAO
::executeQuery($sql);
1741 if (CRM_Core_DAO
::singleValueQuery("
1743 FROM civicrm_entity_file
1744 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1747 UPDATE civicrm_entity_file
1748 SET entity_id = {$mainId}
1749 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1753 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1754 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1756 CRM_Core_DAO
::executeQuery($sql);
1759 // move view only custom fields CRM-5362
1760 $viewOnlyCustomFields = array();
1761 foreach ($submitted as $key => $value) {
1762 $fid = CRM_Core_BAO_CustomField
::getKeyID($key);
1763 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1765 $viewOnlyCustomFields[$key] = $value;
1768 // special case to set values for view only, CRM-5362
1769 if (!empty($viewOnlyCustomFields)) {
1770 $viewOnlyCustomFields['entityID'] = $mainId;
1771 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1774 if (!$checkPermissions ||
(CRM_Core_Permission
::check('merge duplicate contacts') &&
1775 CRM_Core_Permission
::check('delete contacts'))
1777 // if ext id is submitted then set it null for contact to be deleted
1778 if (!empty($submitted['external_identifier'])) {
1779 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1780 CRM_Core_DAO
::executeQuery($query);
1782 civicrm_api3('contact', 'delete', array('id' => $otherId));
1785 // CRM-15681 merge sub_types
1786 if ($other_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1787 if ($main_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1788 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1791 $submitted['contact_sub_type'] = $other_sub_types;
1795 // **** Update contact related info for the main contact
1796 if (!empty($submitted)) {
1797 $submitted['contact_id'] = $mainId;
1799 //update current employer field
1800 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1801 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1802 $submitted['current_employer'] = $submitted['current_employer_id'];
1805 $submitted['current_employer'] = '';
1807 unset($submitted['current_employer_id']);
1810 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1811 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1812 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1814 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1815 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1818 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);
1821 CRM_Utils_Hook
::post('merge', 'Contact', $mainId);
1822 self
::createMergeActivities($mainId, $otherId);
1828 * Builds an Array of Custom tables for given custom field ID's.
1830 * @param $customFieldIDs
1833 * Array of custom table names
1835 private static function getAffectedCustomTables($customFieldIDs) {
1836 $customTableToCopyValues = array();
1838 foreach ($customFieldIDs as $fieldID) {
1839 if (!empty($fieldID)) {
1840 $customField = civicrm_api3('custom_field', 'getsingle', array(
1842 'is_active' => TRUE,
1844 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
1845 $customGroup = civicrm_api3('custom_group', 'getsingle', array(
1846 'id' => $customField['custom_group_id'],
1847 'is_active' => TRUE,
1850 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1851 $customTableToCopyValues[] = $customGroup['table_name'];
1857 return $customTableToCopyValues;
1861 * Get fields in the contact table suitable for merging.
1864 * Array of field names to be potentially merged.
1866 public static function getContactFields() {
1867 $contactFields = CRM_Contact_DAO_Contact
::fields();
1868 $invalidFields = array(
1875 'primary_contact_id',
1879 foreach ($contactFields as $field => $value) {
1880 if (in_array($field, $invalidFields)) {
1881 unset($contactFields[$field]);
1884 return array_keys($contactFields);
1888 * Added for CRM-12695
1889 * Based on the contactID provided
1890 * add/update membership(s) to related contacts
1892 * @param int $contactID
1894 public static function addMembershipToRealtedContacts($contactID) {
1895 $dao = new CRM_Member_DAO_Membership();
1896 $dao->contact_id
= $contactID;
1900 //checks membership of contact itself
1901 while ($dao->fetch()) {
1902 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1903 if ($relationshipTypeId) {
1904 $membershipParams = array(
1906 'contact_id' => $dao->contact_id
,
1907 'membership_type_id' => $dao->membership_type_id
,
1908 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1909 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1910 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1911 'source' => $dao->source
,
1912 'status_id' => $dao->status_id
,
1914 // create/update membership(s) for related contact(s)
1915 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1916 } // end of if relationshipTypeId
1921 * Create activities tracking the merge on affected contacts.
1923 * @param int $mainId
1924 * @param int $otherId
1926 * @throws \CiviCRM_API3_Exception
1928 public static function createMergeActivities($mainId, $otherId) {
1933 $activity = civicrm_api3('activity', 'create', array(
1934 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1936 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1937 'target_contact_id' => $mainId,
1938 'activity_type_id' => 'Contact Merged',
1939 'status_id' => 'Completed',
1941 if (civicrm_api3('Setting', 'getvalue', array('name' => 'contact_undelete', 'group' => 'CiviCRM Preferences'))) {
1942 civicrm_api3('activity', 'create', array(
1943 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1945 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1946 'target_contact_id' => $otherId,
1947 'activity_type_id' => 'Contact Deleted by Merge',
1948 'parent_id' => $activity['id'],
1949 'status_id' => 'Completed',
1955 * Get Duplicate Pairs based on a rule for a group.
1957 * @param int $rule_group_id
1958 * @param int $group_id
1959 * @param bool $reloadCacheIfEmpty
1960 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
1961 * @param int $batchLimit
1962 * @param bool $isSelected
1963 * Limit to selected pairs.
1964 * @param array|string $orderByClause
1965 * @param bool $includeConflicts
1966 * @param array $criteria
1967 * Additional criteria to narrow down the merge group.
1969 * @param bool $checkPermissions
1970 * Respect logged in user permissions.
1972 * @param int $searchLimit
1973 * Limit to searching for matches against this many contacts.
1976 * Array of matches meeting the criteria.
1978 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $orderByClause = '', $includeConflicts = TRUE, $criteria = array(), $checkPermissions = TRUE, $searchLimit = 0) {
1979 $where = self
::getWhereString($isSelected);
1980 $cacheKeyString = self
::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions);
1981 $join = self
::getJoinOnDedupeTable();
1982 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where, 0, $batchLimit, array(), $orderByClause, $includeConflicts);
1983 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1984 // If we haven't found any dupes, probably cache is empty.
1985 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1986 // until we have done some processing.
1987 CRM_Core_BAO_PrevNextCache
::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions, $searchLimit);
1988 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where, 0, $batchLimit, array(), $orderByClause, $includeConflicts);
1995 * Get the cache key string for the merge action.
1997 * @param int $rule_group_id
1998 * @param int $group_id
1999 * @param array $criteria
2000 * Additional criteria to narrow down the merge group.
2001 * Currently we are only supporting the key 'contact' within it.
2003 * @param bool $checkPermissions
2004 * Respect the users permissions.
2008 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = array(), $checkPermissions = TRUE) {
2009 $contactType = CRM_Dedupe_BAO_RuleGroup
::getContactTypeForRuleGroup($rule_group_id);
2010 $cacheKeyString = "merge_{$contactType}";
2011 $cacheKeyString .= $rule_group_id ?
"_{$rule_group_id}" : '_0';
2012 $cacheKeyString .= $group_id ?
"_{$group_id}" : '_0';
2013 $cacheKeyString .= !empty($criteria) ?
md5(serialize($criteria)) : '_0';
2014 if ($checkPermissions) {
2015 $contactID = CRM_Core_Session
::getLoggedInContactID();
2017 // Distinguish between no permission check & no logged in user.
2018 $contactID = 'null';
2020 $cacheKeyString .= '_' . $contactID;
2023 $cacheKeyString .= '_0';
2025 return $cacheKeyString;
2029 * @param array $contact
2033 public static function getSpecialValues($contact) {
2034 $preferred_communication_method = CRM_Utils_Array
::value('preferred_communication_method', $contact);
2035 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
2036 $specialValues = array(
2037 'preferred_communication_method' => $value,
2038 'communication_style_id' => $value,
2041 if (!empty($contact['preferred_communication_method'])) {
2042 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
2043 $prefCommList = is_array($specialValues['preferred_communication_method']) ?
implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues['preferred_communication_method']) : $specialValues['preferred_communication_method'];
2044 $specialValues['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
2047 'preferred_communication_method' => array(
2048 'newName' => 'preferred_communication_method_display',
2049 'groupName' => 'preferred_communication_method',
2052 CRM_Core_OptionGroup
::lookupValues($specialValues, $names);
2054 if (!empty($contact['communication_style'])) {
2055 $specialValues['communication_style_id_display'] = $contact['communication_style'];
2057 return $specialValues;
2061 * Get the metadata for the merge fields.
2063 * This is basically the contact metadata, augmented with fields to
2064 * represent email greeting, postal greeting & addressee.
2068 public static function getMergeFieldsMetadata() {
2069 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['merge_fields_metadata'])) {
2070 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
2072 $fields = CRM_Contact_DAO_Contact
::fields();
2073 static $optionValueFields = array();
2074 if (empty($optionValueFields)) {
2075 $optionValueFields = CRM_Core_OptionValue
::getFields();
2077 foreach ($optionValueFields as $field => $params) {
2078 $fields[$field]['title'] = $params['title'];
2080 \Civi
::$statics[__CLASS__
]['merge_fields_metadata'] = $fields;
2081 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
2085 * Get the details of the contact to be merged.
2087 * @param int $contact_id
2091 * @throws CRM_Core_Exception
2093 public static function getMergeContactDetails($contact_id) {
2095 'contact_id' => $contact_id,
2097 'return' => array_merge(array('display_name'), self
::getContactFields()),
2099 $result = civicrm_api('contact', 'get', $params);
2101 // CRM-18480: Cancel the process if the contact is already deleted
2102 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
2103 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', array(
2108 return $result['values'][$contact_id];
2114 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
2116 * The data is in the format received from the merge form (which is a fairly confusing format).
2118 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
2119 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
2120 * been calculated and before saving because
2121 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
2122 * - passing to a hook right before save means calculations only have to be done once
2123 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
2126 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
2127 * is likely to be significant data in merge hooks.
2129 * @param int $mainId
2130 * @param int $otherId
2131 * @param array $locationMigrationInfo
2132 * Portion of the migration_info that holds location migration information.
2134 * @param array $migrationInfo
2135 * Migration info for the merge. This is passed to the hook as informational only.
2137 public static function mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo) {
2138 foreach ($locationMigrationInfo as $key => $value) {
2139 $locField = explode('_', $key);
2140 $fieldName = $locField[2];
2141 $fieldCount = $locField[3];
2143 // Set up the operation type (add/overwrite)
2144 // Ignore operation for websites
2145 // @todo Tidy this up
2147 if ($fieldName != 'website') {
2148 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
2150 // default operation is overwrite.
2154 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
2156 $blocksDAO = array();
2158 // @todo Handle OpenID (not currently in API).
2159 if (!empty($locBlocks)) {
2160 $locationBlocks = self
::getLocationBlockInfo();
2162 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
2163 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
2165 foreach ($locBlocks as $name => $block) {
2166 $blocksDAO[$name] = array('delete' => array(), 'update' => array());
2167 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
2170 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
2171 $changePrimary = FALSE;
2172 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
2173 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
2175 foreach ($block as $blkCount => $values) {
2176 $otherBlockId = CRM_Utils_Array
::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
2177 $mainBlockId = CRM_Utils_Array
::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
2178 if (!$otherBlockId) {
2182 // For the block which belongs to other-contact, link the location block to main-contact
2183 $otherBlockDAO = new $daoName();
2184 $otherBlockDAO->contact_id
= $mainId;
2186 // Get the ID of this block on the 'other' contact, otherwise skip
2187 $otherBlockDAO->id
= $otherBlockId;
2189 // Add/update location and type information from the form, if applicable
2190 if ($locationBlocks[$name]['hasLocation']) {
2191 $locTypeId = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2192 $otherBlockDAO->location_type_id
= $locTypeId;
2194 if ($locationBlocks[$name]['hasType']) {
2195 $typeTypeId = CRM_Utils_Array
::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2196 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
2199 // If we're deliberately setting this as primary then add the flag
2200 // and remove it from the current primary location (if there is one).
2201 // But only once for each entity.
2202 $set_primary = CRM_Utils_Array
::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
2203 if (!$changePrimary && $set_primary == "1") {
2204 $otherBlockDAO->is_primary
= 1;
2205 if ($primaryDAOId) {
2206 $removePrimaryDAO = new $daoName();
2207 $removePrimaryDAO->id
= $primaryDAOId;
2208 $removePrimaryDAO->is_primary
= 0;
2209 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
2211 $changePrimary = TRUE;
2213 // Otherwise, if main contact already has primary, set it to 0.
2214 elseif ($primaryDAOId) {
2215 $otherBlockDAO->is_primary
= 0;
2218 // If the main contact already has a billing location, set this to 0.
2219 if ($billingDAOId) {
2220 $otherBlockDAO->is_billing
= 0;
2223 $operation = CRM_Utils_Array
::value('operation', $values, 2);
2224 // overwrite - need to delete block which belongs to main-contact.
2225 if (!empty($mainBlockId) && ($operation == 2)) {
2226 $deleteDAO = new $daoName();
2227 $deleteDAO->id
= $mainBlockId;
2228 $deleteDAO->find(TRUE);
2230 // if we about to delete a primary / billing block, set the flags for new block
2231 // that we going to assign to main-contact
2232 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
2233 $otherBlockDAO->is_primary
= 1;
2235 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
2236 $otherBlockDAO->is_billing
= 1;
2238 $blocksDAO[$name]['delete'][$deleteDAO->id
] = $deleteDAO;
2240 $blocksDAO[$name]['update'][$otherBlockDAO->id
] = $otherBlockDAO;
2245 CRM_Utils_Hook
::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2246 foreach ($blocksDAO as $blockDAOs) {
2247 if (!empty($blockDAOs['update'])) {
2248 foreach ($blockDAOs['update'] as $blockDAO) {
2252 if (!empty($blockDAOs['delete'])) {
2253 foreach ($blockDAOs['delete'] as $blockDAO) {
2254 $blockDAO->delete();
2261 * Dedupe a pair of contacts.
2263 * @param array $migrationInfo
2264 * @param array $resultStats
2265 * @param array $deletedContacts
2266 * @param string $mode
2267 * @param bool $checkPermissions
2268 * @param int $mainId
2269 * @param int $otherId
2270 * @param string $cacheKeyString
2272 protected static function dedupePair(&$migrationInfo, &$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) {
2274 // go ahead with merge if there is no conflict
2275 $conflicts = array();
2276 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2277 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2278 $resultStats['merged'][] = array(
2279 'main_id' => $mainId,
2280 'other_id' => $otherId,
2282 $deletedContacts[] = $otherId;
2285 $resultStats['skipped'][] = array(
2286 'main_id' => $mainId,
2287 'other_id' => $otherId,
2291 // store any conflicts
2292 if (!empty($conflicts)) {
2293 foreach ($conflicts as $key => $dnc) {
2294 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
2296 CRM_Core_BAO_PrevNextCache
::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
2299 // delete entry from PrevNextCache table so we don't consider the pair next time
2300 // pair may have been flipped, so make sure we delete using both orders
2301 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString, TRUE);