3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 * This function calls the merge hook but the entityTypes hook is the recommended
209 * way to add tables to this result.
211 public static function cidRefs() {
212 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
213 return \Civi
::$statics[__CLASS__
]['contact_references'];
215 $contactReferences = array();
216 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
217 foreach ($coreReferences as $coreReference) {
218 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
219 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
222 self
::addCustomTablesExtendingContactsToCidRefs($contactReferences);
224 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
225 $contactReferences['civicrm_entity_tag'][] = 'entity_id';
227 // Allow hook_civicrm_merge() to adjust $cidRefs.
228 // Note that if entities are registered using the entityTypes hook there
229 // is no need to use this hook.
230 CRM_Utils_Hook
::merge('cidRefs', $contactReferences);
231 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
232 return \Civi
::$statics[__CLASS__
]['contact_references'];
236 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
238 public static function eidRefs() {
241 // FIXME: this should be generated dynamically from the schema
242 // tables that reference contacts with entity_{id,table}
244 'civicrm_acl' => array('entity_table' => 'entity_id'),
245 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
246 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
247 'civicrm_log' => array('entity_table' => 'entity_id'),
248 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
249 'civicrm_note' => array('entity_table' => 'entity_id'),
252 // Allow hook_civicrm_merge() to adjust $eidRefs
253 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
259 * Return tables using locations.
261 public static function locTables() {
264 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
266 // Allow hook_civicrm_merge() to adjust $locTables
267 CRM_Utils_Hook
::merge('locTables', $locTables);
273 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
274 * @param string $request
275 * 'relTables' or 'cidRefs'.
278 public static function getMultiValueCustomSets($request) {
280 if ($data === NULL) {
282 'relTables' => array(),
283 'cidRefs' => array(),
285 $result = civicrm_api3('custom_group', 'get', array(
287 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
288 'return' => array('id', 'title', 'table_name', 'style'),
290 foreach ($result['values'] as $custom) {
291 $data['cidRefs'][$custom['table_name']] = array('entity_id');
292 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
293 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
294 'title' => $custom['title'],
295 'tables' => array($custom['table_name']),
296 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
300 return $data[$request];
304 * Tables which require custom processing should declare functions to call here.
305 * Doing so will override normal processing.
307 public static function cpTables() {
311 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
312 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
313 // Empty array == do nothing - this table is handled by mergeGroupContact
314 'civicrm_subscription_history' => array(),
315 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
322 * Return payment related table.
324 public static function paymentTables() {
327 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
333 * Return payment update Query.
335 * @param string $tableName
336 * @param int $mainContactId
337 * @param int $otherContactId
341 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
343 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
347 $paymentTables = self
::paymentTables();
348 if (!in_array($tableName, $paymentTables)) {
352 switch ($tableName) {
353 case 'civicrm_pledge':
355 UPDATE IGNORE civicrm_contribution contribution
356 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
357 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
358 SET contribution.contact_id = $mainContactId
359 WHERE pledge.contact_id = $otherContactId";
362 case 'civicrm_membership':
364 UPDATE IGNORE civicrm_contribution contribution
365 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
366 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
367 SET contribution.contact_id = $mainContactId
368 WHERE membership.contact_id = $otherContactId";
371 case 'civicrm_participant':
373 UPDATE IGNORE civicrm_contribution contribution
374 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
375 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
376 SET contribution.contact_id = $mainContactId
377 WHERE participant.contact_id = $otherContactId";
386 * @param int $otherId
387 * @param string $tableName
388 * @param array $tableOperations
389 * @param string $mode
393 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
395 if (!$tableName ||
!$mainId ||
!$otherId) {
399 switch ($tableName) {
400 case 'civicrm_membership':
401 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
404 if ($mode == 'add') {
406 DELETE membership1.* FROM civicrm_membership membership1
407 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
408 AND membership1.contact_id = {$mainId}
409 AND membership2.contact_id = {$otherId} ";
411 if ($mode == 'payment') {
413 DELETE contribution.* FROM civicrm_contribution contribution
414 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
415 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
416 AND membership1.contact_id = {$mainId}
417 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
418 AND membership2.contact_id = {$otherId}";
422 case 'civicrm_uf_match':
423 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
424 // failing to meet intended result. Therefore we introduce this additional query:
425 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
433 * Based on the provided two contact_ids and a set of tables, move the
434 * belongings of the other contact to the main one.
437 * @param int $otherId
438 * @param bool $tables
439 * @param array $tableOperations
440 * @param array $customTableToCopyFrom
442 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array(), $customTableToCopyFrom = NULL) {
443 $cidRefs = self
::cidRefs();
444 $eidRefs = self
::eidRefs();
445 $cpTables = self
::cpTables();
446 $paymentTables = self
::paymentTables();
448 // getting all custom tables
449 $customTables = array();
450 if ($customTableToCopyFrom !== NULL) {
451 self
::addCustomTablesExtendingContactsToCidRefs($customTables);
452 $customTables = array_keys($customTables);
455 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
457 // if there aren't any specific tables, don't affect the ones handled by relTables()
458 // also don't affect tables in locTables() CRM-15658
459 $relTables = self
::relTables();
460 $handled = self
::locTables();
462 foreach ($relTables as $params) {
463 $handled = array_merge($handled, $params['tables']);
465 $affected = array_diff($affected, $handled);
466 $affected = array_unique(array_merge($affected, $tables));
468 $mainId = (int) $mainId;
469 $otherId = (int) $otherId;
472 foreach ($affected as $table) {
473 // skipping non selected custom table's value migration
474 if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
478 // Call custom processing function for objects that require it
479 if (isset($cpTables[$table])) {
480 foreach ($cpTables[$table] as $className => $fnName) {
481 $className::$fnName($mainId, $otherId, $sqls);
483 // Skip normal processing
487 // use UPDATE IGNORE + DELETE query pair to skip on situations when
488 // there's a UNIQUE restriction on ($field, some_other_field) pair
489 if (isset($cidRefs[$table])) {
490 foreach ($cidRefs[$table] as $field) {
491 // carry related contributions CRM-5359
492 if (in_array($table, $paymentTables)) {
493 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
494 $sqls = array_merge($sqls, $paymentSqls);
496 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
497 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
498 $sqls = array_merge($sqls, $payOprSqls);
502 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
503 $sqls = array_merge($sqls, $preOperationSqls);
505 if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self
::customRecordExists($mainId, $table, $field)) {
506 $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
508 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
509 $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);
529 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
530 $transaction->commit();
534 * Given a contact ID, will check if a record exists in given table.
539 * Field where the contact's ID is stored in the table
542 * True if a record is found for the given contact ID, false otherwise
544 private static function customRecordExists($contactID, $table, $idField) {
546 SELECT COUNT(*) AS count
548 WHERE $idField = $contactID
550 $dbResult = CRM_Core_DAO
::executeQuery($sql);
553 if ($dbResult->count
> 0) {
561 * Load all non-empty fields for the contacts
565 * @param array $other
570 public static function retrieveFields($main, $other) {
572 'contact' => array(),
575 foreach (self
::getContactFields() as $validField) {
576 // CRM-17556 Get all non-empty fields, to make comparison easier
577 if (!empty($main[$validField]) ||
!empty($other[$validField])) {
578 $result['contact'][] = $validField;
582 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
583 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
584 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
585 foreach ($keys as $key) {
586 // Exclude multi-value fields CRM-13836
587 if (strpos($key, '_')) {
590 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
591 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
592 // CRM-17556 Get all non-empty fields, to make comparison easier
593 if (!empty($key1) ||
!empty($key2)) {
594 $result['custom'][] = $key;
601 * Batch merge a set of contacts based on rule-group and group.
607 * @param string $mode
608 * Helps decide how to behave when there are conflicts.
609 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
610 * mode does a force merge.
611 * @param int $batchLimit number of merges to carry out in one batch.
612 * @param int $isSelected if records with is_selected column needs to be processed.
614 * @param array $criteria
615 * Criteria to use in the filter.
617 * @param bool $checkPermissions
618 * Respect logged in user permissions.
622 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = array(), $checkPermissions = TRUE) {
623 $redirectForPerformance = ($batchLimit > 1) ?
TRUE : FALSE;
624 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
625 $dupePairs = self
::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, '', ($mode == 'aggressive'), $criteria, $checkPermissions);
627 $cacheParams = array(
628 'cache_key_string' => self
::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
629 // @todo stop passing these parameters in & instead calculate them in the merge function based
630 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
631 'join' => self
::getJoinOnDedupeTable(),
632 'where' => self
::getWhereString($batchLimit, $isSelected),
634 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
638 * Get the string to join the prevnext cache to the dedupe table.
641 * The join string to join prevnext cache on the dedupe table.
643 public static function getJoinOnDedupeTable() {
645 LEFT JOIN civicrm_dedupe_exception de
647 pn.entity_id1 = de.contact_id1
648 AND pn.entity_id2 = de.contact_id2 )
653 * Get where string for dedupe join.
655 * @param int $batchLimit
656 * @param bool $isSelected
660 protected static function getWhereString($batchLimit, $isSelected) {
661 $where = "de.id IS NULL";
662 if ($isSelected === 0 ||
$isSelected === 1) {
663 $where .= " AND pn.is_selected = {$isSelected}";
665 // else consider all dupe pairs
666 // @todo Adding limit to Where??!!
668 $where .= " LIMIT {$batchLimit}";
674 * Update the statistics for the merge set.
676 * @param string $cacheKeyString
677 * @param array $result
679 public static function updateMergeStats($cacheKeyString, $result = array()) {
680 // gather latest stats
681 $merged = count($result['merged']);
682 $skipped = count($result['skipped']);
684 if ($merged <= 0 && $skipped <= 0) {
688 // get previous stats
689 $previousStats = CRM_Core_BAO_PrevNextCache
::retrieve("{$cacheKeyString}_stats");
690 if (!empty($previousStats)) {
691 if ($previousStats[0]['merged']) {
692 $merged = $merged +
$previousStats[0]['merged'];
694 if ($previousStats[0]['skipped']) {
695 $skipped = $skipped +
$previousStats[0]['skipped'];
700 CRM_Dedupe_Merger
::resetMergeStats($cacheKeyString);
702 // store the updated stats
705 'skipped' => $skipped,
707 $data = CRM_Core_DAO
::escapeString(serialize($data));
710 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
711 CRM_Core_BAO_PrevNextCache
::setItem($values);
715 * Delete information about merges for the given string.
717 * @param $cacheKeyString
719 public static function resetMergeStats($cacheKeyString) {
720 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, "{$cacheKeyString}_stats");
724 * Get merge outcome statistics.
726 * @param string $cacheKeyString
729 * Array of how many were merged and how many were skipped.
731 public static function getMergeStats($cacheKeyString) {
732 $stats = CRM_Core_BAO_PrevNextCache
::retrieve("{$cacheKeyString}_stats");
733 if (!empty($stats)) {
740 * Get merge statistics message.
742 * @param string $cacheKeyString
746 public static function getMergeStatsMsg($cacheKeyString) {
748 $stats = CRM_Dedupe_Merger
::getMergeStats($cacheKeyString);
749 if (!empty($stats['merged'])) {
750 $msg = "{$stats['merged']} " . ts('Contact(s) were merged.');
752 if (!empty($stats['skipped'])) {
753 $msg .= $stats['skipped'] . ts(' Contact(s) were skipped.');
759 * Merge given set of contacts. Performs core operation.
761 * @param array $dupePairs
762 * Set of pair of contacts for whom merge is to be done.
763 * @param array $cacheParams
764 * Prev-next-cache params based on which next pair of contacts are computed.
765 * Generally used with batch-merge.
766 * @param string $mode
767 * Helps decide how to behave when there are conflicts.
768 * A 'safe' value skips the merge if there are any un-resolved conflicts.
769 * Does a force merge otherwise (aggressive mode).
771 * @param bool $redirectForPerformance
772 * Redirect to a url for batch processing.
774 * @param bool $checkPermissions
775 * Respect logged in user permissions.
779 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
780 $redirectForPerformance = FALSE, $checkPermissions = TRUE
782 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
783 $resultStats = array('merged' => array(), 'skipped' => array());
785 // we don't want dupe caching to get reset after every-merge, and therefore set the
786 CRM_Core_Config
::setPermitCacheFlushMode(FALSE);
787 $deletedContacts = array();
789 while (!empty($dupePairs)) {
790 foreach ($dupePairs as $index => $dupes) {
791 if (in_array($dupes['dstID'], $deletedContacts) ||
in_array($dupes['srcID'], $deletedContacts)) {
792 unset($dupePairs[$index]);
795 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
796 $mainId = $dupes['dstID'];
797 $otherId = $dupes['srcID'];
799 if (!$mainId ||
!$otherId) {
803 // Generate var $migrationInfo. The variable structure is exactly same as
804 // $formValues submitted during a UI merge for a pair of contacts.
805 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions);
806 // add additional details that we might need to resolve conflicts
807 $rowsElementsAndInfo['migration_info']['main_details'] = &$rowsElementsAndInfo['main_details'];
808 $rowsElementsAndInfo['migration_info']['other_details'] = &$rowsElementsAndInfo['other_details'];
809 $rowsElementsAndInfo['migration_info']['rows'] = &$rowsElementsAndInfo['rows'];
811 self
::dedupePair($rowsElementsAndInfo['migration_info'], $resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString);
814 if ($cacheKeyString && !$redirectForPerformance) {
815 // retrieve next pair of dupes
816 // @todo call getDuplicatePairs.
817 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
818 $cacheParams['join'],
819 $cacheParams['where'],
828 // do not proceed. Terminate the loop
833 CRM_Dedupe_Merger
::updateMergeStats($cacheKeyString, $resultStats);
838 * A function which uses various rules / algorithms for choosing which contact to bias to
839 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
842 * Main contact with whom merge has to happen.
843 * @param int $otherId
844 * Duplicate contact which would be deleted after merge operation.
845 * @param array $migrationInfo
846 * Array of information about which elements to merge.
847 * @param string $mode
848 * Helps decide how to behave when there are conflicts.
849 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
850 * - Does a force merge otherwise (aggressive mode).
852 * @param array $conflicts
856 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
858 $originalMigrationInfo = $migrationInfo;
859 foreach ($migrationInfo as $key => $val) {
860 if ($val === "null") {
861 // Rule: Never overwrite with an empty value (in any mode)
862 unset($migrationInfo[$key]);
865 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
866 substr($key, 0, 12) == 'move_custom_'
869 // Rule: If both main-contact, and other-contact have a field with a
870 // different value, then let $mode decide if to merge it or not
872 (!empty($migrationInfo['rows'][$key]['main'])
873 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
874 // is probably true for other fields too - e.g. 'do_not_email' but
875 // leaving that investigation as a @todo - until tests can be written.
876 // Note the handling of this has test coverage - although the data-typing
877 // of '0' feels flakey we have insurance.
878 ||
($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
880 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
883 // note it down & lets wait for response from the hook.
884 // For no response $mode will decide if to skip this merge
885 $conflicts[$key] = NULL;
888 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
889 $locField = explode('_', $key);
890 $fieldName = $locField[2];
891 $fieldCount = $locField[3];
893 // Rule: Catch address conflicts (same address type on both contacts)
895 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
896 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
899 // Load the address we're inspecting from the 'other' contact
900 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
901 $addressRecordLocTypeId = CRM_Utils_Array
::value('location_type_id', $addressRecord);
903 // If it exists on the 'main' contact already, skip it. Otherwise
904 // if the location type exists already, log a conflict.
905 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
906 if (self
::locationIsSame($addressRecord, $mainAddressRecord)) {
907 unset($migrationInfo[$key]);
910 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
911 $conflicts[$key] = NULL;
917 // For other locations, don't merge/add if the values are the same
918 elseif (CRM_Utils_Array
::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
919 unset($migrationInfo[$key]);
924 // A hook to implement other algorithms for choosing which contact to bias to when
925 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
926 // merge happens with new values filled in here. For a particular field / row not to be merged
927 // field should be unset from fields_in_conflict.
928 $migrationData = array(
929 'old_migration_info' => $originalMigrationInfo,
931 'fields_in_conflict' => $conflicts,
932 'merge_mode' => $mode,
933 'migration_info' => $migrationInfo,
935 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
936 $conflicts = $migrationData['fields_in_conflict'];
937 // allow hook to override / manipulate migrationInfo as well
938 $migrationInfo = $migrationData['migration_info'];
940 if (!empty($conflicts)) {
941 foreach ($conflicts as $key => $val) {
942 if ($val === NULL and $mode == 'safe') {
943 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
947 // copy over the resolved values
948 $migrationInfo[$key] = $val;
951 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
952 if (array_key_exists('skip_merge', $migrationData)) {
953 return (bool) $migrationData['skip_merge'];
960 * Compare 2 addresses to see if they are the same.
962 * @param array $mainAddress
963 * @param array $comparisonAddress
967 static public function locationIsSame($mainAddress, $comparisonAddress) {
968 $keysToIgnore = array('id', 'is_primary', 'is_billing', 'manual_geo_code', 'contact_id', 'reset_date', 'hold_date');
969 foreach ($comparisonAddress as $field => $value) {
970 if (in_array($field, $keysToIgnore)) {
973 if ((!empty($value) ||
$value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
981 * A function to build an array of information about location blocks that is
982 * required when merging location fields
986 public static function getLocationBlockInfo() {
987 $locationBlocks = array(
989 'label' => 'Address',
990 'displayField' => 'display',
991 'sortString' => 'location_type_id',
992 'hasLocation' => TRUE,
997 'displayField' => 'email',
998 'sortString' => 'location_type_id',
999 'hasLocation' => TRUE,
1004 'displayField' => 'name',
1005 'sortString' => 'location_type_id,provider_id',
1006 'hasLocation' => TRUE,
1007 'hasType' => 'provider_id',
1011 'displayField' => 'phone',
1012 'sortString' => 'location_type_id,phone_type_id',
1013 'hasLocation' => TRUE,
1014 'hasType' => 'phone_type_id',
1017 'label' => 'Website',
1018 'displayField' => 'url',
1019 'sortString' => 'website_type_id',
1020 'hasLocation' => FALSE,
1021 'hasType' => 'website_type_id',
1024 return $locationBlocks;
1028 * A function to build an array of information required by merge function and the merge UI.
1030 * @param int $mainId
1031 * Main contact with whom merge has to happen.
1032 * @param int $otherId
1033 * Duplicate contact which would be deleted after merge operation.
1034 * @param bool $checkPermissions
1035 * Should the logged in user's permissions be ignore. Setting this to false is
1036 * highly risky as it could cause data to be lost due to conflicts not showing up.
1037 * OTOH there is a risk a merger might view custom data they do not have permission to.
1038 * Hence for now only making this really explicit and making it reflect perms in
1041 * @todo review permissions issue!
1043 * @return array|bool|int
1045 * rows => An array of arrays, each is row of merge information for the table
1046 * Format: move_fieldname, eg: move_contact_type
1047 * main => Value associated with the main contact
1048 * other => Value associated with the other contact
1049 * title => The title of the field to display in the merge table
1051 * elements => An array of form elements for the merge UI
1053 * rel_table_elements => An array of form elements for the merge UI for
1054 * entities related to the contact (eg: checkbox to move 'mailings')
1056 * rel_tables => Stores the tables that have related entities for the contact
1057 * for example mailings, groups
1059 * main_details => An array of core contact field values, eg: first_name, etc.
1060 * location_blocks => An array of location block data for the main contact
1061 * stored as the 'result' of an API call.
1062 * eg: main_details['location_blocks']['address'][0]['id']
1063 * eg: main_details['location_blocks']['email'][1]['id']
1065 * other_details => As above, but for the 'other' contact
1067 * migration_info => Stores the 'default' merge actions for each field which
1068 * is used when programatically merging contacts. It contains instructions
1069 * to move all fields from the 'other' contact to the 'main' contact, as
1070 * though the form had been submitted with those options.
1072 * @throws \CRM_Core_Exception
1073 * @throws \CiviCRM_API3_Exception
1074 * @throws \Exception
1076 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1077 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1078 $fields = self
::getMergeFieldsMetadata();
1080 $main = self
::getMergeContactDetails($mainId);
1081 $other = self
::getMergeContactDetails($otherId);
1082 $specialValues['main'] = self
::getSpecialValues($main);
1083 $specialValues['other'] = self
::getSpecialValues($other);
1085 $compareFields = self
::retrieveFields($main, $other);
1087 $rows = $elements = $relTableElements = $migrationInfo = array();
1089 foreach ($compareFields['contact'] as $field) {
1090 if ($field == 'contact_sub_type') {
1091 // CRM-15681 don't display sub-types in UI
1094 foreach (array('main', 'other') as $moniker) {
1095 $contact = &$
$moniker;
1096 $value = CRM_Utils_Array
::value($field, $contact);
1097 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
1098 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1100 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
1101 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
1103 $value = str_replace('-', '', $value);
1104 $label = CRM_Utils_Date
::customFormat($label);
1110 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
1111 if ($label === '0') {
1114 if ($label === '1') {
1118 elseif ($field == 'prefix_id') {
1119 $label = CRM_Utils_Array
::value('individual_prefix', $contact);
1121 elseif ($field == 'suffix_id') {
1122 $label = CRM_Utils_Array
::value('individual_suffix', $contact);
1124 elseif ($field == 'gender_id' && !empty($value)) {
1125 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
1126 $label = $genderOptions['values'][$value];
1128 elseif ($field == 'current_employer_id' && !empty($value)) {
1129 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
1131 $rows["move_$field"][$moniker] = $label;
1132 if ($moniker == 'other') {
1134 if ($value === NULL ||
$value == '') {
1137 if ($value === 0 or $value === '0') {
1138 $value = $qfZeroBug;
1140 if (is_array($value) && empty($value[1])) {
1144 // Display a checkbox to migrate, only if the values are different
1145 if ($value != $main[$field]) {
1146 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1149 $migrationInfo["move_$field"] = $value;
1152 $rows["move_$field"]['title'] = $fields[$field]['title'];
1155 // Handle location blocks.
1156 // @todo OpenID not in API yet, so is not supported here.
1158 // Set up useful information about the location blocks
1159 $locationBlocks = self
::getLocationBlockInfo();
1166 // @todo This could probably be defined and used earlier
1167 $mergeTargets = array(
1169 'other' => $otherId,
1172 foreach ($locationBlocks as $blockName => $blockInfo) {
1174 // Collect existing fields from both 'main' and 'other' contacts first
1175 // This allows us to match up location/types when building the table rows
1176 foreach ($mergeTargets as $moniker => $cid) {
1177 $searchParams = array(
1178 'contact_id' => $cid,
1179 // CRM-17556 Order by field-specific criteria
1181 'sort' => $blockInfo['sortString'],
1184 $values = civicrm_api3($blockName, 'get', $searchParams);
1185 if ($values['count']) {
1187 foreach ($values['values'] as $value) {
1188 $locations[$moniker][$blockName][$cnt] = $value;
1189 // Fix address display
1190 if ($blockName == 'address') {
1191 CRM_Core_BAO_Address
::fixAddress($value);
1192 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address
::format($value);
1200 // Now, build the table rows appropriately, based off the information on
1201 // the 'other' contact
1202 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1203 foreach ($locations['other'][$blockName] as $count => $value) {
1205 $displayValue = $value[$blockInfo['displayField']];
1207 // Add this value to the table rows
1208 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1210 // CRM-17556 Only display 'main' contact value if it's the same location + type
1211 // Look it up from main values...
1213 $lookupLocation = FALSE;
1214 if ($blockInfo['hasLocation']) {
1215 $lookupLocation = $value['location_type_id'];
1218 $lookupType = FALSE;
1219 if ($blockInfo['hasType']) {
1220 $lookupType = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
1223 // Hold ID of main contact's matching block
1224 $mainContactBlockId = 0;
1226 if (!empty($locations['main'][$blockName])) {
1227 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1228 // No location/type, or matching location and type
1230 (empty($lookupLocation) ||
$lookupLocation == $mainValueCheck['location_type_id'])
1231 && (empty($lookupType) ||
$lookupType == $mainValueCheck[$blockInfo['hasType']])
1233 // Set this value as the default against the 'other' contact value
1234 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1235 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
1236 $mainContactBlockId = $mainValueCheck['id'];
1242 // Add checkbox to migrate data from 'other' to 'main'
1243 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
1245 // Add checkbox to set the 'other' location as primary
1246 $elements[] = array('advcheckbox', "location_blocks[$blockName][$count][set_other_primary]", NULL, ts('Set as primary'));
1248 // Flag up this field to skipMerge function (@todo: do we need to?)
1249 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1251 // Add a hidden field to store the ID of the target main contact block
1252 $elements[] = array('hidden', "location_blocks[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
1255 $thisTypeId = FALSE;
1258 // Provide a select drop-down for the location's location type
1259 // eg: Home, Work...
1261 if ($blockInfo['hasLocation']) {
1263 // Load the location options for this entity
1264 $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
1266 $thisLocId = $value['location_type_id'];
1268 // Put this field's location type at the top of the list
1269 $tmpIdList = $locationOptions['values'];
1270 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1271 unset($tmpIdList[$thisLocId]);
1274 $elements[] = array(
1276 "location_blocks[$blockName][$count][locTypeId]",
1278 $defaultLocId +
$tmpIdList,
1281 // Add the relevant information to the $migrationInfo
1282 // Keep location-type-id same as that of other-contact
1283 // @todo Check this logic out
1284 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1285 if ($blockName != 'address') {
1286 $elements[] = array('advcheckbox', "location_blocks[{$blockName}][$count][operation]", NULL, ts('Add new'));
1287 // always use add operation
1288 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1293 // Provide a select drop-down for the location's type/provider
1294 // eg websites: Google+, Facebook...
1296 if ($blockInfo['hasType']) {
1298 // Load the type options for this entity
1299 $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
1301 $thisTypeId = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
1303 // Put this field's location type at the top of the list
1304 $tmpIdList = $typeOptions['values'];
1305 $defaultTypeId = array($thisTypeId => CRM_Utils_Array
::value($thisTypeId, $tmpIdList));
1306 unset($tmpIdList[$thisTypeId]);
1309 $elements[] = array(
1311 "location_blocks[$blockName][$count][typeTypeId]",
1313 $defaultTypeId +
$tmpIdList,
1316 // Add the information to the migrationInfo
1317 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1321 // Set the label for this row
1322 $rowTitle = $blockInfo['label'] . ' ' . ($count +
1);
1323 if (!empty($thisLocId)) {
1324 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1326 if (!empty($thisTypeId)) {
1327 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1329 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1331 } // End loop through 'other' locations of this type
1333 } // End if 'other' location for this type exists
1335 } // End loop through each location block entity
1337 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1338 $config = CRM_Core_Config
::singleton();
1339 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1343 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1344 $mainUser = user_load($mainUfId);
1346 elseif ($config->userFramework
== 'Joomla') {
1347 $mainUser = JFactory
::getUser($mainUfId);
1350 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1354 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1355 $otherUser = user_load($otherUfId);
1357 elseif ($config->userFramework
== 'Joomla') {
1358 $otherUser = JFactory
::getUser($otherUfId);
1362 $relTables = CRM_Dedupe_Merger
::relTables();
1363 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1364 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1365 foreach ($relTables as $name => $null) {
1366 if (!in_array($name, $activeRelTables) &&
1367 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1369 unset($relTables[$name]);
1373 $relTableElements[] = array('checkbox', "move_$name");
1374 $migrationInfo["move_$name"] = 1;
1376 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1377 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1378 if ($name == 'rel_table_users') {
1379 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1380 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1381 $find = array('$ufid', '$ufname');
1383 $replace = array($mainUfId, $mainUser->name
);
1384 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1387 $replace = array($otherUfId, $otherUser->name
);
1388 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1391 if ($name == 'rel_table_memberships') {
1392 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1393 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1396 foreach ($relTables as $name => $null) {
1397 $relTables["move_$name"] = $relTables[$name];
1398 unset($relTables[$name]);
1401 // handle custom fields
1402 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $mainId, -1,
1403 CRM_Utils_Array
::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
1405 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $otherId, -1,
1406 CRM_Utils_Array
::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
1408 CRM_Core_DAO
::freeResult();
1410 foreach ($otherTree as $gid => $group) {
1411 $foundField = FALSE;
1412 if (!isset($group['fields'])) {
1416 foreach ($group['fields'] as $fid => $field) {
1417 if (in_array($fid, $compareFields['custom'])) {
1419 $rows["custom_group_$gid"]['title'] = $group['title'];
1422 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1423 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1424 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1428 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1429 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1430 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1431 if ($values['data'] === 0 ||
$values['data'] === '0') {
1432 $values['data'] = $qfZeroBug;
1434 $value = ($values['data']) ?
$values['data'] : $value;
1437 $rows["move_custom_$fid"]['title'] = $field['label'];
1439 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1440 $migrationInfo["move_custom_$fid"] = $value;
1447 'elements' => $elements,
1448 'rel_table_elements' => $relTableElements,
1449 'rel_tables' => $relTables,
1450 'main_details' => $main,
1451 'other_details' => $other,
1452 'migration_info' => $migrationInfo,
1455 $result['main_details']['location_blocks'] = $locations['main'];
1456 $result['other_details']['location_blocks'] = $locations['other'];
1462 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1463 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1464 * A superset of moveContactBelongings() function.
1466 * @param int $mainId
1467 * Main contact with whom merge has to happen.
1468 * @param int $otherId
1469 * Duplicate contact which would be deleted after merge operation.
1471 * @param $migrationInfo
1473 * @param bool $checkPermissions
1474 * Respect logged in user permissions.
1478 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1479 if (empty($migrationInfo)) {
1483 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1484 $relTables = CRM_Dedupe_Merger
::relTables();
1485 $submittedCustomFields = $moveTables = $locationMigrationInfo = $tableOperations = array();
1487 foreach ($migrationInfo as $key => $value) {
1488 if ($value == $qfZeroBug) {
1492 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
1493 $submitted[substr($key, 5)] = $value;
1494 $submittedCustomFields[] = substr($key, 12);
1496 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) && $value != NULL) {
1497 $submitted[substr($key, 5)] = $value;
1499 // Set up initial information for handling migration of location blocks
1500 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1501 $locationMigrationInfo[$key] = $value;
1503 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1504 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1505 if (array_key_exists('operation', $migrationInfo)) {
1506 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1507 if (array_key_exists($key, $migrationInfo['operation'])) {
1508 $tableOperations[$table] = $migrationInfo['operation'][$key];
1514 self
::mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo);
1516 // **** Do contact related migrations
1517 $customTablesToCopyValues = self
::getAffectedCustomTables($submittedCustomFields);
1518 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1519 unset($moveTables, $tableOperations);
1521 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1522 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1523 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1524 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1525 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1526 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1527 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1528 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1529 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1531 // fix custom fields so they're edible by createProfileContact()
1532 static $treeCache = array();
1533 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1534 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree($migrationInfo['main_details']['contact_type'], NULL, NULL, -1);
1538 foreach ($treeCache[$migrationInfo['main_details']['contact_type']] as $key => $group) {
1539 if (!isset($group['fields'])) {
1542 foreach ($group['fields'] as $fid => $field) {
1543 $cFields[$fid]['attributes'] = $field;
1547 if (!isset($submitted)) {
1548 $submitted = array();
1550 foreach ($submitted as $key => $value) {
1551 if (substr($key, 0, 7) == 'custom_') {
1552 $fid = (int) substr($key, 7);
1553 if (empty($cFields[$fid])) {
1556 $htmlType = $cFields[$fid]['attributes']['html_type'];
1557 switch ($htmlType) {
1559 $customFiles[] = $fid;
1560 unset($submitted["custom_$fid"]);
1563 case 'Select Country':
1564 case 'Select State/Province':
1565 $submitted[$key] = CRM_Core_BAO_CustomField
::displayValue($value, $fid);
1569 if ($cFields[$fid]['attributes']['is_view']) {
1570 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
1575 case 'AdvMulti-Select':
1576 case 'Multi-Select':
1577 case 'Multi-Select Country':
1578 case 'Multi-Select State/Province':
1579 // Merge values from both contacts for multivalue fields, CRM-4385
1580 // get the existing custom values from db.
1581 $customParams = array('entityID' => $mainId, $key => TRUE);
1582 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1583 if (!empty($customfieldValues[$key])) {
1584 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1585 if (is_array($existingValue) && !empty($existingValue)) {
1586 $mergeValue = $submittedCustomFields = array();
1587 if ($value == 'null') {
1588 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
1589 $submitted[$key] = $value;
1593 $submittedCustomFields = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1596 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
1597 // custom field value stored at $submittedCustomValue.
1598 foreach ($submittedCustomFields as $k => $v) {
1599 if ($v != '' && !in_array($v, $mergeValue)) {
1604 //keep state and country as array format.
1605 //for checkbox and m-select format w/ VALUE_SEPARATOR
1606 if (in_array($htmlType, array(
1611 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1613 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1616 $submitted[$key] = $mergeValue;
1621 elseif (in_array($htmlType, array(
1622 'Multi-Select Country',
1623 'Multi-Select State/Province',
1625 //we require submitted values should be in array format
1627 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1628 //hack to remove null values from array.
1629 $mergeValue = array();
1630 foreach ($mergeValueArray as $k => $v) {
1635 $submitted[$key] = $mergeValue;
1646 // **** Do file custom fields related migrations
1647 // FIXME: move this someplace else (one of the BAOs) after discussing
1648 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1649 // like, delete a file...
1651 if (!isset($customFiles)) {
1652 $customFiles = array();
1654 foreach ($customFiles as $customId) {
1655 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1657 // get the contact_id -> file_id mapping
1659 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1660 $dao = CRM_Core_DAO
::executeQuery($sql);
1661 while ($dao->fetch()) {
1662 $fileIds[$dao->entity_id
] = $dao->file_id
;
1663 if ($dao->entity_id
== $mainId) {
1664 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1669 // move the other contact's file to main contact
1670 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1671 if (CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
1672 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1675 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1677 CRM_Core_DAO
::executeQuery($sql);
1679 if (CRM_Core_DAO
::singleValueQuery("
1681 FROM civicrm_entity_file
1682 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1685 UPDATE civicrm_entity_file
1686 SET entity_id = {$mainId}
1687 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1691 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1692 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1694 CRM_Core_DAO
::executeQuery($sql);
1697 // move view only custom fields CRM-5362
1698 $viewOnlyCustomFields = array();
1699 foreach ($submitted as $key => $value) {
1700 $fid = (int) substr($key, 7);
1701 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1702 $viewOnlyCustomFields[$key] = $value;
1706 // special case to set values for view only, CRM-5362
1707 if (!empty($viewOnlyCustomFields)) {
1708 $viewOnlyCustomFields['entityID'] = $mainId;
1709 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1712 if (!$checkPermissions ||
(CRM_Core_Permission
::check('merge duplicate contacts') &&
1713 CRM_Core_Permission
::check('delete contacts'))
1715 // if ext id is submitted then set it null for contact to be deleted
1716 if (!empty($submitted['external_identifier'])) {
1717 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1718 CRM_Core_DAO
::executeQuery($query);
1720 civicrm_api3('contact', 'delete', array('id' => $otherId));
1723 // CRM-15681 merge sub_types
1724 if ($other_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1725 if ($main_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1726 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1729 $submitted['contact_sub_type'] = $other_sub_types;
1733 // **** Update contact related info for the main contact
1734 if (!empty($submitted)) {
1735 $submitted['contact_id'] = $mainId;
1737 //update current employer field
1738 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1739 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1740 $submitted['current_employer'] = $submitted['current_employer_id'];
1743 $submitted['current_employer'] = '';
1745 unset($submitted['current_employer_id']);
1748 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1749 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1750 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1752 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1753 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1756 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);
1759 CRM_Utils_Hook
::post('merge', 'Contact', $mainId);
1760 self
::createMergeActivities($mainId, $otherId);
1766 * Builds an Array of Custom tables for given custom field ID's.
1768 * @param $customFieldIDs
1771 * Array of custom table names
1773 private static function getAffectedCustomTables($customFieldIDs) {
1774 $customTableToCopyValues = array();
1776 foreach ($customFieldIDs as $fieldID) {
1777 if (!empty($fieldID)) {
1778 $customField = civicrm_api3('custom_field', 'getsingle', array(
1780 'is_active' => TRUE,
1782 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
1783 $customGroup = civicrm_api3('custom_group', 'getsingle', array(
1784 'id' => $customField['custom_group_id'],
1785 'is_active' => TRUE,
1788 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1789 $customTableToCopyValues[] = $customGroup['table_name'];
1795 return $customTableToCopyValues;
1799 * Get fields in the contact table suitable for merging.
1802 * Array of field names to be potentially merged.
1804 public static function getContactFields() {
1805 $contactFields = CRM_Contact_DAO_Contact
::fields();
1806 $invalidFields = array(
1813 'primary_contact_id',
1817 foreach ($contactFields as $field => $value) {
1818 if (in_array($field, $invalidFields)) {
1819 unset($contactFields[$field]);
1822 return array_keys($contactFields);
1826 * Added for CRM-12695
1827 * Based on the contactID provided
1828 * add/update membership(s) to related contacts
1830 * @param int $contactID
1832 public static function addMembershipToRealtedContacts($contactID) {
1833 $dao = new CRM_Member_DAO_Membership();
1834 $dao->contact_id
= $contactID;
1838 //checks membership of contact itself
1839 while ($dao->fetch()) {
1840 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1841 if ($relationshipTypeId) {
1842 $membershipParams = array(
1844 'contact_id' => $dao->contact_id
,
1845 'membership_type_id' => $dao->membership_type_id
,
1846 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1847 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1848 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1849 'source' => $dao->source
,
1850 'status_id' => $dao->status_id
,
1852 // create/update membership(s) for related contact(s)
1853 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1854 } // end of if relationshipTypeId
1859 * Add custom tables that extend contacts to the list of contact references.
1861 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
1862 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
1863 * - the down side is it is not cached.
1865 * Further changes should be include tests in the CRM_Core_MergerTest class
1866 * to ensure that disabled, subtype, multiple etc groups are still captured.
1868 * @param array $cidRefs
1870 public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
1871 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
1872 $customValueTables->find();
1873 while ($customValueTables->fetch()) {
1874 $cidRefs[$customValueTables->table_name
] = array('entity_id');
1879 * Create activities tracking the merge on affected contacts.
1881 * @param int $mainId
1882 * @param int $otherId
1884 * @throws \CiviCRM_API3_Exception
1886 public static function createMergeActivities($mainId, $otherId) {
1891 $activity = civicrm_api3('activity', 'create', array(
1892 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1894 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1895 'target_contact_id' => $mainId,
1896 'activity_type_id' => 'Contact Merged',
1897 'status_id' => 'Completed',
1899 if (civicrm_api3('Setting', 'getvalue', array('name' => 'contact_undelete', 'group' => 'CiviCRM Preferences'))) {
1900 civicrm_api3('activity', 'create', array(
1901 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1903 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1904 'target_contact_id' => $otherId,
1905 'activity_type_id' => 'Contact Deleted by Merge',
1906 'parent_id' => $activity['id'],
1907 'status_id' => 'Completed',
1913 * Get Duplicate Pairs based on a rule for a group.
1915 * @param int $rule_group_id
1916 * @param int $group_id
1917 * @param bool $reloadCacheIfEmpty
1918 * @param int $batchLimit
1919 * @param bool $isSelected
1920 * Limit to selected pairs.
1921 * @param array|string $orderByClause
1922 * @param bool $includeConflicts
1923 * @param array $criteria
1924 * Additional criteria to narrow down the merge group.
1926 * @param bool $checkPermissions
1927 * Respect logged in user permissions.
1929 * @param int $searchLimit
1930 * Limit to searching for matches against this many contacts.
1933 * Array of matches meeting the criteria.
1935 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $orderByClause = '', $includeConflicts = TRUE, $criteria = array(), $checkPermissions = TRUE, $searchLimit = 0) {
1936 $where = self
::getWhereString($batchLimit, $isSelected);
1937 $cacheKeyString = self
::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions);
1938 $join = self
::getJoinOnDedupeTable();
1939 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
1940 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1941 // If we haven't found any dupes, probably cache is empty.
1942 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1943 // until we have done some processing.
1944 CRM_Core_BAO_PrevNextCache
::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions, $searchLimit);
1945 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
1952 * Get the cache key string for the merge action.
1954 * @param int $rule_group_id
1955 * @param int $group_id
1956 * @param array $criteria
1957 * Additional criteria to narrow down the merge group.
1958 * Currently we are only supporting the key 'contact' within it.
1960 * @param bool $checkPermissions
1961 * Respect the users permissions.
1965 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = array(), $checkPermissions = TRUE) {
1966 $contactType = CRM_Dedupe_BAO_RuleGroup
::getContactTypeForRuleGroup($rule_group_id);
1967 $cacheKeyString = "merge {$contactType}";
1968 $cacheKeyString .= $rule_group_id ?
"_{$rule_group_id}" : '_0';
1969 $cacheKeyString .= $group_id ?
"_{$group_id}" : '_0';
1970 $cacheKeyString .= !empty($criteria) ?
md5(serialize($criteria)) : '_0';
1971 if ($checkPermissions) {
1972 $contactID = CRM_Core_Session
::getLoggedInContactID();
1974 // Distinguish between no permission check & no logged in user.
1975 $contactID = 'null';
1977 $cacheKeyString .= '_' . $contactID;
1980 $cacheKeyString .= '_0';
1982 return $cacheKeyString;
1986 * @param array $contact
1990 public static function getSpecialValues($contact) {
1991 $preferred_communication_method = CRM_Utils_Array
::value('preferred_communication_method', $contact);
1992 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
1993 $specialValues = array(
1994 'preferred_communication_method' => $value,
1995 'communication_style_id' => $value,
1998 if (!empty($contact['preferred_communication_method'])) {
1999 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
2000 $prefCommList = is_array($specialValues['preferred_communication_method']) ?
implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues['preferred_communication_method']) : $specialValues['preferred_communication_method'];
2001 $specialValues['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
2004 'preferred_communication_method' => array(
2005 'newName' => 'preferred_communication_method_display',
2006 'groupName' => 'preferred_communication_method',
2009 CRM_Core_OptionGroup
::lookupValues($specialValues, $names);
2011 if (!empty($contact['communication_style'])) {
2012 $specialValues['communication_style_id_display'] = $contact['communication_style'];
2014 return $specialValues;
2018 * Get the metadata for the merge fields.
2020 * This is basically the contact metadata, augmented with fields to
2021 * represent email greeting, postal greeting & addressee.
2025 public static function getMergeFieldsMetadata() {
2026 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['merge_fields_metadata'])) {
2027 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
2029 $fields = CRM_Contact_DAO_Contact
::fields();
2030 static $optionValueFields = array();
2031 if (empty($optionValueFields)) {
2032 $optionValueFields = CRM_Core_OptionValue
::getFields();
2034 foreach ($optionValueFields as $field => $params) {
2035 $fields[$field]['title'] = $params['title'];
2037 \Civi
::$statics[__CLASS__
]['merge_fields_metadata'] = $fields;
2038 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
2042 * Get the details of the contact to be merged.
2044 * @param int $contact_id
2048 * @throws CRM_Core_Exception
2050 public static function getMergeContactDetails($contact_id) {
2052 'contact_id' => $contact_id,
2054 'return' => array_merge(array('display_name'), self
::getContactFields()),
2056 $result = civicrm_api('contact', 'get', $params);
2058 // CRM-18480: Cancel the process if the contact is already deleted
2059 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
2060 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', array(
2065 return $result['values'][$contact_id];
2071 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
2073 * The data is in the format received from the merge form (which is a fairly confusing format).
2075 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
2076 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
2077 * been calculated and before saving because
2078 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
2079 * - passing to a hook right before save means calculations only have to be done once
2080 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
2083 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
2084 * is likely to be significant data in merge hooks.
2086 * @param int $mainId
2087 * @param int $otherId
2088 * @param array $locationMigrationInfo
2089 * Portion of the migration_info that holds location migration information.
2091 * @param array $migrationInfo
2092 * Migration info for the merge. This is passed to the hook as informational only.
2094 public static function mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo) {
2095 foreach ($locationMigrationInfo as $key => $value) {
2096 $locField = explode('_', $key);
2097 $fieldName = $locField[2];
2098 $fieldCount = $locField[3];
2100 // Set up the operation type (add/overwrite)
2101 // Ignore operation for websites
2102 // @todo Tidy this up
2104 if ($fieldName != 'website') {
2105 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
2107 // default operation is overwrite.
2111 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
2113 $blocksDAO = array();
2115 // @todo Handle OpenID (not currently in API).
2116 if (!empty($locBlocks)) {
2117 $locationBlocks = self
::getLocationBlockInfo();
2119 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
2120 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
2122 foreach ($locBlocks as $name => $block) {
2123 $blocksDAO[$name] = array('delete' => array(), 'update' => array());
2124 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
2127 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
2128 $changePrimary = FALSE;
2129 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
2130 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
2132 foreach ($block as $blkCount => $values) {
2133 $otherBlockId = CRM_Utils_Array
::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
2134 $mainBlockId = CRM_Utils_Array
::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
2135 if (!$otherBlockId) {
2139 // For the block which belongs to other-contact, link the location block to main-contact
2140 $otherBlockDAO = new $daoName();
2141 $otherBlockDAO->contact_id
= $mainId;
2143 // Get the ID of this block on the 'other' contact, otherwise skip
2144 $otherBlockDAO->id
= $otherBlockId;
2146 // Add/update location and type information from the form, if applicable
2147 if ($locationBlocks[$name]['hasLocation']) {
2148 $locTypeId = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2149 $otherBlockDAO->location_type_id
= $locTypeId;
2151 if ($locationBlocks[$name]['hasType']) {
2152 $typeTypeId = CRM_Utils_Array
::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2153 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
2156 // If we're deliberately setting this as primary then add the flag
2157 // and remove it from the current primary location (if there is one).
2158 // But only once for each entity.
2159 $set_primary = CRM_Utils_Array
::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
2160 if (!$changePrimary && $set_primary == "1") {
2161 $otherBlockDAO->is_primary
= 1;
2162 if ($primaryDAOId) {
2163 $removePrimaryDAO = new $daoName();
2164 $removePrimaryDAO->id
= $primaryDAOId;
2165 $removePrimaryDAO->is_primary
= 0;
2166 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
2168 $changePrimary = TRUE;
2170 // Otherwise, if main contact already has primary, set it to 0.
2171 elseif ($primaryDAOId) {
2172 $otherBlockDAO->is_primary
= 0;
2175 // If the main contact already has a billing location, set this to 0.
2176 if ($billingDAOId) {
2177 $otherBlockDAO->is_billing
= 0;
2180 $operation = CRM_Utils_Array
::value('operation', $values, 2);
2181 // overwrite - need to delete block which belongs to main-contact.
2182 if (!empty($mainBlockId) && ($operation == 2)) {
2183 $deleteDAO = new $daoName();
2184 $deleteDAO->id
= $mainBlockId;
2185 $deleteDAO->find(TRUE);
2187 // if we about to delete a primary / billing block, set the flags for new block
2188 // that we going to assign to main-contact
2189 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
2190 $otherBlockDAO->is_primary
= 1;
2192 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
2193 $otherBlockDAO->is_billing
= 1;
2195 $blocksDAO[$name]['delete'][$deleteDAO->id
] = $deleteDAO;
2197 $blocksDAO[$name]['update'][$otherBlockDAO->id
] = $otherBlockDAO;
2202 CRM_Utils_Hook
::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2203 foreach ($blocksDAO as $blockDAOs) {
2204 if (!empty($blockDAOs['update'])) {
2205 foreach ($blockDAOs['update'] as $blockDAO) {
2209 if (!empty($blockDAOs['delete'])) {
2210 foreach ($blockDAOs['delete'] as $blockDAO) {
2211 $blockDAO->delete();
2218 * Dedupe a pair of contacts.
2220 * @param array $migrationInfo
2221 * @param array $resultStats
2222 * @param array $deletedContacts
2223 * @param string $mode
2224 * @param bool $checkPermissions
2225 * @param int $mainId
2226 * @param int $otherId
2227 * @param string $cacheKeyString
2229 protected static function dedupePair(&$migrationInfo, &$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) {
2231 // go ahead with merge if there is no conflict
2232 $conflicts = array();
2233 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2234 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2235 $resultStats['merged'][] = array(
2236 'main_id' => $mainId,
2237 'other_id' => $otherId,
2239 $deletedContacts[] = $otherId;
2242 $resultStats['skipped'][] = array(
2243 'main_id' => $mainId,
2244 'other_id' => $otherId,
2248 // store any conflicts
2249 if (!empty($conflicts)) {
2250 foreach ($conflicts as $key => $dnc) {
2251 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
2253 CRM_Core_BAO_PrevNextCache
::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
2256 // delete entry from PrevNextCache table so we don't consider the pair next time
2257 // pair may have been flipped, so make sure we delete using both orders
2258 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
2261 CRM_Core_DAO
::freeResult();