3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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/mailing', 'reset=1&force=1&cid=$cid'),
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();
442 $membershipMerge = FALSE; // CRM-12695
444 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
445 if ($tables !== FALSE) {
446 // if there are specific tables, sanitize the list
447 $affected = array_unique(array_intersect($affected, $tables));
450 // if there aren't any specific tables, don't affect the ones handled by relTables()
451 // also don't affect tables in locTables() CRM-15658
452 $relTables = self
::relTables();
453 $handled = self
::locTables();
454 foreach ($relTables as $params) {
455 $handled = array_merge($handled, $params['tables']);
457 $affected = array_diff($affected, $handled);
460 * Set $membershipMerge flag only once
461 * while doing contact related migration
462 * to call addMembershipToRealtedContacts()
463 * function only once.
464 * Since the current function (moveContactBelongings) is called twice
465 * with & without parameters $tables & $tableOperations
467 // retrieve main contact's related table(s)
468 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
469 // check if membership table exists in main contact's related table(s)
470 if (in_array('rel_table_memberships', $activeMainRelTables)) {
471 $membershipMerge = TRUE; // set membership flag - CRM-12695
475 $mainId = (int) $mainId;
476 $otherId = (int) $otherId;
479 foreach ($affected as $table) {
480 // Call custom processing function for objects that require it
481 if (isset($cpTables[$table])) {
482 foreach ($cpTables[$table] as $className => $fnName) {
483 $className::$fnName($mainId, $otherId, $sqls);
485 // Skip normal processing
489 // use UPDATE IGNORE + DELETE query pair to skip on situations when
490 // there's a UNIQUE restriction on ($field, some_other_field) pair
491 if (isset($cidRefs[$table])) {
492 foreach ($cidRefs[$table] as $field) {
493 // carry related contributions CRM-5359
494 if (in_array($table, $paymentTables)) {
495 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
496 $sqls = array_merge($sqls, $paymentSqls);
498 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
499 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
500 $sqls = array_merge($sqls, $payOprSqls);
504 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
505 $sqls = array_merge($sqls, $preOperationSqls);
507 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
508 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
511 if (isset($eidRefs[$table])) {
512 foreach ($eidRefs[$table] as $entityTable => $entityId) {
513 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
514 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
519 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
520 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
522 // call the SQL queries in one transaction
523 $transaction = new CRM_Core_Transaction();
524 foreach ($sqls as $sql) {
525 CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, TRUE);
528 if ($membershipMerge) {
529 // call to function adding membership to related contacts
530 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
532 $transaction->commit();
536 * Load all non-empty fields for the contacts
540 * @param array $other
545 public static function retrieveFields($main, $other) {
547 'contact' => array(),
550 foreach (self
::getContactFields() as $validField) {
551 // CRM-17556 Get all non-empty fields, to make comparison easier
552 if (!empty($main[$validField]) ||
!empty($other[$validField])) {
553 $result['contact'][] = $validField;
557 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
558 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
559 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
560 foreach ($keys as $key) {
561 // Exclude multi-value fields CRM-13836
562 if (strpos($key, '_')) {
565 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
566 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
567 // CRM-17556 Get all non-empty fields, to make comparison easier
568 if (!empty($key1) ||
!empty($key2)) {
569 $result['custom'][] = $key;
576 * Batch merge a set of contacts based on rule-group and group.
582 * @param string $mode
583 * Helps decide how to behave when there are conflicts.
584 * A 'safe' value skips the merge if there are any un-resolved conflicts.
585 * Does a force merge otherwise.
586 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
587 * Wether to let api decide which contact to retain and which to delete.
588 * @param int $batchLimit number of merges to carry out in one batch.
589 * @param int $isSelected if records with is_selected column needs to be processed.
593 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $batchLimit = 1, $isSelected = 2) {
594 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
595 $cacheKeyString = "merge {$contactType}";
596 $cacheKeyString .= $rgid ?
"_{$rgid}" : '_0';
597 $cacheKeyString .= $gid ?
"_{$gid}" : '_0';
598 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
599 pn.entity_id2 = de.contact_id2 )";
601 $where = "de.id IS NULL";
602 if ($isSelected === 0 ||
$isSelected === 1) {
603 $where .= " AND pn.is_selected = {$isSelected}";
604 }// else consider all dupe pairs
605 $where .= " LIMIT {$batchLimit}";
607 $redirectForPerformance = ($batchLimit > 1) ?
TRUE : FALSE;
609 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
610 if (empty($dupePairs) && !$redirectForPerformance && $isSelected == 2) {
611 // If we haven't found any dupes, probably cache is empty.
612 // Try filling cache and give another try.
613 CRM_Core_BAO_PrevNextCache
::refillCache($rgid, $gid, $cacheKeyString);
614 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
617 $cacheParams = array(
618 'cache_key_string' => $cacheKeyString,
622 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
625 public static function updateMergeStats($cacheKeyString, $result = array()) {
626 // gather latest stats
627 $merged = count($result['merged']);
628 $skipped = count($result['skipped']);
630 if ($merged <= 0 && $skipped <= 0) {
634 // get previous stats
635 $previousStats = CRM_Core_BAO_PrevNextCache
::retrieve("{$cacheKeyString}_stats");
636 if (!empty($previousStats)) {
637 if ($previousStats[0]['merged']) {
638 $merged = $merged +
$previousStats[0]['merged'];
640 if ($previousStats[0]['skipped']) {
641 $skipped = $skipped +
$previousStats[0]['skipped'];
646 CRM_Dedupe_Merger
::resetMergeStats($cacheKeyString);
648 // store the updated stats
651 'skipped' => $skipped,
653 $data = CRM_Core_DAO
::escapeString(serialize($data));
656 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
657 CRM_Core_BAO_PrevNextCache
::setItem($values);
660 public static function resetMergeStats($cacheKeyString) {
661 return CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, "{$cacheKeyString}_stats");
664 public static function getMergeStats($cacheKeyString) {
665 $stats = CRM_Core_BAO_PrevNextCache
::retrieve("{$cacheKeyString}_stats");
666 if (!empty($stats)) {
672 public static function getMergeStatsMsg($cacheKeyString) {
674 $stats = CRM_Dedupe_Merger
::getMergeStats($cacheKeyString);
675 if (!empty($stats['merged'])) {
676 $msg = "{$stats['merged']} " . ts(' Contact(s) were merged. ');
678 if (!empty($stats['skipped'])) {
679 $msg .= $stats['skipped'] . ts(' Contact(s) were skipped.');
685 * Merge given set of contacts. Performs core operation.
687 * @param array $dupePairs
688 * Set of pair of contacts for whom merge is to be done.
689 * @param array $cacheParams
690 * Prev-next-cache params based on which next pair of contacts are computed.
691 * Generally used with batch-merge.
692 * @param string $mode
693 * Helps decide how to behave when there are conflicts.
694 * A 'safe' value skips the merge if there are any un-resolved conflicts.
695 * Does a force merge otherwise (aggressive mode).
696 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
697 * Wether to let api decide which contact to retain and which to delete.
700 * @param bool $redirectForPerformance
704 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
705 $autoFlip = TRUE, $redirectForPerformance = FALSE
707 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
708 $resultStats = array('merged' => array(), 'skipped' => array());
710 // we don't want dupe caching to get reset after every-merge, and therefore set the
711 // doNotResetCache flag
712 $config = CRM_Core_Config
::singleton();
713 $config->doNotResetCache
= 1;
715 while (!empty($dupePairs)) {
716 foreach ($dupePairs as $dupes) {
717 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
718 $mainId = $dupes['dstID'];
719 $otherId = $dupes['srcID'];
720 $isAutoFlip = CRM_Utils_Array
::value('auto_flip', $dupes, $autoFlip);
721 // if we can, make sure that $mainId is the one with lower id number
722 if ($isAutoFlip && ($mainId > $otherId)) {
723 $mainId = $dupes['srcID'];
724 $otherId = $dupes['dstID'];
726 if (!$mainId ||
!$otherId) {
731 // Generate var $migrationInfo. The variable structure is exactly same as
732 // $formValues submitted during a UI merge for a pair of contacts.
733 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId);
735 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
737 // add additional details that we might need to resolve conflicts
738 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
739 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
740 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
741 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
743 // go ahead with merge if there is no conflict
744 $conflicts = array();
745 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
746 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo);
747 $resultStats['merged'][] = array('main_id' => $mainId, 'other_id' => $otherId);
750 $resultStats['skipped'][] = array('main_id' => $mainId, 'other_id' => $otherId);
753 // store any conflicts
754 if (!empty($conflicts)) {
755 foreach ($conflicts as $key => $dnc) {
756 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
758 CRM_Core_BAO_PrevNextCache
::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
761 // delete entry from PrevNextCache table so we don't consider the pair next time
762 // pair may have been flipped, so make sure we delete using both orders
763 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
766 CRM_Core_DAO
::freeResult();
767 unset($rowsElementsAndInfo, $migrationInfo);
770 if ($cacheKeyString && !$redirectForPerformance) {
771 // retrieve next pair of dupes
772 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
773 $cacheParams['join'],
774 $cacheParams['where']
778 // do not proceed. Terminate the loop
783 CRM_Dedupe_Merger
::updateMergeStats($cacheKeyString, $resultStats);
788 * A function which uses various rules / algorithms for choosing which contact to bias to
789 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
792 * Main contact with whom merge has to happen.
793 * @param int $otherId
794 * Duplicate contact which would be deleted after merge operation.
795 * @param array $migrationInfo
796 * Array of information about which elements to merge.
797 * @param string $mode
798 * Helps decide how to behave when there are conflicts.
799 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
800 * - Does a force merge otherwise (aggressive mode).
802 * @param array $conflicts
806 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
808 $migrationData = array(
809 'old_migration_info' => $migrationInfo,
813 $allLocationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
815 foreach ($migrationInfo as $key => $val) {
816 if ($val === "null") {
817 // Rule: Never overwrite with an empty value (in any mode)
818 unset($migrationInfo[$key]);
821 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
822 substr($key, 0, 12) == 'move_custom_'
825 // Rule: If both main-contact, and other-contact have a field with a
826 // different value, then let $mode decide if to merge it or not
828 !empty($migrationInfo['rows'][$key]['main'])
829 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
832 // note it down & lets wait for response from the hook.
833 // For no response $mode will decide if to skip this merge
834 $conflicts[$key] = NULL;
837 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
838 $locField = explode('_', $key);
839 $fieldName = $locField[2];
840 $fieldCount = $locField[3];
842 // Rule: resolve address conflict if any
843 if ($fieldName == 'address') {
844 $mainNewLocTypeId = $migrationInfo['location_blocks'][$fieldName][$fieldCount]['locTypeId'];
845 if (!empty($migrationInfo['main_loc_block']) &&
846 array_key_exists("main_address_{$mainNewLocTypeId}", $migrationInfo['main_loc_block'])) {
847 // main loc already has some address for the loc-type. Its a overwrite situation.
848 // look for next available loc-type
850 foreach ($allLocationTypes as $typeId => $typeLabel) {
851 if (!array_key_exists("main_address_{$typeId}", $migrationInfo['main_loc_block'])) {
852 $newTypeId = $typeId;
856 // try insert address at new available loc-type
857 $migrationInfo['location_blocks'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
860 // note it down & lets wait for response from the hook.
861 // For no response $mode will decide if to skip this merge
862 $conflicts[$key] = NULL;
866 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
867 // for loc blocks other than address like email, phone .. if values are same no point in merging
868 // and adding redundant value
869 unset($migrationInfo[$key]);
874 // A hook to implement other algorithms for choosing which contact to bias to when
875 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
876 // merge happens with new values filled in here. For a particular field / row not to be merged
877 // field should be unset from fields_in_conflict.
878 $migrationData['fields_in_conflict'] = $conflicts;
879 $migrationData['merge_mode'] = $mode;
880 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
881 $conflicts = $migrationData['fields_in_conflict'];
882 // allow hook to override / manipulate migrationInfo as well
883 $migrationInfo = $migrationData['old_migration_info'];
885 if (!empty($conflicts)) {
886 foreach ($conflicts as $key => $val) {
887 if ($val === NULL and $mode == 'safe') {
888 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
892 // copy over the resolved values
893 $migrationInfo[$key] = $val;
896 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
897 if (array_key_exists('skip_merge', $migrationData)) {
898 return (bool) $migrationData['skip_merge'];
905 * A function to build an array of information about location blocks that is
906 * required when merging location fields
910 public static function getLocationBlockInfo() {
911 $locationBlocks = array(
913 'label' => 'Address',
914 'displayField' => 'display',
915 'sortString' => 'location_type_id',
916 'hasLocation' => TRUE,
921 'displayField' => 'email',
922 'sortString' => 'location_type_id',
923 'hasLocation' => TRUE,
928 'displayField' => 'name',
929 'sortString' => 'location_type_id,provider_id',
930 'hasLocation' => TRUE,
931 'hasType' => 'provider_id',
935 'displayField' => 'phone',
936 'sortString' => 'location_type_id,phone_type_id',
937 'hasLocation' => TRUE,
938 'hasType' => 'phone_type_id',
941 'label' => 'Website',
942 'displayField' => 'url',
943 'sortString' => 'website_type_id',
944 'hasLocation' => FALSE,
945 'hasType' => 'website_type_id',
948 return $locationBlocks;
952 * A function to build an array of information required by merge function and the merge UI.
955 * Main contact with whom merge has to happen.
956 * @param int $otherId
957 * Duplicate contact which would be deleted after merge operation.
959 * @return array|bool|int
960 * 'main_loc_block' => Stores all location blocks associated with the 'main' contact
962 public static function getRowsElementsAndInfo($mainId, $otherId) {
963 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
966 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
968 'contact_id' => $cid,
970 'return' => array_merge(array('display_name'), self
::getContactFields()),
972 $result = civicrm_api('contact', 'get', $params);
974 if (empty($result['values'][$cid]['contact_type'])) {
977 $
$moniker = $result['values'][$cid];
980 static $fields = array();
981 if (empty($fields)) {
982 $fields = CRM_Contact_DAO_Contact
::fields();
983 CRM_Core_DAO
::freeResult();
986 // FIXME: there must be a better way
987 foreach (array('main', 'other') as $moniker) {
988 $contact = &$
$moniker;
989 $preferred_communication_method = CRM_Utils_array
::value('preferred_communication_method', $contact);
990 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
991 $specialValues[$moniker] = array(
992 'preferred_communication_method' => $value,
993 'communication_style_id' => $value,
996 if (!empty($contact['preferred_communication_method'])) {
997 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
998 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
999 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
1002 'preferred_communication_method' => array(
1003 'newName' => 'preferred_communication_method_display',
1004 'groupName' => 'preferred_communication_method',
1007 CRM_Core_OptionGroup
::lookupValues($specialValues[$moniker], $names);
1009 if (!empty($contact['communication_style'])) {
1010 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
1014 static $optionValueFields = array();
1015 if (empty($optionValueFields)) {
1016 $optionValueFields = CRM_Core_OptionValue
::getFields();
1018 foreach ($optionValueFields as $field => $params) {
1019 $fields[$field]['title'] = $params['title'];
1022 $compareFields = self
::retrieveFields($main, $other);
1024 $rows = $elements = $relTableElements = $migrationInfo = array();
1026 foreach ($compareFields['contact'] as $field) {
1027 if ($field == 'contact_sub_type') {
1028 // CRM-15681 don't display sub-types in UI
1031 foreach (array('main', 'other') as $moniker) {
1032 $contact = &$
$moniker;
1033 $value = CRM_Utils_Array
::value($field, $contact);
1034 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
1035 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1037 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
1038 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
1040 $value = str_replace('-', '', $value);
1041 $label = CRM_Utils_Date
::customFormat($label);
1047 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
1048 if ($label === '0') {
1051 if ($label === '1') {
1055 elseif ($field == 'individual_prefix' ||
$field == 'prefix_id') {
1056 $label = CRM_Utils_Array
::value('individual_prefix', $contact);
1057 $value = CRM_Utils_Array
::value('prefix_id', $contact);
1058 $field = 'prefix_id';
1060 elseif ($field == 'individual_suffix' ||
$field == 'suffix_id') {
1061 $label = CRM_Utils_Array
::value('individual_suffix', $contact);
1062 $value = CRM_Utils_Array
::value('suffix_id', $contact);
1063 $field = 'suffix_id';
1065 elseif ($field == 'gender_id' && !empty($value)) {
1066 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
1067 $label = $genderOptions['values'][$value];
1069 elseif ($field == 'current_employer_id' && !empty($value)) {
1070 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
1072 $rows["move_$field"][$moniker] = $label;
1073 if ($moniker == 'other') {
1075 if ($value === NULL ||
$value == '') {
1078 if ($value === 0 or $value === '0') {
1079 $value = $qfZeroBug;
1081 if (is_array($value) && empty($value[1])) {
1085 // Display a checkbox to migrate, only if the values are different
1086 if ($value != $main[$field]) {
1087 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1090 $migrationInfo["move_$field"] = $value;
1093 $rows["move_$field"]['title'] = $fields[$field]['title'];
1096 // Handle location blocks.
1097 // @todo OpenID not in API yet, so is not supported here.
1099 // Set up useful information about the location blocks
1100 $locationBlocks = self
::getLocationBlockInfo();
1107 $mainLocBlock = array();
1109 // @todo This could probably be defined and used earlier
1110 $mergeTargets = array(
1112 'other' => $otherId,
1115 foreach ($locationBlocks as $blockName => $blockInfo) {
1117 // Collect existing fields from both 'main' and 'other' contacts first
1118 // This allows us to match up location/types when building the table rows
1119 foreach ($mergeTargets as $moniker => $cid) {
1121 $searchParams = array(
1123 'contact_id' => $cid,
1124 // CRM-17556 Order by field-specific criteria
1126 'sort' => $blockInfo['sortString'],
1129 $values = civicrm_api($blockName, 'get', $searchParams);
1130 if ($values['count']) {
1132 foreach ($values['values'] as $index => $value) {
1133 $locations[$moniker][$blockName][$cnt] = $value;
1134 // Fix address display
1136 if ($blockName == 'address') {
1137 CRM_Core_BAO_Address
::fixAddress($value);
1138 $display = CRM_Utils_Address
::format($value);
1139 $locations[$moniker][$blockName][$cnt]['display'] = $display;
1142 // Add any 'main' contact block values to an array for the JS
1143 // @todo The JS should just access the main_details to find this info?
1144 if ($moniker == 'main') {
1145 if ($blockInfo['hasType']) {
1146 // Handle websites, no location type ID
1147 // @todo Remove the need for this specific 'if'
1148 if ($blockName == 'website') {
1149 $value['location_type_id'] = 0;
1151 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id'] . "_" . $value[$blockInfo['hasType']]]['display'] = $value[$blockInfo['displayField']];
1152 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id'] . "_" . $value[$blockInfo['hasType']]]['id'] = $value['id'];
1155 // Get the correct display value for addresses
1156 // @todo Remove the need for this if...
1157 if ($blockName == 'address') {
1158 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['display'] = $display;
1159 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['id'] = $value['id'];
1162 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['display'] = $value[$blockInfo['displayField']];
1163 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['id'] = $value['id'];
1173 // Now, build the table rows appropriately, based off the information on
1174 // the 'other' contact
1175 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1176 foreach ($locations['other'][$blockName] as $count => $value) {
1178 $displayValue = $value[$blockInfo['displayField']];
1180 // Add this value to the table rows
1181 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1183 // CRM-17556 Only display 'main' contact value if it's the same location + type
1184 // Look it up from main values...
1186 $lookupLocation = FALSE;
1187 if ($blockInfo['hasLocation']) {
1188 $lookupLocation = $value['location_type_id'];
1191 $lookupType = FALSE;
1192 if ($blockInfo['hasType']) {
1193 $lookupType = $value[$blockInfo['hasType']];
1196 // Hold ID of main contact's matching block
1197 $mainContactBlockId = 0;
1199 if (!empty($locations['main'][$blockName])) {
1200 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1201 // No location/type, or matching location and type
1203 (empty($lookupLocation) ||
$lookupLocation == $mainValueCheck['location_type_id'])
1204 && (empty($lookupType) ||
$lookupType == $mainValueCheck[$blockInfo['hasType']])
1206 // Set this value as the default against the 'other' contact value
1207 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1208 $mainContactBlockId = $mainValueCheck['id'];
1214 // Add checkbox to migrate data from 'other' to 'main'
1215 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
1217 // Flag up this field to skipMerge function (@todo: do we need to?)
1218 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1220 // Add a hidden field to store the ID of the target main contact block
1221 $elements[] = array('hidden', "location[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
1224 $thisTypeId = FALSE;
1227 // Provide a select drop-down for the location's location type
1228 // eg: Home, Work...
1232 if ($blockInfo['hasLocation']) {
1234 // Load the location options for this entity
1235 $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
1237 // JS lookup 'main' contact's location (if there are any)
1238 if (!empty($locations['main'][$blockName])) {
1239 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'locTypeId' );");
1242 $thisLocId = $value['location_type_id'];
1244 // Put this field's location type at the top of the list
1245 $tmpIdList = $locationOptions['values'];
1246 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1247 unset($tmpIdList[$thisLocId]);
1250 $elements[] = array(
1252 "location[$blockName][$count][locTypeId]",
1254 $defaultLocId +
$tmpIdList,
1258 // Add the relevant information to the $migrationInfo
1259 // Keep location-type-id same as that of other-contact
1260 // @todo Check this logic out
1261 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1262 if ($blockName != 'address') {
1263 $elements[] = array('advcheckbox', "location[{$blockName}][$count][operation]", NULL, ts('add new'));
1264 // always use add operation
1265 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1270 // Provide a select drop-down for the location's type/provider
1271 // eg websites: Google+, Facebook...
1275 if ($blockInfo['hasType']) {
1277 // Load the type options for this entity
1278 $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
1280 // CRM-17556 Set up JS lookup of 'main' contact's value by type
1281 if (!empty($locations['main'][$blockName])) {
1282 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'typeTypeId' );");
1285 $thisTypeId = $value[$blockInfo['hasType']];
1287 // Put this field's location type at the top of the list
1288 $tmpIdList = $typeOptions['values'];
1289 $defaultTypeId = array($thisTypeId => $tmpIdList[$thisTypeId]);
1290 unset($tmpIdList[$thisTypeId]);
1293 $elements[] = array(
1295 "location[$blockName][$count][typeTypeId]",
1297 $defaultTypeId +
$tmpIdList,
1301 // Add the information to the migrationInfo (@todo Why?)
1302 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1306 // Set the label for this row
1307 $rowTitle = $blockInfo['label'] . ' ' . ($count +
1);
1308 if (!empty($thisLocId)) {
1309 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1311 if (!empty($thisTypeId)) {
1312 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1314 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1316 } // End loop through 'other' locations of this type
1318 } // End if 'other' location for this type exists
1320 } // End loop through each location block entity
1322 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1323 $config = CRM_Core_Config
::singleton();
1324 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1328 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1329 $mainUser = user_load($mainUfId);
1331 elseif ($config->userFramework
== 'Joomla') {
1332 $mainUser = JFactory
::getUser($mainUfId);
1335 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1339 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1340 $otherUser = user_load($otherUfId);
1342 elseif ($config->userFramework
== 'Joomla') {
1343 $otherUser = JFactory
::getUser($otherUfId);
1347 $relTables = CRM_Dedupe_Merger
::relTables();
1348 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1349 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1350 foreach ($relTables as $name => $null) {
1351 if (!in_array($name, $activeRelTables) &&
1352 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1354 unset($relTables[$name]);
1358 $relTableElements[] = array('checkbox', "move_$name");
1359 $migrationInfo["move_$name"] = 1;
1361 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1362 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1363 if ($name == 'rel_table_users') {
1364 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1365 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1366 $find = array('$ufid', '$ufname');
1368 $replace = array($mainUfId, $mainUser->name
);
1369 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1372 $replace = array($otherUfId, $otherUser->name
);
1373 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1376 if ($name == 'rel_table_memberships') {
1377 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1378 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1381 foreach ($relTables as $name => $null) {
1382 $relTables["move_$name"] = $relTables[$name];
1383 unset($relTables[$name]);
1386 // handle custom fields
1387 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $mainId, -1,
1388 CRM_Utils_Array
::value('contact_sub_type', $main)
1390 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $otherId, -1,
1391 CRM_Utils_Array
::value('contact_sub_type', $other)
1393 CRM_Core_DAO
::freeResult();
1395 foreach ($otherTree as $gid => $group) {
1396 $foundField = FALSE;
1397 if (!isset($group['fields'])) {
1401 foreach ($group['fields'] as $fid => $field) {
1402 if (in_array($fid, $compareFields['custom'])) {
1404 $rows["custom_group_$gid"]['title'] = $group['title'];
1407 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1408 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1409 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1413 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1414 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1415 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1416 if ($values['data'] === 0 ||
$values['data'] === '0') {
1417 $values['data'] = $qfZeroBug;
1419 $value = ($values['data']) ?
$values['data'] : $value;
1422 $rows["move_custom_$fid"]['title'] = $field['label'];
1424 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1425 $migrationInfo["move_custom_$fid"] = $value;
1432 'elements' => $elements,
1433 'rel_table_elements' => $relTableElements,
1434 'main_loc_block' => $mainLocBlock,
1435 'rel_tables' => $relTables,
1436 'main_details' => $main,
1437 'other_details' => $other,
1438 'migration_info' => $migrationInfo,
1441 $result['main_details']['location_blocks'] = $locations['main'];
1442 $result['other_details']['location_blocks'] = $locations['other'];
1448 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1449 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1450 * A superset of moveContactBelongings() function.
1452 * @param int $mainId
1453 * Main contact with whom merge has to happen.
1454 * @param int $otherId
1455 * Duplicate contact which would be deleted after merge operation.
1457 * @param $migrationInfo
1461 public static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1462 if (empty($migrationInfo)) {
1466 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1467 $relTables = CRM_Dedupe_Merger
::relTables();
1468 $moveTables = $locBlocks = $tableOperations = array();
1469 foreach ($migrationInfo as $key => $value) {
1470 if ($value == $qfZeroBug) {
1473 if ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) ||
1474 substr($key, 0, 12) == 'move_custom_') &&
1477 $submitted[substr($key, 5)] = $value;
1480 // Set up initial information for handling migration of location blocks
1481 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1482 $locField = explode('_', $key);
1483 $fieldName = $locField[2];
1484 $fieldCount = $locField[3];
1486 // Set up the operation type (add/overwrite)
1487 // Ignore operation for websites
1488 // @todo Tidy this up
1490 if ($fieldName != 'website') {
1491 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1493 // default operation is overwrite.
1497 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1501 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1502 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1503 if (array_key_exists('operation', $migrationInfo)) {
1504 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1505 if (array_key_exists($key, $migrationInfo['operation'])) {
1506 $tableOperations[$table] = $migrationInfo['operation'][$key];
1513 // **** Do location related migration.
1514 // @todo Handle OpenID (not currently in API).
1515 if (!empty($locBlocks)) {
1517 $locationBlocks = self
::getLocationBlockInfo();
1519 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
1520 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
1522 foreach ($locBlocks as $name => $block) {
1523 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1526 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
1527 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1528 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1530 foreach ($block as $blkCount => $values) {
1532 // For the block which belongs to other-contact, link the location block to main-contact
1533 $otherBlockDAO = new $daoName();
1534 $otherBlockDAO->contact_id
= $mainId;
1536 // Get the ID of this block on the 'other' contact, otherwise skip
1537 $otherBlockId = CRM_Utils_Array
::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
1538 if (!$otherBlockId) {
1541 $otherBlockDAO->id
= $otherBlockId;
1543 // Add/update location and type information from the form, if applicable
1544 if ($locationBlocks[$name]['hasLocation']) {
1545 $locTypeId = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1546 $otherBlockDAO->location_type_id
= $locTypeId;
1548 if ($locationBlocks[$name]['hasType']) {
1549 $typeTypeId = CRM_Utils_Array
::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1550 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
1553 // Get main block ID
1554 $mainBlockId = CRM_Utils_Array
::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1556 // if main contact already has primary & billing, set the flags to 0.
1557 if ($primaryDAOId) {
1558 $otherBlockDAO->is_primary
= 0;
1560 if ($billingDAOId) {
1561 $otherBlockDAO->is_billing
= 0;
1564 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1565 // overwrite - need to delete block which belongs to main-contact.
1566 if (!empty($mainBlockId) && ($operation == 2)) {
1567 $deleteDAO = new $daoName();
1568 $deleteDAO->id
= $mainBlockId;
1569 $deleteDAO->find(TRUE);
1571 // if we about to delete a primary / billing block, set the flags for new block
1572 // that we going to assign to main-contact
1573 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1574 $otherBlockDAO->is_primary
= 1;
1576 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1577 $otherBlockDAO->is_billing
= 1;
1580 $deleteDAO->delete();
1584 $otherBlockDAO->update();
1585 $otherBlockDAO->free();
1590 // **** Do tables related migrations
1591 if (!empty($moveTables)) {
1592 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1593 unset($moveTables, $tableOperations);
1596 // **** Do contact related migrations
1597 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId);
1599 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1600 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1601 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1602 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1603 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1604 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1605 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1606 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1607 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1609 // fix custom fields so they're edible by createProfileContact()
1610 static $treeCache = array();
1611 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1612 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree($migrationInfo['main_details']['contact_type'],
1613 CRM_Core_DAO
::$_nullObject, NULL, -1
1616 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1619 foreach ($cgTree as $key => $group) {
1620 if (!isset($group['fields'])) {
1623 foreach ($group['fields'] as $fid => $field) {
1624 $cFields[$fid]['attributes'] = $field;
1628 if (!isset($submitted)) {
1629 $submitted = array();
1631 foreach ($submitted as $key => $value) {
1632 if (substr($key, 0, 7) == 'custom_') {
1633 $fid = (int) substr($key, 7);
1634 if (empty($cFields[$fid])) {
1637 $htmlType = $cFields[$fid]['attributes']['html_type'];
1638 switch ($htmlType) {
1640 $customFiles[] = $fid;
1641 unset($submitted["custom_$fid"]);
1644 case 'Select Country':
1645 case 'Select State/Province':
1646 $submitted[$key] = CRM_Core_BAO_CustomField
::displayValue($value, $fid);
1650 case 'AdvMulti-Select':
1651 case 'Multi-Select':
1652 case 'Multi-Select Country':
1653 case 'Multi-Select State/Province':
1654 // Merge values from both contacts for multivalue fields, CRM-4385
1655 // get the existing custom values from db.
1656 $customParams = array('entityID' => $mainId, $key => TRUE);
1657 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1658 if (!empty($customfieldValues[$key])) {
1659 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1660 if (is_array($existingValue) && !empty($existingValue)) {
1661 $mergeValue = $submmtedCustomValue = array();
1663 $submmtedCustomValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1666 //hack to remove null and duplicate values from array.
1667 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1668 if ($v != '' && !in_array($v, $mergeValue)) {
1673 //keep state and country as array format.
1674 //for checkbox and m-select format w/ VALUE_SEPARATOR
1675 if (in_array($htmlType, array(
1680 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1682 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1685 $submitted[$key] = $mergeValue;
1689 elseif (in_array($htmlType, array(
1690 'Multi-Select Country',
1691 'Multi-Select State/Province',
1693 //we require submitted values should be in array format
1695 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1696 //hack to remove null values from array.
1697 $mergeValue = array();
1698 foreach ($mergeValueArray as $k => $v) {
1703 $submitted[$key] = $mergeValue;
1714 // **** Do file custom fields related migrations
1715 // FIXME: move this someplace else (one of the BAOs) after discussing
1716 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1717 // like, delete a file...
1719 if (!isset($customFiles)) {
1720 $customFiles = array();
1722 foreach ($customFiles as $customId) {
1723 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1725 // get the contact_id -> file_id mapping
1727 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1728 $dao = CRM_Core_DAO
::executeQuery($sql);
1729 while ($dao->fetch()) {
1730 $fileIds[$dao->entity_id
] = $dao->file_id
;
1734 // delete the main contact's file
1735 if (!empty($fileIds[$mainId])) {
1736 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 = (int) substr($key, 7);
1771 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1772 $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 // **** Delete other contact & update prev-next caching
1783 $otherParams = array(
1784 'contact_id' => $otherId,
1788 if (CRM_Core_Permission
::check('merge duplicate contacts') &&
1789 CRM_Core_Permission
::check('delete contacts')
1791 // if ext id is submitted then set it null for contact to be deleted
1792 if (!empty($submitted['external_identifier'])) {
1793 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1794 CRM_Core_DAO
::executeQuery($query);
1797 civicrm_api('contact', 'delete', $otherParams);
1798 CRM_Core_BAO_PrevNextCache
::deleteItem($otherId);
1803 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1807 // CRM-15681 merge sub_types
1808 if ($other_sub_types = CRM_Utils_array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1809 if ($main_sub_types = CRM_Utils_array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1810 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1813 $submitted['contact_sub_type'] = $other_sub_types;
1817 // **** Update contact related info for the main contact
1818 if (!empty($submitted)) {
1819 $submitted['contact_id'] = $mainId;
1821 //update current employer field
1822 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1823 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1824 $submitted['current_employer'] = $submitted['current_employer_id'];
1827 $submitted['current_employer'] = '';
1829 unset($submitted['current_employer_id']);
1832 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1833 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1834 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1836 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1837 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1840 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);
1844 CRM_Utils_Hook
::post('merge', 'Contact', $mainId, CRM_Core_DAO
::$_nullObject);
1851 * Array of field names which will be compared, so everything except ID.
1853 public static function getContactFields() {
1854 $contactFields = CRM_Contact_DAO_Contact
::fields();
1855 $invalidFields = array(
1857 'contact_is_deleted',
1863 'primary_contact_id',
1867 foreach ($contactFields as $field => $value) {
1868 if (in_array($field, $invalidFields)) {
1869 unset($contactFields[$field]);
1872 return array_keys($contactFields);
1876 * Added for CRM-12695
1877 * Based on the contactID provided
1878 * add/update membership(s) to related contacts
1880 * @param int $contactID
1882 public static function addMembershipToRealtedContacts($contactID) {
1883 $dao = new CRM_Member_DAO_Membership();
1884 $dao->contact_id
= $contactID;
1888 //checks membership of contact itself
1889 while ($dao->fetch()) {
1890 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1891 if ($relationshipTypeId) {
1892 $membershipParams = array(
1894 'contact_id' => $dao->contact_id
,
1895 'membership_type_id' => $dao->membership_type_id
,
1896 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1897 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1898 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1899 'source' => $dao->source
,
1900 'status_id' => $dao->status_id
,
1902 // create/update membership(s) for related contact(s)
1903 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1904 } // end of if relationshipTypeId
1909 * Add custom tables that extend contacts to the list of contact references.
1911 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
1912 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
1913 * - the down side is it is not cached.
1915 * Further changes should be include tests in the CRM_Core_MergerTest class
1916 * to ensure that disabled, subtype, multiple etc groups are still captured.
1918 * @param array $cidRefs
1920 public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
1921 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
1922 $customValueTables->find();
1923 while ($customValueTables->fetch()) {
1924 $cidRefs[$customValueTables->table_name
] = array('entity_id');