3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 includes core tables, custom group tables, tables added by the merge
207 * hook and (somewhat randomly) the entity_tag table.
209 * Refer to CRM-17454 for information on the danger of querying the information
210 * schema to derive this.
212 * This function calls the merge hook but the entityTypes hook is the recommended
213 * way to add tables to this result.
215 public static function cidRefs() {
216 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
217 return \Civi
::$statics[__CLASS__
]['contact_references'];
219 $contactReferences = array();
220 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
221 foreach ($coreReferences as $coreReference) {
222 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
223 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
226 self
::addCustomTablesExtendingContactsToCidRefs($contactReferences);
228 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
229 $contactReferences['civicrm_entity_tag'][] = 'entity_id';
231 // Allow hook_civicrm_merge() to adjust $cidRefs.
232 // Note that if entities are registered using the entityTypes hook there
233 // is no need to use this hook.
234 CRM_Utils_Hook
::merge('cidRefs', $contactReferences);
235 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
236 return \Civi
::$statics[__CLASS__
]['contact_references'];
240 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
242 public static function eidRefs() {
245 // FIXME: this should be generated dynamically from the schema
246 // tables that reference contacts with entity_{id,table}
248 'civicrm_acl' => array('entity_table' => 'entity_id'),
249 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
250 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
251 'civicrm_log' => array('entity_table' => 'entity_id'),
252 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
253 'civicrm_note' => array('entity_table' => 'entity_id'),
256 // Allow hook_civicrm_merge() to adjust $eidRefs
257 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
263 * Return tables using locations.
265 public static function locTables() {
268 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
270 // Allow hook_civicrm_merge() to adjust $locTables
271 CRM_Utils_Hook
::merge('locTables', $locTables);
277 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
278 * @param string $request
279 * 'relTables' or 'cidRefs'.
283 public static function getMultiValueCustomSets($request) {
285 if (!isset(Civi
::$statics[__CLASS__
]['multiValueCustomSets'])) {
287 'relTables' => array(),
288 'cidRefs' => array(),
290 $result = civicrm_api3('custom_group', 'get', array(
292 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
293 'return' => array('id', 'title', 'table_name', 'style'),
295 foreach ($result['values'] as $custom) {
296 $data['cidRefs'][$custom['table_name']] = array('entity_id');
297 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
298 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
299 'title' => $custom['title'],
300 'tables' => array($custom['table_name']),
301 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
305 // Store the result in a static variable cache
306 Civi
::$statics[__CLASS__
]['multiValueCustomSets'] = $data;
309 return Civi
::$statics[__CLASS__
]['multiValueCustomSets'][$request];
313 * Tables which require custom processing should declare functions to call here.
314 * Doing so will override normal processing.
316 public static function cpTables() {
320 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
321 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
322 // Empty array == do nothing - this table is handled by mergeGroupContact
323 'civicrm_subscription_history' => array(),
324 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
325 'civicrm_membership' => array('CRM_Member_BAO_Membership' => 'mergeMemberships'),
332 * Return payment related table.
334 public static function paymentTables() {
337 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
343 * Return payment update Query.
345 * @param string $tableName
346 * @param int $mainContactId
347 * @param int $otherContactId
351 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
353 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
357 $paymentTables = self
::paymentTables();
358 if (!in_array($tableName, $paymentTables)) {
362 switch ($tableName) {
363 case 'civicrm_pledge':
365 UPDATE IGNORE civicrm_contribution contribution
366 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
367 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
368 SET contribution.contact_id = $mainContactId
369 WHERE pledge.contact_id = $otherContactId";
372 case 'civicrm_membership':
374 UPDATE IGNORE civicrm_contribution contribution
375 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
376 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
377 SET contribution.contact_id = $mainContactId
378 WHERE membership.contact_id = $otherContactId";
381 case 'civicrm_participant':
383 UPDATE IGNORE civicrm_contribution contribution
384 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
385 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
386 SET contribution.contact_id = $mainContactId
387 WHERE participant.contact_id = $otherContactId";
396 * @param int $otherId
397 * @param string $tableName
398 * @param array $tableOperations
399 * @param string $mode
403 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
405 if (!$tableName ||
!$mainId ||
!$otherId) {
409 switch ($tableName) {
410 case 'civicrm_membership':
411 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
414 if ($mode == 'add') {
416 DELETE membership1.* FROM civicrm_membership membership1
417 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
418 AND membership1.contact_id = {$mainId}
419 AND membership2.contact_id = {$otherId} ";
421 if ($mode == 'payment') {
423 DELETE contribution.* FROM civicrm_contribution contribution
424 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
425 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
426 AND membership1.contact_id = {$mainId}
427 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
428 AND membership2.contact_id = {$otherId}";
432 case 'civicrm_uf_match':
433 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
434 // failing to meet intended result. Therefore we introduce this additional query:
435 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
443 * Based on the provided two contact_ids and a set of tables, remove the
444 * belongings of the other contact and of their relations.
446 * @param int $otherID
447 * @param bool $tables
449 public static function removeContactBelongings($otherID, $tables) {
450 // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
451 if (in_array("civicrm_membership", $tables)) {
452 $membershipIDs = CRM_Utils_Array
::collect('id',
453 CRM_Utils_Array
::value('values',
454 civicrm_api3("Membership", "get", array(
455 "contact_id" => $otherID,
461 if (!empty($membershipIDs)) {
462 civicrm_api3("Membership", "get", array(
463 'owner_membership_id' => array('IN' => $membershipIDs),
464 'api.Membership.delete' => array('id' => '$value.id'),
471 * Based on the provided two contact_ids and a set of tables, move the
472 * belongings of the other contact to the main one.
475 * @param int $otherId
476 * @param bool $tables
477 * @param array $tableOperations
478 * @param array $customTableToCopyFrom
480 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array(), $customTableToCopyFrom = NULL) {
481 $cidRefs = self
::cidRefs();
482 $eidRefs = self
::eidRefs();
483 $cpTables = self
::cpTables();
484 $paymentTables = self
::paymentTables();
486 // getting all custom tables
487 $customTables = array();
488 if ($customTableToCopyFrom !== NULL) {
489 self
::addCustomTablesExtendingContactsToCidRefs($customTables);
490 $customTables = array_keys($customTables);
493 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
495 // if there aren't any specific tables, don't affect the ones handled by relTables()
496 // also don't affect tables in locTables() CRM-15658
497 $relTables = self
::relTables();
498 $handled = self
::locTables();
500 foreach ($relTables as $params) {
501 $handled = array_merge($handled, $params['tables']);
503 $affected = array_diff($affected, $handled);
504 $affected = array_unique(array_merge($affected, $tables));
506 $mainId = (int) $mainId;
507 $otherId = (int) $otherId;
508 $multi_value_tables = array_keys(CRM_Dedupe_Merger
::getMultiValueCustomSets('cidRefs'));
511 foreach ($affected as $table) {
512 // skipping non selected single-value custom table's value migration
513 if (!in_array($table, $multi_value_tables)) {
514 if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
519 // Call custom processing function for objects that require it
520 if (isset($cpTables[$table])) {
521 foreach ($cpTables[$table] as $className => $fnName) {
522 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
524 // Skip normal processing
528 // use UPDATE IGNORE + DELETE query pair to skip on situations when
529 // there's a UNIQUE restriction on ($field, some_other_field) pair
530 if (isset($cidRefs[$table])) {
531 foreach ($cidRefs[$table] as $field) {
532 // carry related contributions CRM-5359
533 if (in_array($table, $paymentTables)) {
534 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
535 $sqls = array_merge($sqls, $paymentSqls);
537 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
538 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
539 $sqls = array_merge($sqls, $payOprSqls);
543 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
544 $sqls = array_merge($sqls, $preOperationSqls);
546 if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self
::customRecordExists($mainId, $table, $field)) {
547 $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
549 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
550 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
554 if (isset($eidRefs[$table])) {
555 foreach ($eidRefs[$table] as $entityTable => $entityId) {
556 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
557 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
562 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
563 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
565 // call the SQL queries in one transaction
566 $transaction = new CRM_Core_Transaction();
567 foreach ($sqls as $sql) {
568 CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, TRUE);
570 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
571 $transaction->commit();
575 * Given a contact ID, will check if a record exists in given table.
580 * Field where the contact's ID is stored in the table
583 * True if a record is found for the given contact ID, false otherwise
585 private static function customRecordExists($contactID, $table, $idField) {
587 SELECT COUNT(*) AS count
589 WHERE $idField = $contactID
591 $dbResult = CRM_Core_DAO
::executeQuery($sql);
594 if ($dbResult->count
> 0) {
602 * Load all non-empty fields for the contacts
606 * @param array $other
611 public static function retrieveFields($main, $other) {
613 'contact' => array(),
616 foreach (self
::getContactFields() as $validField) {
617 // CRM-17556 Get all non-empty fields, to make comparison easier
618 if (!empty($main[$validField]) ||
!empty($other[$validField])) {
619 $result['contact'][] = $validField;
623 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
624 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
625 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
626 foreach ($keys as $key) {
627 // Exclude multi-value fields CRM-13836
628 if (strpos($key, '_')) {
631 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
632 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
633 // CRM-17556 Get all non-empty fields, to make comparison easier
634 if (!empty($key1) ||
!empty($key2)) {
635 $result['custom'][] = $key;
642 * Batch merge a set of contacts based on rule-group and group.
648 * @param string $mode
649 * Helps decide how to behave when there are conflicts.
650 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
651 * mode does a force merge.
652 * @param int $batchLimit number of merges to carry out in one batch.
653 * @param int $isSelected if records with is_selected column needs to be processed.
654 * Note the option of '2' is only used in conjunction with $redirectForPerformance
655 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
656 * out in favour of explicitly passing in $reloadCacheIfEmpty
658 * @param array $criteria
659 * Criteria to use in the filter.
661 * @param bool $checkPermissions
662 * Respect logged in user permissions.
663 * @param bool|NULL $reloadCacheIfEmpty
664 * If not set explicitly this is calculated but it is preferred that it be set
665 * per comments on isSelected above.
669 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = array(), $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL) {
670 $redirectForPerformance = ($batchLimit > 1) ?
TRUE : FALSE;
672 if (!isset($reloadCacheIfEmpty)) {
673 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
675 if ($isSelected !== 0 && $isSelected !== 1) {
676 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
679 $dupePairs = self
::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, '', ($mode == 'aggressive'), $criteria, $checkPermissions);
681 $cacheParams = array(
682 'cache_key_string' => self
::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
683 // @todo stop passing these parameters in & instead calculate them in the merge function based
684 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
685 'join' => self
::getJoinOnDedupeTable(),
686 'where' => self
::getWhereString($isSelected),
687 'limit' => (int) $batchLimit,
689 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
693 * Get the string to join the prevnext cache to the dedupe table.
696 * The join string to join prevnext cache on the dedupe table.
698 public static function getJoinOnDedupeTable() {
700 LEFT JOIN civicrm_dedupe_exception de
702 pn.entity_id1 = de.contact_id1
703 AND pn.entity_id2 = de.contact_id2 )
708 * Get where string for dedupe join.
710 * @param bool $isSelected
714 protected static function getWhereString($isSelected) {
715 $where = "de.id IS NULL";
716 if ($isSelected === 0 ||
$isSelected === 1) {
717 $where .= " AND pn.is_selected = {$isSelected}";
723 * Update the statistics for the merge set.
725 * @param string $cacheKeyString
726 * @param array $result
728 public static function updateMergeStats($cacheKeyString, $result = array()) {
729 // gather latest stats
730 $merged = count($result['merged']);
731 $skipped = count($result['skipped']);
733 if ($merged <= 0 && $skipped <= 0) {
737 // get previous stats
738 $previousStats = CRM_Core_BAO_PrevNextCache
::retrieve("{$cacheKeyString}_stats");
739 if (!empty($previousStats)) {
740 if ($previousStats[0]['merged']) {
741 $merged = $merged +
$previousStats[0]['merged'];
743 if ($previousStats[0]['skipped']) {
744 $skipped = $skipped +
$previousStats[0]['skipped'];
749 CRM_Dedupe_Merger
::resetMergeStats($cacheKeyString);
751 // store the updated stats
754 'skipped' => $skipped,
756 $data = CRM_Core_DAO
::escapeString(serialize($data));
759 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
760 CRM_Core_BAO_PrevNextCache
::setItem($values);
764 * Delete information about merges for the given string.
766 * @param $cacheKeyString
768 public static function resetMergeStats($cacheKeyString) {
769 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, "{$cacheKeyString}_stats");
773 * Get merge outcome statistics.
775 * @param string $cacheKeyString
778 * Array of how many were merged and how many were skipped.
780 public static function getMergeStats($cacheKeyString) {
781 $stats = CRM_Core_BAO_PrevNextCache
::retrieve("{$cacheKeyString}_stats");
782 if (!empty($stats)) {
789 * Get merge statistics message.
791 * @param array $stats
795 public static function getMergeStatsMsg($stats) {
797 if (!empty($stats['merged'])) {
798 $msg = '<p>' . ts('One contact merged.', array('count' => $stats['merged'], 'plural' => '%count contacts merged.')) . '</p>';
800 if (!empty($stats['skipped'])) {
801 $msg .= '<p>' . ts('One contact was skipped.', array('count' => $stats['skipped'], 'plural' => '%count contacts were skipped.')) . '</p>';
807 * Merge given set of contacts. Performs core operation.
809 * @param array $dupePairs
810 * Set of pair of contacts for whom merge is to be done.
811 * @param array $cacheParams
812 * Prev-next-cache params based on which next pair of contacts are computed.
813 * Generally used with batch-merge.
814 * @param string $mode
815 * Helps decide how to behave when there are conflicts.
816 * A 'safe' value skips the merge if there are any un-resolved conflicts.
817 * Does a force merge otherwise (aggressive mode).
819 * @param bool $redirectForPerformance
820 * Redirect to a url for batch processing.
822 * @param bool $checkPermissions
823 * Respect logged in user permissions.
827 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
828 $redirectForPerformance = FALSE, $checkPermissions = TRUE
830 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
831 $resultStats = array('merged' => array(), 'skipped' => array());
833 // we don't want dupe caching to get reset after every-merge, and therefore set the
834 CRM_Core_Config
::setPermitCacheFlushMode(FALSE);
835 $deletedContacts = array();
837 while (!empty($dupePairs)) {
838 foreach ($dupePairs as $index => $dupes) {
839 if (in_array($dupes['dstID'], $deletedContacts) ||
in_array($dupes['srcID'], $deletedContacts)) {
840 unset($dupePairs[$index]);
843 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
844 $mainId = $dupes['dstID'];
845 $otherId = $dupes['srcID'];
847 if (!$mainId ||
!$otherId) {
851 // Generate var $migrationInfo. The variable structure is exactly same as
852 // $formValues submitted during a UI merge for a pair of contacts.
853 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions);
854 // add additional details that we might need to resolve conflicts
855 $rowsElementsAndInfo['migration_info']['main_details'] = &$rowsElementsAndInfo['main_details'];
856 $rowsElementsAndInfo['migration_info']['other_details'] = &$rowsElementsAndInfo['other_details'];
857 $rowsElementsAndInfo['migration_info']['rows'] = &$rowsElementsAndInfo['rows'];
859 self
::dedupePair($rowsElementsAndInfo['migration_info'], $resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString);
862 if ($cacheKeyString && !$redirectForPerformance) {
863 // retrieve next pair of dupes
864 // @todo call getDuplicatePairs.
865 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
866 $cacheParams['join'],
867 $cacheParams['where'],
869 $cacheParams['limit'],
876 // do not proceed. Terminate the loop
881 CRM_Dedupe_Merger
::updateMergeStats($cacheKeyString, $resultStats);
886 * A function which uses various rules / algorithms for choosing which contact to bias to
887 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
890 * Main contact with whom merge has to happen.
891 * @param int $otherId
892 * Duplicate contact which would be deleted after merge operation.
893 * @param array $migrationInfo
894 * Array of information about which elements to merge.
895 * @param string $mode
896 * Helps decide how to behave when there are conflicts.
897 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
898 * - Does a force merge otherwise (aggressive mode).
900 * @param array $conflicts
904 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
906 $originalMigrationInfo = $migrationInfo;
907 foreach ($migrationInfo as $key => $val) {
908 if ($val === "null") {
909 // Rule: Never overwrite with an empty value (in any mode)
910 unset($migrationInfo[$key]);
913 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
914 substr($key, 0, 12) == 'move_custom_'
917 // Rule: If both main-contact, and other-contact have a field with a
918 // different value, then let $mode decide if to merge it or not
920 (!empty($migrationInfo['rows'][$key]['main'])
921 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
922 // is probably true for other fields too - e.g. 'do_not_email' but
923 // leaving that investigation as a @todo - until tests can be written.
924 // Note the handling of this has test coverage - although the data-typing
925 // of '0' feels flakey we have insurance.
926 ||
($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
928 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
931 // note it down & lets wait for response from the hook.
932 // For no response $mode will decide if to skip this merge
933 $conflicts[$key] = NULL;
936 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
937 $locField = explode('_', $key);
938 $fieldName = $locField[2];
939 $fieldCount = $locField[3];
941 // Rule: Catch address conflicts (same address type on both contacts)
943 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
944 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
947 // Load the address we're inspecting from the 'other' contact
948 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
949 $addressRecordLocTypeId = CRM_Utils_Array
::value('location_type_id', $addressRecord);
951 // If it exists on the 'main' contact already, skip it. Otherwise
952 // if the location type exists already, log a conflict.
953 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
954 if (self
::locationIsSame($addressRecord, $mainAddressRecord)) {
955 unset($migrationInfo[$key]);
958 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
959 $conflicts[$key] = NULL;
965 // For other locations, don't merge/add if the values are the same
966 elseif (CRM_Utils_Array
::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
967 unset($migrationInfo[$key]);
972 // A hook to implement other algorithms for choosing which contact to bias to when
973 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
974 // merge happens with new values filled in here. For a particular field / row not to be merged
975 // field should be unset from fields_in_conflict.
976 $migrationData = array(
977 'old_migration_info' => $originalMigrationInfo,
979 'fields_in_conflict' => $conflicts,
980 'merge_mode' => $mode,
981 'migration_info' => $migrationInfo,
983 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
984 $conflicts = $migrationData['fields_in_conflict'];
985 // allow hook to override / manipulate migrationInfo as well
986 $migrationInfo = $migrationData['migration_info'];
988 if (!empty($conflicts)) {
989 foreach ($conflicts as $key => $val) {
990 if ($val === NULL and $mode == 'safe') {
991 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
995 // copy over the resolved values
996 $migrationInfo[$key] = $val;
999 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
1000 if (array_key_exists('skip_merge', $migrationData)) {
1001 return (bool) $migrationData['skip_merge'];
1008 * Compare 2 addresses to see if they are the same.
1010 * @param array $mainAddress
1011 * @param array $comparisonAddress
1015 static public function locationIsSame($mainAddress, $comparisonAddress) {
1016 $keysToIgnore = array('id', 'is_primary', 'is_billing', 'manual_geo_code', 'contact_id', 'reset_date', 'hold_date');
1017 foreach ($comparisonAddress as $field => $value) {
1018 if (in_array($field, $keysToIgnore)) {
1021 if ((!empty($value) ||
$value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
1029 * A function to build an array of information about location blocks that is
1030 * required when merging location fields
1034 public static function getLocationBlockInfo() {
1035 $locationBlocks = array(
1037 'label' => 'Address',
1038 'displayField' => 'display',
1039 'sortString' => 'location_type_id',
1040 'hasLocation' => TRUE,
1045 'displayField' => 'display',
1046 'sortString' => 'location_type_id',
1047 'hasLocation' => TRUE,
1052 'displayField' => 'name',
1053 'sortString' => 'location_type_id,provider_id',
1054 'hasLocation' => TRUE,
1055 'hasType' => 'provider_id',
1059 'displayField' => 'phone',
1060 'sortString' => 'location_type_id,phone_type_id',
1061 'hasLocation' => TRUE,
1062 'hasType' => 'phone_type_id',
1065 'label' => 'Website',
1066 'displayField' => 'url',
1067 'sortString' => 'website_type_id',
1068 'hasLocation' => FALSE,
1069 'hasType' => 'website_type_id',
1072 return $locationBlocks;
1076 * A function to build an array of information required by merge function and the merge UI.
1078 * @param int $mainId
1079 * Main contact with whom merge has to happen.
1080 * @param int $otherId
1081 * Duplicate contact which would be deleted after merge operation.
1082 * @param bool $checkPermissions
1083 * Should the logged in user's permissions be ignore. Setting this to false is
1084 * highly risky as it could cause data to be lost due to conflicts not showing up.
1085 * OTOH there is a risk a merger might view custom data they do not have permission to.
1086 * Hence for now only making this really explicit and making it reflect perms in
1089 * @todo review permissions issue!
1091 * @return array|bool|int
1093 * rows => An array of arrays, each is row of merge information for the table
1094 * Format: move_fieldname, eg: move_contact_type
1095 * main => Value associated with the main contact
1096 * other => Value associated with the other contact
1097 * title => The title of the field to display in the merge table
1099 * elements => An array of form elements for the merge UI
1101 * rel_table_elements => An array of form elements for the merge UI for
1102 * entities related to the contact (eg: checkbox to move 'mailings')
1104 * rel_tables => Stores the tables that have related entities for the contact
1105 * for example mailings, groups
1107 * main_details => An array of core contact field values, eg: first_name, etc.
1108 * location_blocks => An array of location block data for the main contact
1109 * stored as the 'result' of an API call.
1110 * eg: main_details['location_blocks']['address'][0]['id']
1111 * eg: main_details['location_blocks']['email'][1]['id']
1113 * other_details => As above, but for the 'other' contact
1115 * migration_info => Stores the 'default' merge actions for each field which
1116 * is used when programatically merging contacts. It contains instructions
1117 * to move all fields from the 'other' contact to the 'main' contact, as
1118 * though the form had been submitted with those options.
1120 * @throws \CRM_Core_Exception
1121 * @throws \CiviCRM_API3_Exception
1122 * @throws \Exception
1124 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1125 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1126 $fields = self
::getMergeFieldsMetadata();
1128 $main = self
::getMergeContactDetails($mainId);
1129 $other = self
::getMergeContactDetails($otherId);
1130 $specialValues['main'] = self
::getSpecialValues($main);
1131 $specialValues['other'] = self
::getSpecialValues($other);
1133 $compareFields = self
::retrieveFields($main, $other);
1135 $rows = $elements = $relTableElements = $migrationInfo = array();
1137 foreach ($compareFields['contact'] as $field) {
1138 if ($field == 'contact_sub_type') {
1139 // CRM-15681 don't display sub-types in UI
1142 foreach (array('main', 'other') as $moniker) {
1143 $contact = &$
$moniker;
1144 $value = CRM_Utils_Array
::value($field, $contact);
1145 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
1146 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1148 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
1149 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
1151 $value = str_replace('-', '', $value);
1152 $label = CRM_Utils_Date
::customFormat($label);
1158 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
1159 if ($label === '0') {
1162 if ($label === '1') {
1166 elseif ($field == 'prefix_id') {
1167 $label = CRM_Utils_Array
::value('individual_prefix', $contact);
1169 elseif ($field == 'suffix_id') {
1170 $label = CRM_Utils_Array
::value('individual_suffix', $contact);
1172 elseif ($field == 'gender_id' && !empty($value)) {
1173 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
1174 $label = $genderOptions['values'][$value];
1176 elseif ($field == 'current_employer_id' && !empty($value)) {
1177 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
1179 $rows["move_$field"][$moniker] = $label;
1180 if ($moniker == 'other') {
1182 if ($value === NULL ||
$value == '') {
1185 if ($value === 0 or $value === '0') {
1186 $value = $qfZeroBug;
1188 if (is_array($value) && empty($value[1])) {
1192 // Display a checkbox to migrate, only if the values are different
1193 if ($value != $main[$field]) {
1194 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1197 $migrationInfo["move_$field"] = $value;
1200 $rows["move_$field"]['title'] = $fields[$field]['title'];
1203 // Handle location blocks.
1204 // @todo OpenID not in API yet, so is not supported here.
1206 // Set up useful information about the location blocks
1207 $locationBlocks = self
::getLocationBlockInfo();
1214 // @todo This could probably be defined and used earlier
1215 $mergeTargets = array(
1217 'other' => $otherId,
1220 foreach ($locationBlocks as $blockName => $blockInfo) {
1222 // Collect existing fields from both 'main' and 'other' contacts first
1223 // This allows us to match up location/types when building the table rows
1224 foreach ($mergeTargets as $moniker => $cid) {
1225 $searchParams = array(
1226 'contact_id' => $cid,
1227 // CRM-17556 Order by field-specific criteria
1229 'sort' => $blockInfo['sortString'],
1232 $values = civicrm_api3($blockName, 'get', $searchParams);
1233 if ($values['count']) {
1235 foreach ($values['values'] as $value) {
1236 $locations[$moniker][$blockName][$cnt] = $value;
1237 // Fix address display
1238 if ($blockName == 'address') {
1239 CRM_Core_BAO_Address
::fixAddress($value);
1240 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address
::format($value);
1242 // Fix email display
1243 elseif ($blockName == 'email') {
1244 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Mail
::format($value);
1252 // Now, build the table rows appropriately, based off the information on
1253 // the 'other' contact
1254 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1255 foreach ($locations['other'][$blockName] as $count => $value) {
1257 $displayValue = $value[$blockInfo['displayField']];
1259 // Add this value to the table rows
1260 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1262 // CRM-17556 Only display 'main' contact value if it's the same location + type
1263 // Look it up from main values...
1265 $lookupLocation = FALSE;
1266 if ($blockInfo['hasLocation']) {
1267 $lookupLocation = $value['location_type_id'];
1270 $lookupType = FALSE;
1271 if ($blockInfo['hasType']) {
1272 $lookupType = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
1275 // Hold ID of main contact's matching block
1276 $mainContactBlockId = 0;
1278 if (!empty($locations['main'][$blockName])) {
1279 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1280 // No location/type, or matching location and type
1282 (empty($lookupLocation) ||
$lookupLocation == $mainValueCheck['location_type_id'])
1283 && (empty($lookupType) ||
$lookupType == $mainValueCheck[$blockInfo['hasType']])
1285 // Set this value as the default against the 'other' contact value
1286 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1287 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
1288 $mainContactBlockId = $mainValueCheck['id'];
1294 // Add checkbox to migrate data from 'other' to 'main'
1295 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
1297 // Add checkbox to set the 'other' location as primary
1298 $elements[] = array('advcheckbox', "location_blocks[$blockName][$count][set_other_primary]", NULL, ts('Set as primary'));
1300 // Flag up this field to skipMerge function (@todo: do we need to?)
1301 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1303 // Add a hidden field to store the ID of the target main contact block
1304 $elements[] = array('hidden', "location_blocks[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
1307 $thisTypeId = FALSE;
1310 // Provide a select drop-down for the location's location type
1311 // eg: Home, Work...
1313 if ($blockInfo['hasLocation']) {
1315 // Load the location options for this entity
1316 $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
1318 $thisLocId = $value['location_type_id'];
1320 // Put this field's location type at the top of the list
1321 $tmpIdList = $locationOptions['values'];
1322 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1323 unset($tmpIdList[$thisLocId]);
1326 $elements[] = array(
1328 "location_blocks[$blockName][$count][locTypeId]",
1330 $defaultLocId +
$tmpIdList,
1333 // Add the relevant information to the $migrationInfo
1334 // Keep location-type-id same as that of other-contact
1335 // @todo Check this logic out
1336 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1337 if ($blockName != 'address') {
1338 $elements[] = array('advcheckbox', "location_blocks[{$blockName}][$count][operation]", NULL, ts('Add new'));
1339 // always use add operation
1340 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1345 // Provide a select drop-down for the location's type/provider
1346 // eg websites: Google+, Facebook...
1348 if ($blockInfo['hasType']) {
1350 // Load the type options for this entity
1351 $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
1353 $thisTypeId = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
1355 // Put this field's location type at the top of the list
1356 $tmpIdList = $typeOptions['values'];
1357 $defaultTypeId = array($thisTypeId => CRM_Utils_Array
::value($thisTypeId, $tmpIdList));
1358 unset($tmpIdList[$thisTypeId]);
1361 $elements[] = array(
1363 "location_blocks[$blockName][$count][typeTypeId]",
1365 $defaultTypeId +
$tmpIdList,
1368 // Add the information to the migrationInfo
1369 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1373 // Set the label for this row
1374 $rowTitle = $blockInfo['label'] . ' ' . ($count +
1);
1375 if (!empty($thisLocId)) {
1376 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1378 if (!empty($thisTypeId)) {
1379 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1381 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1383 } // End loop through 'other' locations of this type
1385 } // End if 'other' location for this type exists
1387 } // End loop through each location block entity
1389 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1390 $config = CRM_Core_Config
::singleton();
1391 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1395 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1396 $mainUser = user_load($mainUfId);
1398 elseif ($config->userFramework
== 'Joomla') {
1399 $mainUser = JFactory
::getUser($mainUfId);
1402 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1406 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1407 $otherUser = user_load($otherUfId);
1409 elseif ($config->userFramework
== 'Joomla') {
1410 $otherUser = JFactory
::getUser($otherUfId);
1414 $relTables = CRM_Dedupe_Merger
::relTables();
1415 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1416 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1417 foreach ($relTables as $name => $null) {
1418 if (!in_array($name, $activeRelTables) &&
1419 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1421 unset($relTables[$name]);
1425 $relTableElements[] = array('checkbox', "move_$name");
1426 $migrationInfo["move_$name"] = 1;
1428 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1429 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1430 if ($name == 'rel_table_users') {
1431 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1432 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1433 $find = array('$ufid', '$ufname');
1435 $replace = array($mainUfId, $mainUser->name
);
1436 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1439 $replace = array($otherUfId, $otherUser->name
);
1440 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1443 if ($name == 'rel_table_memberships') {
1444 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1445 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1448 foreach ($relTables as $name => $null) {
1449 $relTables["move_$name"] = $relTables[$name];
1450 unset($relTables[$name]);
1453 // handle custom fields
1454 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $mainId, -1,
1455 CRM_Utils_Array
::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
1457 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $otherId, -1,
1458 CRM_Utils_Array
::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
1461 foreach ($otherTree as $gid => $group) {
1462 $foundField = FALSE;
1463 if (!isset($group['fields'])) {
1467 foreach ($group['fields'] as $fid => $field) {
1468 if (in_array($fid, $compareFields['custom'])) {
1470 $rows["custom_group_$gid"]['title'] = $group['title'];
1473 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1474 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1475 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1479 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1480 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1481 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1482 if ($values['data'] === 0 ||
$values['data'] === '0') {
1483 $values['data'] = $qfZeroBug;
1485 $value = ($values['data']) ?
$values['data'] : $value;
1488 $rows["move_custom_$fid"]['title'] = $field['label'];
1490 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1491 $migrationInfo["move_custom_$fid"] = $value;
1498 'elements' => $elements,
1499 'rel_table_elements' => $relTableElements,
1500 'rel_tables' => $relTables,
1501 'main_details' => $main,
1502 'other_details' => $other,
1503 'migration_info' => $migrationInfo,
1506 $result['main_details']['location_blocks'] = $locations['main'];
1507 $result['other_details']['location_blocks'] = $locations['other'];
1513 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1514 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1515 * A superset of moveContactBelongings() function.
1517 * @param int $mainId
1518 * Main contact with whom merge has to happen.
1519 * @param int $otherId
1520 * Duplicate contact which would be deleted after merge operation.
1522 * @param $migrationInfo
1524 * @param bool $checkPermissions
1525 * Respect logged in user permissions.
1529 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1530 if (empty($migrationInfo)) {
1534 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1535 $relTables = CRM_Dedupe_Merger
::relTables();
1536 $submittedCustomFields = $moveTables = $locationMigrationInfo = $tableOperations = $removeTables = array();
1538 foreach ($migrationInfo as $key => $value) {
1539 if ($value == $qfZeroBug) {
1543 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
1544 $submitted[substr($key, 5)] = $value;
1545 $submittedCustomFields[] = substr($key, 12);
1547 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) && $value != NULL) {
1548 $submitted[substr($key, 5)] = $value;
1550 // Set up initial information for handling migration of location blocks
1551 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1552 $locationMigrationInfo[$key] = $value;
1554 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1555 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1556 if (array_key_exists('operation', $migrationInfo)) {
1557 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1558 if (array_key_exists($key, $migrationInfo['operation'])) {
1559 $tableOperations[$table] = $migrationInfo['operation'][$key];
1564 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
1565 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1568 self
::mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo);
1570 // **** Do contact related migrations
1571 $customTablesToCopyValues = self
::getAffectedCustomTables($submittedCustomFields);
1572 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1573 unset($moveTables, $tableOperations);
1575 // **** Do table related removals
1576 if (!empty($removeTables)) {
1578 CRM_Dedupe_Merger
::removeContactBelongings($otherId, $removeTables);
1579 $removeTables = array();
1582 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1583 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1584 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1585 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1586 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1587 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1588 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1589 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1590 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1592 // fix custom fields so they're edible by createProfileContact()
1593 $treeCache = array();
1594 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1595 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree(
1596 $migrationInfo['main_details']['contact_type'],
1610 foreach ($treeCache[$migrationInfo['main_details']['contact_type']] as $key => $group) {
1611 if (!isset($group['fields'])) {
1614 foreach ($group['fields'] as $fid => $field) {
1615 $cFields[$fid]['attributes'] = $field;
1619 if (!isset($submitted)) {
1620 $submitted = array();
1622 foreach ($submitted as $key => $value) {
1623 if (substr($key, 0, 7) == 'custom_') {
1624 $fid = (int) substr($key, 7);
1625 if (empty($cFields[$fid])) {
1628 $htmlType = $cFields[$fid]['attributes']['html_type'];
1629 switch ($htmlType) {
1631 $customFiles[] = $fid;
1632 unset($submitted["custom_$fid"]);
1635 case 'Select Country':
1636 case 'Select State/Province':
1637 $submitted[$key] = CRM_Core_BAO_CustomField
::displayValue($value, $fid);
1641 if ($cFields[$fid]['attributes']['is_view']) {
1642 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
1647 case 'Multi-Select':
1648 case 'Multi-Select Country':
1649 case 'Multi-Select State/Province':
1650 // Merge values from both contacts for multivalue fields, CRM-4385
1651 // get the existing custom values from db.
1652 $customParams = array('entityID' => $mainId, $key => TRUE);
1653 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1654 if (!empty($customfieldValues[$key])) {
1655 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1656 if (is_array($existingValue) && !empty($existingValue)) {
1657 $mergeValue = $submittedCustomFields = array();
1658 if ($value == 'null') {
1659 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
1660 $submitted[$key] = $value;
1664 $submittedCustomFields = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1667 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
1668 // custom field value stored at $submittedCustomValue.
1669 foreach ($submittedCustomFields as $k => $v) {
1670 if ($v != '' && !in_array($v, $mergeValue)) {
1675 //keep state and country as array format.
1676 //for checkbox and m-select format w/ VALUE_SEPARATOR
1677 if (in_array($htmlType, array(
1681 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1683 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1686 $submitted[$key] = $mergeValue;
1691 elseif (in_array($htmlType, array(
1692 'Multi-Select Country',
1693 'Multi-Select State/Province',
1695 //we require submitted values should be in array format
1697 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1698 //hack to remove null values from array.
1699 $mergeValue = array();
1700 foreach ($mergeValueArray as $k => $v) {
1705 $submitted[$key] = $mergeValue;
1716 // **** Do file custom fields related migrations
1717 // FIXME: move this someplace else (one of the BAOs) after discussing
1718 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1719 // like, delete a file...
1721 if (!isset($customFiles)) {
1722 $customFiles = array();
1724 foreach ($customFiles as $customId) {
1725 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1727 // get the contact_id -> file_id mapping
1729 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1730 $dao = CRM_Core_DAO
::executeQuery($sql);
1731 while ($dao->fetch()) {
1732 $fileIds[$dao->entity_id
] = $dao->file_id
;
1733 if ($dao->entity_id
== $mainId) {
1734 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1739 // move the other contact's file to main contact
1740 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1741 if (CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
1742 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1745 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1747 CRM_Core_DAO
::executeQuery($sql);
1749 if (CRM_Core_DAO
::singleValueQuery("
1751 FROM civicrm_entity_file
1752 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1755 UPDATE civicrm_entity_file
1756 SET entity_id = {$mainId}
1757 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1761 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1762 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1764 CRM_Core_DAO
::executeQuery($sql);
1767 // move view only custom fields CRM-5362
1768 $viewOnlyCustomFields = array();
1769 foreach ($submitted as $key => $value) {
1770 $fid = CRM_Core_BAO_CustomField
::getKeyID($key);
1771 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1773 $viewOnlyCustomFields[$key] = $value;
1776 // special case to set values for view only, CRM-5362
1777 if (!empty($viewOnlyCustomFields)) {
1778 $viewOnlyCustomFields['entityID'] = $mainId;
1779 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1782 if (!$checkPermissions ||
(CRM_Core_Permission
::check('merge duplicate contacts') &&
1783 CRM_Core_Permission
::check('delete contacts'))
1785 // if ext id is submitted then set it null for contact to be deleted
1786 if (!empty($submitted['external_identifier'])) {
1787 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1788 CRM_Core_DAO
::executeQuery($query);
1790 civicrm_api3('contact', 'delete', array('id' => $otherId));
1793 // CRM-15681 merge sub_types
1794 if ($other_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1795 if ($main_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1796 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1799 $submitted['contact_sub_type'] = $other_sub_types;
1803 // **** Update contact related info for the main contact
1804 if (!empty($submitted)) {
1805 $submitted['contact_id'] = $mainId;
1807 //update current employer field
1808 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1809 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1810 $submitted['current_employer'] = $submitted['current_employer_id'];
1813 $submitted['current_employer'] = '';
1815 unset($submitted['current_employer_id']);
1818 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1819 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1820 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1822 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1823 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1826 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);
1829 CRM_Utils_Hook
::post('merge', 'Contact', $mainId);
1830 self
::createMergeActivities($mainId, $otherId);
1836 * Builds an Array of Custom tables for given custom field ID's.
1838 * @param $customFieldIDs
1841 * Array of custom table names
1843 private static function getAffectedCustomTables($customFieldIDs) {
1844 $customTableToCopyValues = array();
1846 foreach ($customFieldIDs as $fieldID) {
1847 if (!empty($fieldID)) {
1848 $customField = civicrm_api3('custom_field', 'getsingle', array(
1850 'is_active' => TRUE,
1852 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
1853 $customGroup = civicrm_api3('custom_group', 'getsingle', array(
1854 'id' => $customField['custom_group_id'],
1855 'is_active' => TRUE,
1858 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1859 $customTableToCopyValues[] = $customGroup['table_name'];
1865 return $customTableToCopyValues;
1869 * Get fields in the contact table suitable for merging.
1872 * Array of field names to be potentially merged.
1874 public static function getContactFields() {
1875 $contactFields = CRM_Contact_DAO_Contact
::fields();
1876 $invalidFields = array(
1883 'primary_contact_id',
1887 foreach ($contactFields as $field => $value) {
1888 if (in_array($field, $invalidFields)) {
1889 unset($contactFields[$field]);
1892 return array_keys($contactFields);
1896 * Added for CRM-12695
1897 * Based on the contactID provided
1898 * add/update membership(s) to related contacts
1900 * @param int $contactID
1902 public static function addMembershipToRealtedContacts($contactID) {
1903 $dao = new CRM_Member_DAO_Membership();
1904 $dao->contact_id
= $contactID;
1908 //checks membership of contact itself
1909 while ($dao->fetch()) {
1910 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1911 if ($relationshipTypeId) {
1912 $membershipParams = array(
1914 'contact_id' => $dao->contact_id
,
1915 'membership_type_id' => $dao->membership_type_id
,
1916 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1917 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1918 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1919 'source' => $dao->source
,
1920 'status_id' => $dao->status_id
,
1922 // create/update membership(s) for related contact(s)
1923 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1924 } // end of if relationshipTypeId
1929 * Add custom tables that extend contacts to the list of contact references.
1931 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
1932 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
1933 * - the down side is it is not cached.
1935 * Further changes should be include tests in the CRM_Core_MergerTest class
1936 * to ensure that disabled, subtype, multiple etc groups are still captured.
1938 * @param array $cidRefs
1940 public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
1941 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
1942 $customValueTables->find();
1943 while ($customValueTables->fetch()) {
1944 $cidRefs[$customValueTables->table_name
] = array('entity_id');
1949 * Create activities tracking the merge on affected contacts.
1951 * @param int $mainId
1952 * @param int $otherId
1954 * @throws \CiviCRM_API3_Exception
1956 public static function createMergeActivities($mainId, $otherId) {
1961 $activity = civicrm_api3('activity', 'create', array(
1962 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1964 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1965 'target_contact_id' => $mainId,
1966 'activity_type_id' => 'Contact Merged',
1967 'status_id' => 'Completed',
1969 if (civicrm_api3('Setting', 'getvalue', array('name' => 'contact_undelete', 'group' => 'CiviCRM Preferences'))) {
1970 civicrm_api3('activity', 'create', array(
1971 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1973 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1974 'target_contact_id' => $otherId,
1975 'activity_type_id' => 'Contact Deleted by Merge',
1976 'parent_id' => $activity['id'],
1977 'status_id' => 'Completed',
1983 * Get Duplicate Pairs based on a rule for a group.
1985 * @param int $rule_group_id
1986 * @param int $group_id
1987 * @param bool $reloadCacheIfEmpty
1988 * @param int $batchLimit
1989 * @param bool $isSelected
1990 * Limit to selected pairs.
1991 * @param array|string $orderByClause
1992 * @param bool $includeConflicts
1993 * @param array $criteria
1994 * Additional criteria to narrow down the merge group.
1996 * @param bool $checkPermissions
1997 * Respect logged in user permissions.
1999 * @param int $searchLimit
2000 * Limit to searching for matches against this many contacts.
2003 * Array of matches meeting the criteria.
2005 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $orderByClause = '', $includeConflicts = TRUE, $criteria = array(), $checkPermissions = TRUE, $searchLimit = 0) {
2006 $where = self
::getWhereString($isSelected);
2007 $cacheKeyString = self
::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions);
2008 $join = self
::getJoinOnDedupeTable();
2009 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where, 0, $batchLimit, array(), $orderByClause, $includeConflicts);
2010 if (empty($dupePairs) && $reloadCacheIfEmpty) {
2011 // If we haven't found any dupes, probably cache is empty.
2012 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
2013 // until we have done some processing.
2014 CRM_Core_BAO_PrevNextCache
::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions, $searchLimit);
2015 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where, 0, $batchLimit, array(), $orderByClause, $includeConflicts);
2022 * Get the cache key string for the merge action.
2024 * @param int $rule_group_id
2025 * @param int $group_id
2026 * @param array $criteria
2027 * Additional criteria to narrow down the merge group.
2028 * Currently we are only supporting the key 'contact' within it.
2030 * @param bool $checkPermissions
2031 * Respect the users permissions.
2035 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = array(), $checkPermissions = TRUE) {
2036 $contactType = CRM_Dedupe_BAO_RuleGroup
::getContactTypeForRuleGroup($rule_group_id);
2037 $cacheKeyString = "merge {$contactType}";
2038 $cacheKeyString .= $rule_group_id ?
"_{$rule_group_id}" : '_0';
2039 $cacheKeyString .= $group_id ?
"_{$group_id}" : '_0';
2040 $cacheKeyString .= !empty($criteria) ?
md5(serialize($criteria)) : '_0';
2041 if ($checkPermissions) {
2042 $contactID = CRM_Core_Session
::getLoggedInContactID();
2044 // Distinguish between no permission check & no logged in user.
2045 $contactID = 'null';
2047 $cacheKeyString .= '_' . $contactID;
2050 $cacheKeyString .= '_0';
2052 return $cacheKeyString;
2056 * @param array $contact
2060 public static function getSpecialValues($contact) {
2061 $preferred_communication_method = CRM_Utils_Array
::value('preferred_communication_method', $contact);
2062 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
2063 $specialValues = array(
2064 'preferred_communication_method' => $value,
2065 'communication_style_id' => $value,
2068 if (!empty($contact['preferred_communication_method'])) {
2069 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
2070 $prefCommList = is_array($specialValues['preferred_communication_method']) ?
implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues['preferred_communication_method']) : $specialValues['preferred_communication_method'];
2071 $specialValues['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
2074 'preferred_communication_method' => array(
2075 'newName' => 'preferred_communication_method_display',
2076 'groupName' => 'preferred_communication_method',
2079 CRM_Core_OptionGroup
::lookupValues($specialValues, $names);
2081 if (!empty($contact['communication_style'])) {
2082 $specialValues['communication_style_id_display'] = $contact['communication_style'];
2084 return $specialValues;
2088 * Get the metadata for the merge fields.
2090 * This is basically the contact metadata, augmented with fields to
2091 * represent email greeting, postal greeting & addressee.
2095 public static function getMergeFieldsMetadata() {
2096 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['merge_fields_metadata'])) {
2097 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
2099 $fields = CRM_Contact_DAO_Contact
::fields();
2100 static $optionValueFields = array();
2101 if (empty($optionValueFields)) {
2102 $optionValueFields = CRM_Core_OptionValue
::getFields();
2104 foreach ($optionValueFields as $field => $params) {
2105 $fields[$field]['title'] = $params['title'];
2107 \Civi
::$statics[__CLASS__
]['merge_fields_metadata'] = $fields;
2108 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
2112 * Get the details of the contact to be merged.
2114 * @param int $contact_id
2118 * @throws CRM_Core_Exception
2120 public static function getMergeContactDetails($contact_id) {
2122 'contact_id' => $contact_id,
2124 'return' => array_merge(array('display_name'), self
::getContactFields()),
2126 $result = civicrm_api('contact', 'get', $params);
2128 // CRM-18480: Cancel the process if the contact is already deleted
2129 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
2130 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', array(
2135 return $result['values'][$contact_id];
2141 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
2143 * The data is in the format received from the merge form (which is a fairly confusing format).
2145 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
2146 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
2147 * been calculated and before saving because
2148 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
2149 * - passing to a hook right before save means calculations only have to be done once
2150 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
2153 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
2154 * is likely to be significant data in merge hooks.
2156 * @param int $mainId
2157 * @param int $otherId
2158 * @param array $locationMigrationInfo
2159 * Portion of the migration_info that holds location migration information.
2161 * @param array $migrationInfo
2162 * Migration info for the merge. This is passed to the hook as informational only.
2164 public static function mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo) {
2165 foreach ($locationMigrationInfo as $key => $value) {
2166 $locField = explode('_', $key);
2167 $fieldName = $locField[2];
2168 $fieldCount = $locField[3];
2170 // Set up the operation type (add/overwrite)
2171 // Ignore operation for websites
2172 // @todo Tidy this up
2174 if ($fieldName != 'website') {
2175 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
2177 // default operation is overwrite.
2181 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
2183 $blocksDAO = array();
2185 // @todo Handle OpenID (not currently in API).
2186 if (!empty($locBlocks)) {
2187 $locationBlocks = self
::getLocationBlockInfo();
2189 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
2190 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
2192 foreach ($locBlocks as $name => $block) {
2193 $blocksDAO[$name] = array('delete' => array(), 'update' => array());
2194 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
2197 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
2198 $changePrimary = FALSE;
2199 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
2200 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
2202 foreach ($block as $blkCount => $values) {
2203 $otherBlockId = CRM_Utils_Array
::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
2204 $mainBlockId = CRM_Utils_Array
::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
2205 if (!$otherBlockId) {
2209 // For the block which belongs to other-contact, link the location block to main-contact
2210 $otherBlockDAO = new $daoName();
2211 $otherBlockDAO->contact_id
= $mainId;
2213 // Get the ID of this block on the 'other' contact, otherwise skip
2214 $otherBlockDAO->id
= $otherBlockId;
2216 // Add/update location and type information from the form, if applicable
2217 if ($locationBlocks[$name]['hasLocation']) {
2218 $locTypeId = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2219 $otherBlockDAO->location_type_id
= $locTypeId;
2221 if ($locationBlocks[$name]['hasType']) {
2222 $typeTypeId = CRM_Utils_Array
::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2223 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
2226 // If we're deliberately setting this as primary then add the flag
2227 // and remove it from the current primary location (if there is one).
2228 // But only once for each entity.
2229 $set_primary = CRM_Utils_Array
::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
2230 if (!$changePrimary && $set_primary == "1") {
2231 $otherBlockDAO->is_primary
= 1;
2232 if ($primaryDAOId) {
2233 $removePrimaryDAO = new $daoName();
2234 $removePrimaryDAO->id
= $primaryDAOId;
2235 $removePrimaryDAO->is_primary
= 0;
2236 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
2238 $changePrimary = TRUE;
2240 // Otherwise, if main contact already has primary, set it to 0.
2241 elseif ($primaryDAOId) {
2242 $otherBlockDAO->is_primary
= 0;
2245 // If the main contact already has a billing location, set this to 0.
2246 if ($billingDAOId) {
2247 $otherBlockDAO->is_billing
= 0;
2250 $operation = CRM_Utils_Array
::value('operation', $values, 2);
2251 // overwrite - need to delete block which belongs to main-contact.
2252 if (!empty($mainBlockId) && ($operation == 2)) {
2253 $deleteDAO = new $daoName();
2254 $deleteDAO->id
= $mainBlockId;
2255 $deleteDAO->find(TRUE);
2257 // if we about to delete a primary / billing block, set the flags for new block
2258 // that we going to assign to main-contact
2259 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
2260 $otherBlockDAO->is_primary
= 1;
2262 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
2263 $otherBlockDAO->is_billing
= 1;
2265 $blocksDAO[$name]['delete'][$deleteDAO->id
] = $deleteDAO;
2267 $blocksDAO[$name]['update'][$otherBlockDAO->id
] = $otherBlockDAO;
2272 CRM_Utils_Hook
::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2273 foreach ($blocksDAO as $blockDAOs) {
2274 if (!empty($blockDAOs['update'])) {
2275 foreach ($blockDAOs['update'] as $blockDAO) {
2279 if (!empty($blockDAOs['delete'])) {
2280 foreach ($blockDAOs['delete'] as $blockDAO) {
2281 $blockDAO->delete();
2288 * Dedupe a pair of contacts.
2290 * @param array $migrationInfo
2291 * @param array $resultStats
2292 * @param array $deletedContacts
2293 * @param string $mode
2294 * @param bool $checkPermissions
2295 * @param int $mainId
2296 * @param int $otherId
2297 * @param string $cacheKeyString
2299 protected static function dedupePair(&$migrationInfo, &$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) {
2301 // go ahead with merge if there is no conflict
2302 $conflicts = array();
2303 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2304 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2305 $resultStats['merged'][] = array(
2306 'main_id' => $mainId,
2307 'other_id' => $otherId,
2309 $deletedContacts[] = $otherId;
2312 $resultStats['skipped'][] = array(
2313 'main_id' => $mainId,
2314 'other_id' => $otherId,
2318 // store any conflicts
2319 if (!empty($conflicts)) {
2320 foreach ($conflicts as $key => $dnc) {
2321 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
2323 CRM_Core_BAO_PrevNextCache
::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
2326 // delete entry from PrevNextCache table so we don't consider the pair next time
2327 // pair may have been flipped, so make sure we delete using both orders
2328 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString, TRUE);