3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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() {
44 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
45 // if the url can't be retrieved. A more standardised way to retrieve them is.
46 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
47 // we may need a different function when it is not known.
48 $title = $userRecordUrl = '';
50 $config = CRM_Core_Config
::singleton();
51 if ($config->userSystem
->is_drupal
) {
52 $userRecordUrl = CRM_Utils_System
::url('user/%ufid');
53 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
55 elseif ($config->userFramework
== 'Joomla') {
56 $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';
57 $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);
163 * Returns the related tables groups for which a contact has any info entered.
169 public static function getActiveRelTables($cid) {
173 $relTables = self
::relTables();
174 $cidRefs = self
::cidRefs();
175 $eidRefs = self
::eidRefs();
176 foreach ($relTables as $group => $params) {
178 foreach ($params['tables'] as $table) {
179 if (isset($cidRefs[$table])) {
180 foreach ($cidRefs[$table] as $field) {
181 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
184 if (isset($eidRefs[$table])) {
185 foreach ($eidRefs[$table] as $entityTable => $entityId) {
186 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
189 foreach ($sqls as $sql) {
190 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
196 return array_unique($groups);
200 * Get array tables and fields that reference civicrm_contact.id.
202 * This includes core tables, custom group tables, tables added by the merge
203 * hook and (somewhat randomly) the entity_tag table.
205 * Refer to CRM-17454 for information on the danger of querying the information
206 * schema to derive this.
208 * @todo create an 'entity hook' to allow entities to be registered to CiviCRM
209 * including all info that is normally in the DAO.
211 public static function cidRefs() {
213 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
214 foreach ($coreReferences as $coreReference) {
215 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
216 $cidRefs[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
219 self
::addCustomTablesExtendingContactsToCidRefs($cidRefs);
221 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
222 $cidRefs['civicrm_entity_tag'][] = 'entity_id';
224 // Allow hook_civicrm_merge() to adjust $cidRefs.
225 // @todo consider adding a way to register entities and have them
226 // automatically added to this list.
227 CRM_Utils_Hook
::merge('cidRefs', $cidRefs);
232 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
234 public static function eidRefs() {
237 // FIXME: this should be generated dynamically from the schema
238 // tables that reference contacts with entity_{id,table}
240 'civicrm_acl' => array('entity_table' => 'entity_id'),
241 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
242 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
243 'civicrm_log' => array('entity_table' => 'entity_id'),
244 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
245 'civicrm_note' => array('entity_table' => 'entity_id'),
248 // Allow hook_civicrm_merge() to adjust $eidRefs
249 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
255 * Return tables using locations.
257 public static function locTables() {
260 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
262 // Allow hook_civicrm_merge() to adjust $locTables
263 CRM_Utils_Hook
::merge('locTables', $locTables);
269 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
270 * @param string $request
271 * 'relTables' or 'cidRefs'.
274 public static function getMultiValueCustomSets($request) {
276 if ($data === NULL) {
278 'relTables' => array(),
279 'cidRefs' => array(),
281 $result = civicrm_api3('custom_group', 'get', array(
283 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
284 'return' => array('id', 'title', 'table_name', 'style'),
286 foreach ($result['values'] as $custom) {
287 $data['cidRefs'][$custom['table_name']] = array('entity_id');
288 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
289 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
290 'title' => $custom['title'],
291 'tables' => array($custom['table_name']),
292 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
296 return $data[$request];
300 * Tables which require custom processing should declare functions to call here.
301 * Doing so will override normal processing.
303 public static function cpTables() {
307 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
308 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
309 // Empty array == do nothing - this table is handled by mergeGroupContact
310 'civicrm_subscription_history' => array(),
311 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
318 * Return payment related table.
320 public static function paymentTables() {
323 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
329 * Return payment update Query.
331 * @param string $tableName
332 * @param int $mainContactId
333 * @param int $otherContactId
337 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
339 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
343 $paymentTables = self
::paymentTables();
344 if (!in_array($tableName, $paymentTables)) {
348 switch ($tableName) {
349 case 'civicrm_pledge':
351 UPDATE IGNORE civicrm_contribution contribution
352 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
353 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
354 SET contribution.contact_id = $mainContactId
355 WHERE pledge.contact_id = $otherContactId";
358 case 'civicrm_membership':
360 UPDATE IGNORE civicrm_contribution contribution
361 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
362 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
363 SET contribution.contact_id = $mainContactId
364 WHERE membership.contact_id = $otherContactId";
367 case 'civicrm_participant':
369 UPDATE IGNORE civicrm_contribution contribution
370 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
371 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
372 SET contribution.contact_id = $mainContactId
373 WHERE participant.contact_id = $otherContactId";
382 * @param int $otherId
383 * @param string $tableName
384 * @param array $tableOperations
385 * @param string $mode
389 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
391 if (!$tableName ||
!$mainId ||
!$otherId) {
395 switch ($tableName) {
396 case 'civicrm_membership':
397 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
400 if ($mode == 'add') {
402 DELETE membership1.* FROM civicrm_membership membership1
403 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
404 AND membership1.contact_id = {$mainId}
405 AND membership2.contact_id = {$otherId} ";
407 if ($mode == 'payment') {
409 DELETE contribution.* FROM civicrm_contribution contribution
410 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
411 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
412 AND membership1.contact_id = {$mainId}
413 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
414 AND membership2.contact_id = {$otherId}";
418 case 'civicrm_uf_match':
419 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
420 // failing to meet intended result. Therefore we introduce this additional query:
421 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
429 * Based on the provided two contact_ids and a set of tables, move the
430 * belongings of the other contact to the main one.
433 * @param int $otherId
434 * @param bool $tables
435 * @param array $tableOperations
437 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
438 $cidRefs = self
::cidRefs();
439 $eidRefs = self
::eidRefs();
440 $cpTables = self
::cpTables();
441 $paymentTables = self
::paymentTables();
443 $membershipMerge = FALSE;
445 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
446 if ($tables !== FALSE) {
447 // if there are specific tables, sanitize the list
448 $affected = array_unique(array_intersect($affected, $tables));
451 // if there aren't any specific tables, don't affect the ones handled by relTables()
452 // also don't affect tables in locTables() CRM-15658
453 $relTables = self
::relTables();
454 $handled = self
::locTables();
455 foreach ($relTables as $params) {
456 $handled = array_merge($handled, $params['tables']);
458 $affected = array_diff($affected, $handled);
461 * Set $membershipMerge flag only once
462 * while doing contact related migration
463 * to call addMembershipToRealtedContacts()
464 * function only once.
465 * Since the current function (moveContactBelongings) is called twice
466 * with & without parameters $tables & $tableOperations
468 // retrieve main contact's related table(s)
469 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
470 // check if membership table exists in main contact's related table(s)
471 // set membership flag - CRM-12695
472 if (in_array('rel_table_memberships', $activeMainRelTables)) {
473 $membershipMerge = TRUE;
477 $mainId = (int) $mainId;
478 $otherId = (int) $otherId;
481 foreach ($affected as $table) {
482 // Call custom processing function for objects that require it
483 if (isset($cpTables[$table])) {
484 foreach ($cpTables[$table] as $className => $fnName) {
485 $className::$fnName($mainId, $otherId, $sqls);
487 // Skip normal processing
491 // use UPDATE IGNORE + DELETE query pair to skip on situations when
492 // there's a UNIQUE restriction on ($field, some_other_field) pair
493 if (isset($cidRefs[$table])) {
494 foreach ($cidRefs[$table] as $field) {
495 // carry related contributions CRM-5359
496 if (in_array($table, $paymentTables)) {
497 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
498 $sqls = array_merge($sqls, $paymentSqls);
500 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
501 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
502 $sqls = array_merge($sqls, $payOprSqls);
506 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
507 $sqls = array_merge($sqls, $preOperationSqls);
509 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
510 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
513 if (isset($eidRefs[$table])) {
514 foreach ($eidRefs[$table] as $entityTable => $entityId) {
515 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
516 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
521 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
522 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
524 // call the SQL queries in one transaction
525 $transaction = new CRM_Core_Transaction();
526 foreach ($sqls as $sql) {
527 CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, TRUE);
530 if ($membershipMerge) {
531 // call to function adding membership to related contacts
532 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
534 $transaction->commit();
538 * Load all non-empty fields for the contacts
542 * @param array $other
547 public static function retrieveFields($main, $other) {
549 'contact' => array(),
552 foreach (self
::getContactFields() as $validField) {
553 // CRM-17556 Get all non-empty fields, to make comparison easier
554 if (!empty($main[$validField]) ||
!empty($other[$validField])) {
555 $result['contact'][] = $validField;
559 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
560 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
561 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
562 foreach ($keys as $key) {
563 // Exclude multi-value fields CRM-13836
564 if (strpos($key, '_')) {
567 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
568 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
569 // CRM-17556 Get all non-empty fields, to make comparison easier
570 if (!empty($key1) ||
!empty($key2)) {
571 $result['custom'][] = $key;
578 * Batch merge a set of contacts based on rule-group and group.
584 * @param string $mode
585 * Helps decide how to behave when there are conflicts.
586 * A 'safe' value skips the merge if there are any un-resolved conflicts.
587 * Does a force merge otherwise.
588 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
589 * Whether to let api decide which contact to retain and which to delete.
590 * @param int $batchLimit number of merges to carry out in one batch.
591 * @param int $isSelected if records with is_selected column needs to be processed.
595 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $batchLimit = 1, $isSelected = 2) {
596 $redirectForPerformance = ($batchLimit > 1) ?
TRUE : FALSE;
597 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
598 $dupePairs = self
::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected);
600 $cacheParams = array(
601 'cache_key_string' => self
::getMergeCacheKeyString($rgid, $gid),
602 // @todo stop passing these parameters in & instead calculate them in the merge function based
603 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
604 'join' => self
::getJoinOnDedupeTable(),
605 'where' => self
::getWhereString($batchLimit, $isSelected),
607 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
611 * Get the string to join the prevnext cache to the dedupe table.
614 * The join string to join prevnext cache on the dedupe table.
616 public static function getJoinOnDedupeTable() {
618 LEFT JOIN civicrm_dedupe_exception de
620 pn.entity_id1 = de.contact_id1
621 AND pn.entity_id2 = de.contact_id2 )
626 * Get where string for dedupe join.
628 * @param int $batchLimit
629 * @param bool $isSelected
633 protected static function getWhereString($batchLimit, $isSelected) {
634 $where = "de.id IS NULL";
635 if ($isSelected === 0 ||
$isSelected === 1) {
636 $where .= " AND pn.is_selected = {$isSelected}";
638 // else consider all dupe pairs
639 // @todo Adding limit to Where??!!
640 $where .= " LIMIT {$batchLimit}";
644 public static function updateMergeStats($cacheKeyString, $result = array()) {
645 // gather latest stats
646 $merged = count($result['merged']);
647 $skipped = count($result['skipped']);
649 if ($merged <= 0 && $skipped <= 0) {
653 // get previous stats
654 $previousStats = CRM_Core_BAO_PrevNextCache
::retrieve("{$cacheKeyString}_stats");
655 if (!empty($previousStats)) {
656 if ($previousStats[0]['merged']) {
657 $merged = $merged +
$previousStats[0]['merged'];
659 if ($previousStats[0]['skipped']) {
660 $skipped = $skipped +
$previousStats[0]['skipped'];
665 CRM_Dedupe_Merger
::resetMergeStats($cacheKeyString);
667 // store the updated stats
670 'skipped' => $skipped,
672 $data = CRM_Core_DAO
::escapeString(serialize($data));
675 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
676 CRM_Core_BAO_PrevNextCache
::setItem($values);
679 public static function resetMergeStats($cacheKeyString) {
680 return CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, "{$cacheKeyString}_stats");
683 public static function getMergeStats($cacheKeyString) {
684 $stats = CRM_Core_BAO_PrevNextCache
::retrieve("{$cacheKeyString}_stats");
685 if (!empty($stats)) {
691 public static function getMergeStatsMsg($cacheKeyString) {
693 $stats = CRM_Dedupe_Merger
::getMergeStats($cacheKeyString);
694 if (!empty($stats['merged'])) {
695 $msg = "{$stats['merged']} " . ts('Contact(s) were merged.');
697 if (!empty($stats['skipped'])) {
698 $msg .= $stats['skipped'] . ts('Contact(s) were skipped.');
704 * Merge given set of contacts. Performs core operation.
706 * @param array $dupePairs
707 * Set of pair of contacts for whom merge is to be done.
708 * @param array $cacheParams
709 * Prev-next-cache params based on which next pair of contacts are computed.
710 * Generally used with batch-merge.
711 * @param string $mode
712 * Helps decide how to behave when there are conflicts.
713 * A 'safe' value skips the merge if there are any un-resolved conflicts.
714 * Does a force merge otherwise (aggressive mode).
715 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
716 * Wether to let api decide which contact to retain and which to delete.
719 * @param bool $redirectForPerformance
723 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
724 $autoFlip = TRUE, $redirectForPerformance = FALSE
726 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
727 $resultStats = array('merged' => array(), 'skipped' => array());
729 // we don't want dupe caching to get reset after every-merge, and therefore set the
730 // doNotResetCache flag
731 $config = CRM_Core_Config
::singleton();
732 $config->doNotResetCache
= 1;
734 while (!empty($dupePairs)) {
735 foreach ($dupePairs as $dupes) {
736 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
737 $mainId = $dupes['dstID'];
738 $otherId = $dupes['srcID'];
739 $isAutoFlip = CRM_Utils_Array
::value('auto_flip', $dupes, $autoFlip);
740 // if we can, make sure that $mainId is the one with lower id number
741 if ($isAutoFlip && ($mainId > $otherId)) {
742 $mainId = $dupes['srcID'];
743 $otherId = $dupes['dstID'];
745 if (!$mainId ||
!$otherId) {
750 // Generate var $migrationInfo. The variable structure is exactly same as
751 // $formValues submitted during a UI merge for a pair of contacts.
752 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId);
754 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
756 // add additional details that we might need to resolve conflicts
757 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
758 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
759 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
761 // go ahead with merge if there is no conflict
762 $conflicts = array();
763 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
764 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo);
765 $resultStats['merged'][] = array('main_id' => $mainId, 'other_id' => $otherId);
768 $resultStats['skipped'][] = array('main_id' => $mainId, 'other_id' => $otherId);
771 // store any conflicts
772 if (!empty($conflicts)) {
773 foreach ($conflicts as $key => $dnc) {
774 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
776 CRM_Core_BAO_PrevNextCache
::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
779 // delete entry from PrevNextCache table so we don't consider the pair next time
780 // pair may have been flipped, so make sure we delete using both orders
781 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
784 CRM_Core_DAO
::freeResult();
785 unset($rowsElementsAndInfo, $migrationInfo);
788 if ($cacheKeyString && !$redirectForPerformance) {
789 // retrieve next pair of dupes
790 // @todo call getDuplicatePairs.
791 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
792 $cacheParams['join'],
793 $cacheParams['where']
797 // do not proceed. Terminate the loop
802 CRM_Dedupe_Merger
::updateMergeStats($cacheKeyString, $resultStats);
807 * A function which uses various rules / algorithms for choosing which contact to bias to
808 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
811 * Main contact with whom merge has to happen.
812 * @param int $otherId
813 * Duplicate contact which would be deleted after merge operation.
814 * @param array $migrationInfo
815 * Array of information about which elements to merge.
816 * @param string $mode
817 * Helps decide how to behave when there are conflicts.
818 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
819 * - Does a force merge otherwise (aggressive mode).
821 * @param array $conflicts
825 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
827 $migrationData = array(
828 'old_migration_info' => $migrationInfo,
832 foreach ($migrationInfo as $key => $val) {
833 if ($val === "null") {
834 // Rule: Never overwrite with an empty value (in any mode)
835 unset($migrationInfo[$key]);
838 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
839 substr($key, 0, 12) == 'move_custom_'
842 // Rule: If both main-contact, and other-contact have a field with a
843 // different value, then let $mode decide if to merge it or not
845 !empty($migrationInfo['rows'][$key]['main'])
846 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
849 // note it down & lets wait for response from the hook.
850 // For no response $mode will decide if to skip this merge
851 $conflicts[$key] = NULL;
854 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
855 $locField = explode('_', $key);
856 $fieldName = $locField[2];
857 $fieldCount = $locField[3];
859 // Rule: Catch address conflicts (same address type on both contacts)
860 if ($fieldName == 'address') {
861 $mainNewLocTypeId = $migrationInfo['location_blocks'][$fieldName][$fieldCount]['locTypeId'];
863 isset($migrationInfo['main_details']['location_blocks']['address']) &&
864 !empty($migrationInfo['main_details']['location_blocks']['address'])
866 // Look for this LocTypeId in the results
867 // @todo This can be streamlined using array_column() in PHP 5.5+
868 foreach ($migrationInfo['main_details']['location_blocks']['address'] as $addressKey => $addressRecord) {
869 if ($addressRecord['location_type_id'] == $mainNewLocTypeId) {
870 $conflicts[$key] = NULL;
877 // For other locations, don't merge/add if the values are the same
878 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
879 unset($migrationInfo[$key]);
884 // A hook to implement other algorithms for choosing which contact to bias to when
885 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
886 // merge happens with new values filled in here. For a particular field / row not to be merged
887 // field should be unset from fields_in_conflict.
888 $migrationData['fields_in_conflict'] = $conflicts;
889 $migrationData['merge_mode'] = $mode;
890 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
891 $conflicts = $migrationData['fields_in_conflict'];
892 // allow hook to override / manipulate migrationInfo as well
893 $migrationInfo = $migrationData['old_migration_info'];
895 if (!empty($conflicts)) {
896 foreach ($conflicts as $key => $val) {
897 if ($val === NULL and $mode == 'safe') {
898 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
902 // copy over the resolved values
903 $migrationInfo[$key] = $val;
906 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
907 if (array_key_exists('skip_merge', $migrationData)) {
908 return (bool) $migrationData['skip_merge'];
915 * A function to build an array of information about location blocks that is
916 * required when merging location fields
920 public static function getLocationBlockInfo() {
921 $locationBlocks = array(
923 'label' => 'Address',
924 'displayField' => 'display',
925 'sortString' => 'location_type_id',
926 'hasLocation' => TRUE,
931 'displayField' => 'email',
932 'sortString' => 'location_type_id',
933 'hasLocation' => TRUE,
938 'displayField' => 'name',
939 'sortString' => 'location_type_id,provider_id',
940 'hasLocation' => TRUE,
941 'hasType' => 'provider_id',
945 'displayField' => 'phone',
946 'sortString' => 'location_type_id,phone_type_id',
947 'hasLocation' => TRUE,
948 'hasType' => 'phone_type_id',
951 'label' => 'Website',
952 'displayField' => 'url',
953 'sortString' => 'website_type_id',
954 'hasLocation' => FALSE,
955 'hasType' => 'website_type_id',
958 return $locationBlocks;
962 * A function to build an array of information required by merge function and the merge UI.
965 * Main contact with whom merge has to happen.
966 * @param int $otherId
967 * Duplicate contact which would be deleted after merge operation.
969 * @return array|bool|int
971 * rows => An array of arrays, each is row of merge information for the table
972 * Format: move_fieldname, eg: move_contact_type
973 * main => Value associated with the main contact
974 * other => Value associated with the other contact
975 * title => The title of the field to display in the merge table
977 * elements => An array of form elements for the merge UI
979 * rel_table_elements => An array of form elements for the merge UI for
980 * entities related to the contact (eg: checkbox to move 'mailings')
982 * rel_tables => Stores the tables that have related entities for the contact
983 * for example mailings, groups
985 * main_details => An array of core contact field values, eg: first_name, etc.
986 * location_blocks => An array of location block data for the main contact
987 * stored as the 'result' of an API call.
988 * eg: main_details['location_blocks']['address'][0]['id']
989 * eg: main_details['location_blocks']['email'][1]['id']
991 * other_details => As above, but for the 'other' contact
993 * migration_info => Stores the 'default' merge actions for each field which
994 * is used when programatically merging contacts. It contains instructions
995 * to move all fields from the 'other' contact to the 'main' contact, as
996 * though the form had been submitted with those options.
999 public static function getRowsElementsAndInfo($mainId, $otherId) {
1000 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1003 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
1005 'contact_id' => $cid,
1007 'return' => array_merge(array('display_name'), self
::getContactFields()),
1009 $result = civicrm_api('contact', 'get', $params);
1011 if (empty($result['values'][$cid]['contact_type'])) {
1015 // CRM-18480: Cancel the process if the contact is already deleted
1016 if (isset($result['values'][$cid]['contact_is_deleted']) && !empty($result['values'][$cid]['contact_is_deleted'])) {
1017 CRM_Core_Error
::fatal(ts('Cannot merge because the \'%1\' contact (ID %2) has been deleted.', array(1 => $moniker, 2 => $cid)));
1020 $
$moniker = $result['values'][$cid];
1023 $fields = CRM_Contact_DAO_Contact
::fields();
1025 // FIXME: there must be a better way
1026 foreach (array('main', 'other') as $moniker) {
1027 $contact = &$
$moniker;
1028 $preferred_communication_method = CRM_Utils_array
::value('preferred_communication_method', $contact);
1029 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
1030 $specialValues[$moniker] = array(
1031 'preferred_communication_method' => $value,
1032 'communication_style_id' => $value,
1035 if (!empty($contact['preferred_communication_method'])) {
1036 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
1037 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
1038 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
1041 'preferred_communication_method' => array(
1042 'newName' => 'preferred_communication_method_display',
1043 'groupName' => 'preferred_communication_method',
1046 CRM_Core_OptionGroup
::lookupValues($specialValues[$moniker], $names);
1048 if (!empty($contact['communication_style'])) {
1049 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
1053 static $optionValueFields = array();
1054 if (empty($optionValueFields)) {
1055 $optionValueFields = CRM_Core_OptionValue
::getFields();
1057 foreach ($optionValueFields as $field => $params) {
1058 $fields[$field]['title'] = $params['title'];
1061 $compareFields = self
::retrieveFields($main, $other);
1063 $rows = $elements = $relTableElements = $migrationInfo = array();
1065 foreach ($compareFields['contact'] as $field) {
1066 if ($field == 'contact_sub_type') {
1067 // CRM-15681 don't display sub-types in UI
1070 foreach (array('main', 'other') as $moniker) {
1071 $contact = &$
$moniker;
1072 $value = CRM_Utils_Array
::value($field, $contact);
1073 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
1074 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1076 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
1077 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
1079 $value = str_replace('-', '', $value);
1080 $label = CRM_Utils_Date
::customFormat($label);
1086 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
1087 if ($label === '0') {
1090 if ($label === '1') {
1094 elseif ($field == 'individual_prefix' ||
$field == 'prefix_id') {
1095 $label = CRM_Utils_Array
::value('individual_prefix', $contact);
1096 $value = CRM_Utils_Array
::value('prefix_id', $contact);
1097 $field = 'prefix_id';
1099 elseif ($field == 'individual_suffix' ||
$field == 'suffix_id') {
1100 $label = CRM_Utils_Array
::value('individual_suffix', $contact);
1101 $value = CRM_Utils_Array
::value('suffix_id', $contact);
1102 $field = 'suffix_id';
1104 elseif ($field == 'gender_id' && !empty($value)) {
1105 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
1106 $label = $genderOptions['values'][$value];
1108 elseif ($field == 'current_employer_id' && !empty($value)) {
1109 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
1111 $rows["move_$field"][$moniker] = $label;
1112 if ($moniker == 'other') {
1114 if ($value === NULL ||
$value == '') {
1117 if ($value === 0 or $value === '0') {
1118 $value = $qfZeroBug;
1120 if (is_array($value) && empty($value[1])) {
1124 // Display a checkbox to migrate, only if the values are different
1125 if ($value != $main[$field]) {
1126 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1129 $migrationInfo["move_$field"] = $value;
1132 $rows["move_$field"]['title'] = $fields[$field]['title'];
1135 // Handle location blocks.
1136 // @todo OpenID not in API yet, so is not supported here.
1138 // Set up useful information about the location blocks
1139 $locationBlocks = self
::getLocationBlockInfo();
1146 // @todo This could probably be defined and used earlier
1147 $mergeTargets = array(
1149 'other' => $otherId,
1152 foreach ($locationBlocks as $blockName => $blockInfo) {
1154 // Collect existing fields from both 'main' and 'other' contacts first
1155 // This allows us to match up location/types when building the table rows
1156 foreach ($mergeTargets as $moniker => $cid) {
1158 $searchParams = array(
1160 'contact_id' => $cid,
1161 // CRM-17556 Order by field-specific criteria
1163 'sort' => $blockInfo['sortString'],
1166 $values = civicrm_api($blockName, 'get', $searchParams);
1167 if ($values['count']) {
1169 foreach ($values['values'] as $index => $value) {
1170 $locations[$moniker][$blockName][$cnt] = $value;
1171 // Fix address display
1173 if ($blockName == 'address') {
1174 CRM_Core_BAO_Address
::fixAddress($value);
1175 $display = CRM_Utils_Address
::format($value);
1176 $locations[$moniker][$blockName][$cnt]['display'] = $display;
1184 // Now, build the table rows appropriately, based off the information on
1185 // the 'other' contact
1186 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1187 foreach ($locations['other'][$blockName] as $count => $value) {
1189 $displayValue = $value[$blockInfo['displayField']];
1191 // Add this value to the table rows
1192 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1194 // CRM-17556 Only display 'main' contact value if it's the same location + type
1195 // Look it up from main values...
1197 $lookupLocation = FALSE;
1198 if ($blockInfo['hasLocation']) {
1199 $lookupLocation = $value['location_type_id'];
1202 $lookupType = FALSE;
1203 if ($blockInfo['hasType']) {
1204 $lookupType = $value[$blockInfo['hasType']];
1207 // Hold ID of main contact's matching block
1208 $mainContactBlockId = 0;
1210 if (!empty($locations['main'][$blockName])) {
1211 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1212 // No location/type, or matching location and type
1214 (empty($lookupLocation) ||
$lookupLocation == $mainValueCheck['location_type_id'])
1215 && (empty($lookupType) ||
$lookupType == $mainValueCheck[$blockInfo['hasType']])
1217 // Set this value as the default against the 'other' contact value
1218 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1219 $mainContactBlockId = $mainValueCheck['id'];
1225 // Add checkbox to migrate data from 'other' to 'main'
1226 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
1228 // Flag up this field to skipMerge function (@todo: do we need to?)
1229 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1231 // Add a hidden field to store the ID of the target main contact block
1232 $elements[] = array('hidden', "location_blocks[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
1235 $thisTypeId = FALSE;
1238 // Provide a select drop-down for the location's location type
1239 // eg: Home, Work...
1243 if ($blockInfo['hasLocation']) {
1245 // Load the location options for this entity
1246 $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
1248 // JS lookup 'main' contact's location (if there are any)
1249 if (!empty($locations['main'][$blockName])) {
1250 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'locTypeId' );");
1253 $thisLocId = $value['location_type_id'];
1255 // Put this field's location type at the top of the list
1256 $tmpIdList = $locationOptions['values'];
1257 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1258 unset($tmpIdList[$thisLocId]);
1261 $elements[] = array(
1263 "location_blocks[$blockName][$count][locTypeId]",
1265 $defaultLocId +
$tmpIdList,
1269 // Add the relevant information to the $migrationInfo
1270 // Keep location-type-id same as that of other-contact
1271 // @todo Check this logic out
1272 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1273 if ($blockName != 'address') {
1274 $elements[] = array('advcheckbox', "location_blocks[{$blockName}][$count][operation]", NULL, ts('add new'));
1275 // always use add operation
1276 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1281 // Provide a select drop-down for the location's type/provider
1282 // eg websites: Google+, Facebook...
1286 if ($blockInfo['hasType']) {
1288 // Load the type options for this entity
1289 $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
1291 // CRM-17556 Set up JS lookup of 'main' contact's value by type
1292 if (!empty($locations['main'][$blockName])) {
1293 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'typeTypeId' );");
1296 $thisTypeId = $value[$blockInfo['hasType']];
1298 // Put this field's location type at the top of the list
1299 $tmpIdList = $typeOptions['values'];
1300 $defaultTypeId = array($thisTypeId => $tmpIdList[$thisTypeId]);
1301 unset($tmpIdList[$thisTypeId]);
1304 $elements[] = array(
1306 "location_blocks[$blockName][$count][typeTypeId]",
1308 $defaultTypeId +
$tmpIdList,
1312 // Add the information to the migrationInfo
1313 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1317 // Set the label for this row
1318 $rowTitle = $blockInfo['label'] . ' ' . ($count +
1);
1319 if (!empty($thisLocId)) {
1320 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1322 if (!empty($thisTypeId)) {
1323 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1325 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1327 } // End loop through 'other' locations of this type
1329 } // End if 'other' location for this type exists
1331 } // End loop through each location block entity
1333 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1334 $config = CRM_Core_Config
::singleton();
1335 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1339 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1340 $mainUser = user_load($mainUfId);
1342 elseif ($config->userFramework
== 'Joomla') {
1343 $mainUser = JFactory
::getUser($mainUfId);
1346 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1350 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1351 $otherUser = user_load($otherUfId);
1353 elseif ($config->userFramework
== 'Joomla') {
1354 $otherUser = JFactory
::getUser($otherUfId);
1358 $relTables = CRM_Dedupe_Merger
::relTables();
1359 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1360 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1361 foreach ($relTables as $name => $null) {
1362 if (!in_array($name, $activeRelTables) &&
1363 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1365 unset($relTables[$name]);
1369 $relTableElements[] = array('checkbox', "move_$name");
1370 $migrationInfo["move_$name"] = 1;
1372 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1373 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1374 if ($name == 'rel_table_users') {
1375 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1376 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1377 $find = array('$ufid', '$ufname');
1379 $replace = array($mainUfId, $mainUser->name
);
1380 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1383 $replace = array($otherUfId, $otherUser->name
);
1384 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1387 if ($name == 'rel_table_memberships') {
1388 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1389 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1392 foreach ($relTables as $name => $null) {
1393 $relTables["move_$name"] = $relTables[$name];
1394 unset($relTables[$name]);
1397 // handle custom fields
1398 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $mainId, -1,
1399 CRM_Utils_Array
::value('contact_sub_type', $main)
1401 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $otherId, -1,
1402 CRM_Utils_Array
::value('contact_sub_type', $other)
1404 CRM_Core_DAO
::freeResult();
1406 foreach ($otherTree as $gid => $group) {
1407 $foundField = FALSE;
1408 if (!isset($group['fields'])) {
1412 foreach ($group['fields'] as $fid => $field) {
1413 if (in_array($fid, $compareFields['custom'])) {
1415 $rows["custom_group_$gid"]['title'] = $group['title'];
1418 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1419 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1420 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1424 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1425 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1426 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1427 if ($values['data'] === 0 ||
$values['data'] === '0') {
1428 $values['data'] = $qfZeroBug;
1430 $value = ($values['data']) ?
$values['data'] : $value;
1433 $rows["move_custom_$fid"]['title'] = $field['label'];
1435 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1436 $migrationInfo["move_custom_$fid"] = $value;
1443 'elements' => $elements,
1444 'rel_table_elements' => $relTableElements,
1445 'rel_tables' => $relTables,
1446 'main_details' => $main,
1447 'other_details' => $other,
1448 'migration_info' => $migrationInfo,
1451 $result['main_details']['location_blocks'] = $locations['main'];
1452 $result['other_details']['location_blocks'] = $locations['other'];
1458 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1459 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1460 * A superset of moveContactBelongings() function.
1462 * @param int $mainId
1463 * Main contact with whom merge has to happen.
1464 * @param int $otherId
1465 * Duplicate contact which would be deleted after merge operation.
1467 * @param $migrationInfo
1471 public static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1472 if (empty($migrationInfo)) {
1476 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1477 $relTables = CRM_Dedupe_Merger
::relTables();
1478 $moveTables = $locBlocks = $tableOperations = array();
1479 foreach ($migrationInfo as $key => $value) {
1480 if ($value == $qfZeroBug) {
1483 if ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) ||
1484 substr($key, 0, 12) == 'move_custom_') &&
1487 $submitted[substr($key, 5)] = $value;
1490 // Set up initial information for handling migration of location blocks
1491 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1492 $locField = explode('_', $key);
1493 $fieldName = $locField[2];
1494 $fieldCount = $locField[3];
1496 // Set up the operation type (add/overwrite)
1497 // Ignore operation for websites
1498 // @todo Tidy this up
1500 if ($fieldName != 'website') {
1501 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1503 // default operation is overwrite.
1507 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1511 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1512 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1513 if (array_key_exists('operation', $migrationInfo)) {
1514 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1515 if (array_key_exists($key, $migrationInfo['operation'])) {
1516 $tableOperations[$table] = $migrationInfo['operation'][$key];
1523 // **** Do location related migration.
1524 // @todo Handle OpenID (not currently in API).
1525 if (!empty($locBlocks)) {
1527 $locationBlocks = self
::getLocationBlockInfo();
1529 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
1530 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
1532 foreach ($locBlocks as $name => $block) {
1533 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1536 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
1537 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1538 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1540 foreach ($block as $blkCount => $values) {
1542 // For the block which belongs to other-contact, link the location block to main-contact
1543 $otherBlockDAO = new $daoName();
1544 $otherBlockDAO->contact_id
= $mainId;
1546 // Get the ID of this block on the 'other' contact, otherwise skip
1547 $otherBlockId = CRM_Utils_Array
::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
1548 if (!$otherBlockId) {
1551 $otherBlockDAO->id
= $otherBlockId;
1553 // Add/update location and type information from the form, if applicable
1554 if ($locationBlocks[$name]['hasLocation']) {
1555 $locTypeId = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1556 $otherBlockDAO->location_type_id
= $locTypeId;
1558 if ($locationBlocks[$name]['hasType']) {
1559 $typeTypeId = CRM_Utils_Array
::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1560 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
1563 // Get main block ID
1564 $mainBlockId = CRM_Utils_Array
::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1566 // if main contact already has primary & billing, set the flags to 0.
1567 if ($primaryDAOId) {
1568 $otherBlockDAO->is_primary
= 0;
1570 if ($billingDAOId) {
1571 $otherBlockDAO->is_billing
= 0;
1574 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1575 // overwrite - need to delete block which belongs to main-contact.
1576 if (!empty($mainBlockId) && ($operation == 2)) {
1577 $deleteDAO = new $daoName();
1578 $deleteDAO->id
= $mainBlockId;
1579 $deleteDAO->find(TRUE);
1581 // if we about to delete a primary / billing block, set the flags for new block
1582 // that we going to assign to main-contact
1583 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1584 $otherBlockDAO->is_primary
= 1;
1586 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1587 $otherBlockDAO->is_billing
= 1;
1590 $deleteDAO->delete();
1594 $otherBlockDAO->update();
1595 $otherBlockDAO->free();
1600 // **** Do tables related migrations
1601 if (!empty($moveTables)) {
1602 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1603 unset($moveTables, $tableOperations);
1606 // **** Do contact related migrations
1607 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId);
1609 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1610 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1611 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1612 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1613 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1614 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1615 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1616 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1617 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1619 // fix custom fields so they're edible by createProfileContact()
1620 static $treeCache = array();
1621 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1622 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree($migrationInfo['main_details']['contact_type'],
1623 CRM_Core_DAO
::$_nullObject, NULL, -1
1626 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1629 foreach ($cgTree as $key => $group) {
1630 if (!isset($group['fields'])) {
1633 foreach ($group['fields'] as $fid => $field) {
1634 $cFields[$fid]['attributes'] = $field;
1638 if (!isset($submitted)) {
1639 $submitted = array();
1641 foreach ($submitted as $key => $value) {
1642 if (substr($key, 0, 7) == 'custom_') {
1643 $fid = (int) substr($key, 7);
1644 if (empty($cFields[$fid])) {
1647 $htmlType = $cFields[$fid]['attributes']['html_type'];
1648 switch ($htmlType) {
1650 $customFiles[] = $fid;
1651 unset($submitted["custom_$fid"]);
1654 case 'Select Country':
1655 case 'Select State/Province':
1656 $submitted[$key] = CRM_Core_BAO_CustomField
::displayValue($value, $fid);
1660 case 'AdvMulti-Select':
1661 case 'Multi-Select':
1662 case 'Multi-Select Country':
1663 case 'Multi-Select State/Province':
1664 // Merge values from both contacts for multivalue fields, CRM-4385
1665 // get the existing custom values from db.
1666 $customParams = array('entityID' => $mainId, $key => TRUE);
1667 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1668 if (!empty($customfieldValues[$key])) {
1669 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1670 if (is_array($existingValue) && !empty($existingValue)) {
1671 $mergeValue = $submmtedCustomValue = array();
1673 $submmtedCustomValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1676 //hack to remove null and duplicate values from array.
1677 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1678 if ($v != '' && !in_array($v, $mergeValue)) {
1683 //keep state and country as array format.
1684 //for checkbox and m-select format w/ VALUE_SEPARATOR
1685 if (in_array($htmlType, array(
1690 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1692 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1695 $submitted[$key] = $mergeValue;
1699 elseif (in_array($htmlType, array(
1700 'Multi-Select Country',
1701 'Multi-Select State/Province',
1703 //we require submitted values should be in array format
1705 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1706 //hack to remove null values from array.
1707 $mergeValue = array();
1708 foreach ($mergeValueArray as $k => $v) {
1713 $submitted[$key] = $mergeValue;
1724 // **** Do file custom fields related migrations
1725 // FIXME: move this someplace else (one of the BAOs) after discussing
1726 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1727 // like, delete a file...
1729 if (!isset($customFiles)) {
1730 $customFiles = array();
1732 foreach ($customFiles as $customId) {
1733 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1735 // get the contact_id -> file_id mapping
1737 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1738 $dao = CRM_Core_DAO
::executeQuery($sql);
1739 while ($dao->fetch()) {
1740 $fileIds[$dao->entity_id
] = $dao->file_id
;
1744 // delete the main contact's file
1745 if (!empty($fileIds[$mainId])) {
1746 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1749 // move the other contact's file to main contact
1750 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1751 if (CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
1752 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1755 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1757 CRM_Core_DAO
::executeQuery($sql);
1759 if (CRM_Core_DAO
::singleValueQuery("
1761 FROM civicrm_entity_file
1762 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1765 UPDATE civicrm_entity_file
1766 SET entity_id = {$mainId}
1767 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1771 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1772 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1774 CRM_Core_DAO
::executeQuery($sql);
1777 // move view only custom fields CRM-5362
1778 $viewOnlyCustomFields = array();
1779 foreach ($submitted as $key => $value) {
1780 $fid = (int) substr($key, 7);
1781 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1782 $viewOnlyCustomFields[$key] = $value;
1786 // special case to set values for view only, CRM-5362
1787 if (!empty($viewOnlyCustomFields)) {
1788 $viewOnlyCustomFields['entityID'] = $mainId;
1789 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1792 if (CRM_Core_Permission
::check('merge duplicate contacts') &&
1793 CRM_Core_Permission
::check('delete contacts')
1795 // if ext id is submitted then set it null for contact to be deleted
1796 if (!empty($submitted['external_identifier'])) {
1797 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1798 CRM_Core_DAO
::executeQuery($query);
1801 civicrm_api3('contact', 'delete', array('id' => $otherId));
1802 CRM_Core_BAO_PrevNextCache
::deleteItem($otherId);
1806 // CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') );
1809 // CRM-15681 merge sub_types
1810 if ($other_sub_types = CRM_Utils_array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1811 if ($main_sub_types = CRM_Utils_array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1812 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1815 $submitted['contact_sub_type'] = $other_sub_types;
1819 // **** Update contact related info for the main contact
1820 if (!empty($submitted)) {
1821 $submitted['contact_id'] = $mainId;
1823 //update current employer field
1824 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1825 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1826 $submitted['current_employer'] = $submitted['current_employer_id'];
1829 $submitted['current_employer'] = '';
1831 unset($submitted['current_employer_id']);
1834 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1835 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1836 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1838 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1839 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1842 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);
1845 CRM_Utils_Hook
::post('merge', 'Contact', $mainId, CRM_Core_DAO
::$_nullObject);
1846 self
::createMergeActivities($mainId, $otherId);
1852 * Get fields in the contact table suitable for merging.
1855 * Array of field names to be potentially merged.
1857 public static function getContactFields() {
1858 $contactFields = CRM_Contact_DAO_Contact
::fields();
1859 $invalidFields = array(
1866 'primary_contact_id',
1870 foreach ($contactFields as $field => $value) {
1871 if (in_array($field, $invalidFields)) {
1872 unset($contactFields[$field]);
1875 return array_keys($contactFields);
1879 * Added for CRM-12695
1880 * Based on the contactID provided
1881 * add/update membership(s) to related contacts
1883 * @param int $contactID
1885 public static function addMembershipToRealtedContacts($contactID) {
1886 $dao = new CRM_Member_DAO_Membership();
1887 $dao->contact_id
= $contactID;
1891 //checks membership of contact itself
1892 while ($dao->fetch()) {
1893 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1894 if ($relationshipTypeId) {
1895 $membershipParams = array(
1897 'contact_id' => $dao->contact_id
,
1898 'membership_type_id' => $dao->membership_type_id
,
1899 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1900 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1901 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1902 'source' => $dao->source
,
1903 'status_id' => $dao->status_id
,
1905 // create/update membership(s) for related contact(s)
1906 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1907 } // end of if relationshipTypeId
1912 * Add custom tables that extend contacts to the list of contact references.
1914 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
1915 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
1916 * - the down side is it is not cached.
1918 * Further changes should be include tests in the CRM_Core_MergerTest class
1919 * to ensure that disabled, subtype, multiple etc groups are still captured.
1921 * @param array $cidRefs
1923 public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
1924 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
1925 $customValueTables->find();
1926 while ($customValueTables->fetch()) {
1927 $cidRefs[$customValueTables->table_name
] = array('entity_id');
1932 * Create activities tracking the merge on affected contacts.
1934 * @param int $mainId
1935 * @param int $otherId
1937 * @throws \CiviCRM_API3_Exception
1939 public static function createMergeActivities($mainId, $otherId) {
1944 $activity = civicrm_api3('activity', 'create', array(
1945 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1947 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1948 'target_contact_id' => $mainId,
1949 'activity_type_id' => 'Contact Merged',
1950 'status_id' => 'Completed',
1952 if (civicrm_api3('Setting', 'getvalue', array('name' => 'contact_undelete', 'group' => 'CiviCRM Preferences'))) {
1953 civicrm_api3('activity', 'create', array(
1954 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1956 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1957 'target_contact_id' => $otherId,
1958 'activity_type_id' => 'Contact Deleted by Merge',
1959 'parent_id' => $activity['id'],
1960 'status_id' => 'Completed',
1966 * Get Duplicate Pairs based on a rule for a group.
1968 * @param int $rule_group_id
1969 * @param int $group_id
1970 * @param bool $reloadCacheIfEmpty
1971 * @param int $batchLimit
1972 * @param bool $isSelected
1975 * Array of matches meeting the criteria.
1977 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected) {
1978 $where = self
::getWhereString($batchLimit, $isSelected);
1979 $cacheKeyString = self
::getMergeCacheKeyString($rule_group_id, $group_id);
1980 $join = self
::getJoinOnDedupeTable();
1981 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
1982 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1983 // If we haven't found any dupes, probably cache is empty.
1984 // Try filling cache and give another try.
1985 CRM_Core_BAO_PrevNextCache
::refillCache($rule_group_id, $group_id, $cacheKeyString);
1986 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
1993 * Get the cache key string for the merge action.
1995 * @param int $rule_group_id
1996 * @param int $group_id
2000 public static function getMergeCacheKeyString($rule_group_id, $group_id) {
2001 $contactType = CRM_Dedupe_BAO_RuleGroup
::getContactTypeForRuleGroup($rule_group_id);
2002 $cacheKeyString = "merge {$contactType}";
2003 $cacheKeyString .= $rule_group_id ?
"_{$rule_group_id}" : '_0';
2004 $cacheKeyString .= $group_id ?
"_{$group_id}" : '_0';
2005 return $cacheKeyString;