3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
35 class CRM_Dedupe_Merger
{
38 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
39 * FIXME: the sub-pages references by the URLs should
40 * be loaded dynamically on the merge form instead
43 public static function relTables() {
46 $config = CRM_Core_Config
::singleton();
47 if ($config->userSystem
->is_drupal
) {
48 $userRecordUrl = CRM_Utils_System
::url('user/%ufid');
49 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
51 elseif ($config->userFramework
== 'Joomla') {
52 $userRecordUrl = $config->userFrameworkVersion
> 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';
53 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
58 'rel_table_contributions' => array(
59 'title' => ts('Contributions'),
60 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
61 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
63 'rel_table_contribution_page' => array(
64 'title' => ts('Contribution Pages'),
65 'tables' => array('civicrm_contribution_page'),
66 'url' => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
68 'rel_table_memberships' => array(
69 'title' => ts('Memberships'),
70 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
71 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
73 'rel_table_participants' => array(
74 'title' => ts('Participants'),
75 'tables' => array('civicrm_participant'),
76 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
78 'rel_table_events' => array(
79 'title' => ts('Events'),
80 'tables' => array('civicrm_event'),
81 'url' => CRM_Utils_System
::url('civicrm/event/manage', 'reset=1&cid=$cid'),
83 'rel_table_activities' => array(
84 'title' => ts('Activities'),
85 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
86 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
88 'rel_table_relationships' => array(
89 'title' => ts('Relationships'),
90 'tables' => array('civicrm_relationship'),
91 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
93 'rel_table_custom_groups' => array(
94 'title' => ts('Custom Groups'),
95 'tables' => array('civicrm_custom_group'),
96 'url' => CRM_Utils_System
::url('civicrm/admin/custom/group', 'reset=1'),
98 'rel_table_uf_groups' => array(
99 'title' => ts('Profiles'),
100 'tables' => array('civicrm_uf_group'),
101 'url' => CRM_Utils_System
::url('civicrm/admin/uf/group', 'reset=1'),
103 'rel_table_groups' => array(
104 'title' => ts('Groups'),
105 'tables' => array('civicrm_group_contact'),
106 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
108 'rel_table_notes' => array(
109 'title' => ts('Notes'),
110 'tables' => array('civicrm_note'),
111 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
113 'rel_table_tags' => array(
114 'title' => ts('Tags'),
115 'tables' => array('civicrm_entity_tag'),
116 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
118 'rel_table_mailings' => array(
119 'title' => ts('Mailings'),
120 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
121 'url' => CRM_Utils_System
::url('civicrm/mailing', 'reset=1&force=1&cid=$cid'),
123 'rel_table_cases' => array(
124 'title' => ts('Cases'),
125 'tables' => array('civicrm_case_contact'),
126 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
128 'rel_table_grants' => array(
129 'title' => ts('Grants'),
130 'tables' => array('civicrm_grant'),
131 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
133 'rel_table_pcp' => array(
134 'title' => ts('PCPs'),
135 'tables' => array('civicrm_pcp'),
136 'url' => CRM_Utils_System
::url('civicrm/contribute/pcp/manage', 'reset=1'),
138 'rel_table_pledges' => array(
139 'title' => ts('Pledges'),
140 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
141 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
143 'rel_table_users' => array(
145 'tables' => array('civicrm_uf_match'),
146 'url' => $userRecordUrl,
150 $relTables +
= self
::getMultiValueCustomSets('relTables');
152 // Allow hook_civicrm_merge() to adjust $relTables
153 CRM_Utils_Hook
::merge('relTables', $relTables);
159 * Returns the related tables groups for which a contact has any info entered.
161 public static function getActiveRelTables($cid) {
165 $relTables = self
::relTables();
166 $cidRefs = self
::cidRefs();
167 $eidRefs = self
::eidRefs();
168 foreach ($relTables as $group => $params) {
170 foreach ($params['tables'] as $table) {
171 if (isset($cidRefs[$table])) {
172 foreach ($cidRefs[$table] as $field) {
173 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
176 if (isset($eidRefs[$table])) {
177 foreach ($eidRefs[$table] as $entityTable => $entityId) {
178 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
181 foreach ($sqls as $sql) {
182 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
188 return array_unique($groups);
192 * Return tables and their fields referencing civicrm_contact.contact_id explicitly
194 public static function cidRefs() {
201 FROM information_schema.key_column_usage
203 referenced_table_schema = database() AND
204 referenced_table_name = 'civicrm_contact' AND
205 referenced_column_name = 'id';
207 $dao = CRM_Core_DAO
::executeQuery($sql);
208 while ($dao->fetch()) {
209 $cidRefs[$dao->table_name
][] = $dao->column_name
;
212 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
213 $cidRefs['civicrm_entity_tag'][] = 'entity_id';
216 // Allow hook_civicrm_merge() to adjust $cidRefs
217 CRM_Utils_Hook
::merge('cidRefs', $cidRefs);
223 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
225 public static function eidRefs() {
228 // FIXME: this should be generated dynamically from the schema
229 // tables that reference contacts with entity_{id,table}
231 'civicrm_acl' => array('entity_table' => 'entity_id'),
232 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
233 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
234 'civicrm_log' => array('entity_table' => 'entity_id'),
235 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
236 'civicrm_note' => array('entity_table' => 'entity_id'),
239 // Allow hook_civicrm_merge() to adjust $eidRefs
240 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
246 * Return tables using locations.
248 public static function locTables() {
251 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
253 // Allow hook_civicrm_merge() to adjust $locTables
254 CRM_Utils_Hook
::merge('locTables', $locTables);
260 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
261 * @param string $request
262 * 'relTables' or 'cidRefs'.
265 public static function getMultiValueCustomSets($request) {
267 if ($data === NULL) {
269 'relTables' => array(),
270 'cidRefs' => array(),
272 $result = civicrm_api3('custom_group', 'get', array(
274 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
275 'return' => array('id', 'title', 'table_name', 'style'),
277 foreach ($result['values'] as $custom) {
278 $data['cidRefs'][$custom['table_name']] = array('entity_id');
279 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
280 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
281 'title' => $custom['title'],
282 'tables' => array($custom['table_name']),
283 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
287 return $data[$request];
291 * Tables which require custom processing should declare functions to call here.
292 * Doing so will override normal processing.
294 public static function cpTables() {
298 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
299 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
300 // Empty array == do nothing - this table is handled by mergeGroupContact
301 'civicrm_subscription_history' => array(),
302 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
309 * Return payment related table.
311 public static function paymentTables() {
314 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
321 * Return payment update Query.
323 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
325 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
329 $paymentTables = self
::paymentTables();
330 if (!in_array($tableName, $paymentTables)) {
334 switch ($tableName) {
335 case 'civicrm_pledge':
337 UPDATE IGNORE civicrm_contribution contribution
338 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
339 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
340 SET contribution.contact_id = $mainContactId
341 WHERE pledge.contact_id = $otherContactId";
344 case 'civicrm_membership':
346 UPDATE IGNORE civicrm_contribution contribution
347 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
348 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
349 SET contribution.contact_id = $mainContactId
350 WHERE membership.contact_id = $otherContactId";
353 case 'civicrm_participant':
355 UPDATE IGNORE civicrm_contribution contribution
356 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
357 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
358 SET contribution.contact_id = $mainContactId
359 WHERE participant.contact_id = $otherContactId";
368 * @param int $otherId
369 * @param string $tableName
370 * @param array $tableOperations
371 * @param string $mode
375 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
377 if (!$tableName ||
!$mainId ||
!$otherId) {
381 switch ($tableName) {
382 case 'civicrm_membership':
383 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
386 if ($mode == 'add') {
388 DELETE membership1.* FROM civicrm_membership membership1
389 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
390 AND membership1.contact_id = {$mainId}
391 AND membership2.contact_id = {$otherId} ";
393 if ($mode == 'payment') {
395 DELETE contribution.* FROM civicrm_contribution contribution
396 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
397 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
398 AND membership1.contact_id = {$mainId}
399 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
400 AND membership2.contact_id = {$otherId}";
404 case 'civicrm_uf_match':
405 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
406 // failing to meet intended result. Therefore we introduce this additonal query:
407 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
415 * Based on the provided two contact_ids and a set of tables, move the
416 * belongings of the other contact to the main one.
419 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
420 $cidRefs = self
::cidRefs();
421 $eidRefs = self
::eidRefs();
422 $cpTables = self
::cpTables();
423 $paymentTables = self
::paymentTables();
424 $membershipMerge = FALSE; // CRM-12695
426 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
427 if ($tables !== FALSE) {
428 // if there are specific tables, sanitize the list
429 $affected = array_unique(array_intersect($affected, $tables));
432 // if there aren't any specific tables, don't affect the ones handled by relTables()
433 // also don't affect tables in locTables() CRM-15658
434 $relTables = self
::relTables();
435 $handled = self
::locTables();
436 foreach ($relTables as $params) {
437 $handled = array_merge($handled, $params['tables']);
439 $affected = array_diff($affected, $handled);
442 * Set $membershipMerge flag only once
443 * while doing contact related migration
444 * to call addMembershipToRealtedContacts()
445 * function only once.
446 * Since the current function (moveContactBelongings) is called twice
447 * with & without parameters $tables & $tableOperations
449 // retrieve main contact's related table(s)
450 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
451 // check if membership table exists in main contact's related table(s)
452 if (in_array('rel_table_memberships', $activeMainRelTables)) {
453 $membershipMerge = TRUE; // set membership flag - CRM-12695
457 $mainId = (int) $mainId;
458 $otherId = (int) $otherId;
461 foreach ($affected as $table) {
462 // Call custom processing function for objects that require it
463 if (isset($cpTables[$table])) {
464 foreach ($cpTables[$table] as $className => $fnName) {
465 $className::$fnName($mainId, $otherId, $sqls);
467 // Skip normal processing
471 // use UPDATE IGNORE + DELETE query pair to skip on situations when
472 // there's a UNIQUE restriction on ($field, some_other_field) pair
473 if (isset($cidRefs[$table])) {
474 foreach ($cidRefs[$table] as $field) {
475 // carry related contributions CRM-5359
476 if (in_array($table, $paymentTables)) {
477 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
478 $sqls = array_merge($sqls, $paymentSqls);
480 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
481 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
482 $sqls = array_merge($sqls, $payOprSqls);
486 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
487 $sqls = array_merge($sqls, $preOperationSqls);
489 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
490 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
493 if (isset($eidRefs[$table])) {
494 foreach ($eidRefs[$table] as $entityTable => $entityId) {
495 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
496 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
501 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
502 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
504 // call the SQL queries in one transaction
505 $transaction = new CRM_Core_Transaction();
506 foreach ($sqls as $sql) {
507 CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, TRUE);
510 if ($membershipMerge) {
511 // call to function adding membership to related contacts
512 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
514 $transaction->commit();
518 * Find differences between contacts.
522 * @param array $other
527 public static function findDifferences($main, $other) {
529 'contact' => array(),
532 foreach (self
::getContactFields() as $validField) {
533 if (CRM_Utils_Array
::value($validField, $main) != CRM_Utils_Array
::value($validField, $other)) {
534 $result['contact'][] = $validField;
538 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
539 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
540 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
541 foreach ($keys as $key) {
542 // Exclude multi-value fields CRM-13836
543 if (strpos($key, '_')) {
546 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
547 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
548 if ($key1 != $key2) {
549 $result['custom'][] = $key;
556 * Batch merge a set of contacts based on rule-group and group.
562 * @param string $mode
563 * Helps decide how to behave when there are conflicts.
564 * A 'safe' value skips the merge if there are any un-resolved conflicts.
565 * Does a force merge otherwise.
566 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
567 * Wether to let api decide which contact to retain and which to delete.
568 * @param bool $redirectForPerformance
572 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $redirectForPerformance = FALSE) {
573 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
574 $cacheKeyString = "merge {$contactType}";
575 $cacheKeyString .= $rgid ?
"_{$rgid}" : '_0';
576 $cacheKeyString .= $gid ?
"_{$gid}" : '_0';
577 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
578 pn.entity_id2 = de.contact_id2 )";
580 $limit = $redirectForPerformance ?
75 : 1;
581 $where = "de.id IS NULL LIMIT {$limit}";
583 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
584 if (empty($dupePairs) && !$redirectForPerformance) {
585 // If we haven't found any dupes, probably cache is empty.
586 // Try filling cache and give another try.
587 CRM_Core_BAO_PrevNextCache
::refillCache($rgid, $gid, $cacheKeyString);
588 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
591 $cacheParams = array(
592 'cache_key_string' => $cacheKeyString,
596 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
600 * Merge given set of contacts. Performs core operation.
602 * @param array $dupePairs
603 * Set of pair of contacts for whom merge is to be done.
604 * @param array $cacheParams
605 * Prev-next-cache params based on which next pair of contacts are computed.
606 * Generally used with batch-merge.
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.
610 * Does a force merge otherwise (aggressive mode).
611 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
612 * Wether to let api decide which contact to retain and which to delete.
615 * @param bool $redirectForPerformance
619 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
620 $autoFlip = TRUE, $redirectForPerformance = FALSE
622 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
623 $resultStats = array('merged' => array(), 'skipped' => array());
625 // we don't want dupe caching to get reset after every-merge, and therefore set the
626 // doNotResetCache flag
627 $config = CRM_Core_Config
::singleton();
628 $config->doNotResetCache
= 1;
630 while (!empty($dupePairs)) {
631 foreach ($dupePairs as $dupes) {
632 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
633 $mainId = $dupes['dstID'];
634 $otherId = $dupes['srcID'];
635 $isAutoFlip = CRM_Utils_Array
::value('auto_flip', $dupes, $autoFlip);
636 // if we can, make sure that $mainId is the one with lower id number
637 if ($isAutoFlip && ($mainId > $otherId)) {
638 $mainId = $dupes['srcID'];
639 $otherId = $dupes['dstID'];
641 if (!$mainId ||
!$otherId) {
646 // Generate var $migrationInfo. The variable structure is exactly same as
647 // $formValues submitted during a UI merge for a pair of contacts.
648 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId);
650 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
652 // add additional details that we might need to resolve conflicts
653 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
654 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
655 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
656 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
658 // go ahead with merge if there is no conflict
659 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode)) {
660 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo);
661 $resultStats['merged'][] = array('main_id' => $mainId, 'other_id' => $otherId);
664 $resultStats['skipped'][] = array('main_id' => $mainId, 'other_id' => $otherId);
667 // delete entry from PrevNextCache table so we don't consider the pair next time
668 // pair may have been flipped, so make sure we delete using both orders
669 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString);
670 CRM_Core_BAO_PrevNextCache
::deletePair($otherId, $mainId, $cacheKeyString);
672 CRM_Core_DAO
::freeResult();
673 unset($rowsElementsAndInfo, $migrationInfo);
676 if ($cacheKeyString && !$redirectForPerformance) {
677 // retrieve next pair of dupes
678 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
679 $cacheParams['join'],
680 $cacheParams['where']
684 // do not proceed. Terminate the loop
692 * A function which uses various rules / algorithms for choosing which contact to bias to
693 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
696 * Main contact with whom merge has to happen.
697 * @param int $otherId
698 * Duplicate contact which would be deleted after merge operation.
699 * @param array $migrationInfo
700 * Array of information about which elements to merge.
701 * @param string $mode
702 * Helps decide how to behave when there are conflicts.
703 * A 'safe' value skips the merge if there are any un-resolved conflicts.
704 * Does a force merge otherwise (aggressive mode).
708 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe') {
709 $conflicts = array();
710 $migrationData = array(
711 'old_migration_info' => $migrationInfo,
714 $allLocationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
716 foreach ($migrationInfo as $key => $val) {
717 if ($val === "null") {
718 // Rule: no overwriting with empty values in any mode
719 unset($migrationInfo[$key]);
722 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
723 substr($key, 0, 12) == 'move_custom_'
726 // Rule: if both main-contact has other-contact, let $mode decide if to merge a
727 // particular field or not
728 if (!empty($migrationInfo['rows'][$key]['main'])) {
729 // if main also has a value its a conflict
730 if ($mode == 'safe') {
731 // note it down & lets wait for response from the hook.
732 // For no response skip this merge
733 $conflicts[$key] = NULL;
735 elseif ($mode == 'aggressive') {
736 // let the main-field be overwritten
741 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
742 $locField = explode('_', $key);
743 $fieldName = $locField[2];
744 $fieldCount = $locField[3];
746 // Rule: resolve address conflict if any -
747 if ($fieldName == 'address') {
748 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
749 if (!empty($migrationInfo['main_loc_block']) &&
750 array_key_exists("main_address{$mainNewLocTypeId}", $migrationInfo['main_loc_block'])) {
751 // main loc already has some address for the loc-type. Its a overwrite situation.
752 // look for next available loc-type
754 foreach ($allLocationTypes as $typeId => $typeLabel) {
755 if (!array_key_exists("main_address{$typeId}", $migrationInfo['main_loc_block'])) {
756 $newTypeId = $typeId;
760 // try insert address at new available loc-type
761 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
763 elseif ($mode == 'safe') {
764 // note it down & lets wait for response from the hook.
765 // For no response skip this merge
766 $conflicts[$key] = NULL;
768 elseif ($mode == 'aggressive') {
769 // let the loc-type-id be same as that of other-contact & go ahead
770 // with merge assuming aggressive mode
775 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
776 // for loc blocks other than address like email, phone .. if values are same no point in merging
777 // and adding redundant value
778 unset($migrationInfo[$key]);
783 // A hook to implement other algorithms for choosing which contact to bias to when
784 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
785 // merge happens with new values filled in here. For a particular field / row not to be merged
786 // field should be unset from fields_in_conflict.
787 $migrationData['fields_in_conflict'] = $conflicts;
788 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
789 $conflicts = $migrationData['fields_in_conflict'];
791 if (!empty($conflicts)) {
792 foreach ($conflicts as $key => $val) {
793 if ($val === NULL and $mode == 'safe') {
794 // un-resolved conflicts still present. Lets skip this merge.
798 // copy over the resolved values
799 $migrationInfo[$key] = $val;
807 * A function to build an array of information required by merge function and the merge UI.
810 * Main contact with whom merge has to happen.
811 * @param int $otherId
812 * Duplicate contact which would be deleted after merge operation.
814 * @return array|bool|int
816 public static function getRowsElementsAndInfo($mainId, $otherId) {
817 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
820 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
822 'contact_id' => $cid,
824 'return' => array_merge(array('display_name'), self
::getContactFields()),
826 $result = civicrm_api('contact', 'get', $params);
828 if (empty($result['values'][$cid]['contact_type'])) {
831 $
$moniker = $result['values'][$cid];
834 static $fields = array();
835 if (empty($fields)) {
836 $fields = CRM_Contact_DAO_Contact
::fields();
837 CRM_Core_DAO
::freeResult();
840 // FIXME: there must be a better way
841 foreach (array('main', 'other') as $moniker) {
842 $contact = &$
$moniker;
843 $preferred_communication_method = CRM_Utils_array
::value('preferred_communication_method', $contact);
844 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
845 $specialValues[$moniker] = array(
846 'preferred_communication_method' => $value,
847 'communication_style_id' => $value,
850 if (!empty($contact['preferred_communication_method'])) {
851 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
852 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
853 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
856 'preferred_communication_method' => array(
857 'newName' => 'preferred_communication_method_display',
858 'groupName' => 'preferred_communication_method',
861 CRM_Core_OptionGroup
::lookupValues($specialValues[$moniker], $names);
863 if (!empty($contact['communication_style'])) {
864 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
868 static $optionValueFields = array();
869 if (empty($optionValueFields)) {
870 $optionValueFields = CRM_Core_OptionValue
::getFields();
872 foreach ($optionValueFields as $field => $params) {
873 $fields[$field]['title'] = $params['title'];
876 $diffs = self
::findDifferences($main, $other);
878 $rows = $elements = $relTableElements = $migrationInfo = array();
880 $genders = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id');
882 foreach ($diffs['contact'] as $field) {
883 if ($field == 'contact_sub_type') {
884 // CRM-15681 don't display sub-types in UI
887 foreach (array('main', 'other') as $moniker) {
888 $contact = &$
$moniker;
889 $value = CRM_Utils_Array
::value($field, $contact);
890 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
891 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
893 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
894 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
896 $value = str_replace('-', '', $value);
897 $label = CRM_Utils_Date
::customFormat($label);
903 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
904 if ($label === '0') {
907 if ($label === '1') {
911 elseif ($field == 'individual_prefix' ||
$field == 'prefix_id') {
912 $label = CRM_Utils_Array
::value('individual_prefix', $contact);
913 $value = CRM_Utils_Array
::value('prefix_id', $contact);
914 $field = 'prefix_id';
916 elseif ($field == 'individual_suffix' ||
$field == 'suffix_id') {
917 $label = CRM_Utils_Array
::value('individual_suffix', $contact);
918 $value = CRM_Utils_Array
::value('suffix_id', $contact);
919 $field = 'suffix_id';
921 elseif ($field == 'gender_id' && !empty($value)) {
922 $label = $genders[$value];
924 elseif ($field == 'current_employer_id' && !empty($value)) {
925 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
927 $rows["move_$field"][$moniker] = $label;
928 if ($moniker == 'other') {
930 if ($value === NULL ||
$value == '') {
933 if ($value === 0 or $value === '0') {
936 if (is_array($value) && empty($value[1])) {
939 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
940 $migrationInfo["move_$field"] = $value;
943 $rows["move_$field"]['title'] = $fields[$field]['title'];
946 // handle location blocks.
947 $locationBlocks = array('email', 'phone', 'address');
948 $locations = array();
950 foreach ($locationBlocks as $block) {
951 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
953 $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
954 $count = $values['count'];
957 foreach ($values['values'] as $value) {
958 if ($block == 'address') {
959 CRM_Core_BAO_Address
::fixAddress($value);
960 $display = CRM_Utils_Address
::format($value);
961 $locations[$moniker][$block][$cnt] = $value;
962 $locations[$moniker][$block][$cnt]['display'] = $display;
965 $locations[$moniker][$block][$cnt] = $value;
973 if ($block == 'address') {
974 CRM_Core_BAO_Address
::fixAddress($values['values'][$id]);
975 $display = CRM_Utils_Address
::format($values['values'][$id]);
976 $locations[$moniker][$block][$cnt] = $values['values'][$id];
977 $locations[$moniker][$block][$cnt]['display'] = $display;
980 $locations[$moniker][$block][$cnt] = $values['values'][$id];
987 $allLocationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
989 $mainLocBlock = $locBlockIds = array();
990 $locBlockIds['main'] = $locBlockIds['other'] = array();
991 foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
992 $name = strtolower($block);
993 foreach (array('main', 'other') as $moniker) {
994 $locIndex = CRM_Utils_Array
::value($moniker, $locations);
995 $blockValue = CRM_Utils_Array
::value($name, $locIndex, array());
996 if (empty($blockValue)) {
997 $locValue[$moniker][$name] = 0;
998 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
1001 $locValue[$moniker][$name] = TRUE;
1002 foreach ($blockValue as $count => $blkValues) {
1004 $locTypeId = $blkValues['location_type_id'];
1005 if ($name == 'im') {
1008 if ($name == 'address') {
1009 $fldName = 'display';
1011 $locLabel[$moniker][$name][$count] = CRM_Utils_Array
::value($fldName,
1014 $locTypes[$moniker][$name][$count] = $locTypeId;
1015 if ($moniker == 'main' && in_array($name, $locationBlocks)) {
1016 $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array
::value($fldName,
1019 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
1022 $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
1028 if ($locValue['other'][$name] != 0) {
1029 foreach ($locLabel['other'][$name] as $count => $value) {
1030 $locTypeId = $locTypes['other'][$name][$count];
1031 $rows["move_location_{$name}_$count"]['other'] = $value;
1032 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array
::value($count,
1033 $locLabel['main'][$name]
1035 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
1039 3 => $allLocationTypes[$locTypeId],
1043 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
1044 $migrationInfo["move_location_{$name}_{$count}"] = 1;
1046 // make sure default location type is always on top
1047 $mainLocTypeId = CRM_Utils_Array
::value($count, $locTypes['main'][$name], $locTypeId);
1048 $locTypeValues = $allLocationTypes;
1049 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
1050 unset($locTypeValues[$mainLocTypeId]);
1052 // keep 1-1 mapping for address - location type.
1054 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
1055 $js = array('onChange' => "mergeBlock('$name', this, $count );");
1057 $elements[] = array(
1059 "location[{$name}][$count][locTypeId]",
1061 $defaultLocType +
$locTypeValues,
1064 // keep location-type-id same as that of other-contact
1065 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
1067 if ($name != 'address') {
1068 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
1069 // always use add operation
1070 $migrationInfo['location'][$name][$count]['operation'] = 1;
1076 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1077 $config = CRM_Core_Config
::singleton();
1078 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1082 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1083 $mainUser = user_load($mainUfId);
1085 elseif ($config->userFramework
== 'Joomla') {
1086 $mainUser = JFactory
::getUser($mainUfId);
1089 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1093 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1094 $otherUser = user_load($otherUfId);
1096 elseif ($config->userFramework
== 'Joomla') {
1097 $otherUser = JFactory
::getUser($otherUfId);
1101 $relTables = CRM_Dedupe_Merger
::relTables();
1102 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1103 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1104 foreach ($relTables as $name => $null) {
1105 if (!in_array($name, $activeRelTables) &&
1106 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1108 unset($relTables[$name]);
1112 $relTableElements[] = array('checkbox', "move_$name");
1113 $migrationInfo["move_$name"] = 1;
1115 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1116 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1117 if ($name == 'rel_table_users') {
1118 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1119 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1120 $find = array('$ufid', '$ufname');
1122 $replace = array($mainUfId, $mainUser->name
);
1123 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1126 $replace = array($otherUfId, $otherUser->name
);
1127 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1130 if ($name == 'rel_table_memberships') {
1131 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1132 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1135 foreach ($relTables as $name => $null) {
1136 $relTables["move_$name"] = $relTables[$name];
1137 unset($relTables[$name]);
1140 // handle custom fields
1141 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $mainId, -1,
1142 CRM_Utils_Array
::value('contact_sub_type', $main)
1144 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $otherId, -1,
1145 CRM_Utils_Array
::value('contact_sub_type', $other)
1147 CRM_Core_DAO
::freeResult();
1149 foreach ($otherTree as $gid => $group) {
1150 $foundField = FALSE;
1151 if (!isset($group['fields'])) {
1155 foreach ($group['fields'] as $fid => $field) {
1156 if (in_array($fid, $diffs['custom'])) {
1158 $rows["custom_group_$gid"]['title'] = $group['title'];
1161 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1162 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1163 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1169 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1170 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1171 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1174 if ($values['data'] === 0 ||
$values['data'] === '0') {
1175 $values['data'] = $qfZeroBug;
1177 $value = ($values['data']) ?
$values['data'] : $value;
1180 $rows["move_custom_$fid"]['title'] = $field['label'];
1182 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1183 $migrationInfo["move_custom_$fid"] = $value;
1189 'elements' => $elements,
1190 'rel_table_elements' => $relTableElements,
1191 'main_loc_block' => $mainLocBlock,
1192 'rel_tables' => $relTables,
1193 'main_details' => $main,
1194 'other_details' => $other,
1195 'migration_info' => $migrationInfo,
1198 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1199 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1205 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1206 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1207 * A superset of moveContactBelongings() function.
1209 * @param int $mainId
1210 * Main contact with whom merge has to happen.
1211 * @param int $otherId
1212 * Duplicate contact which would be deleted after merge operation.
1214 * @param $migrationInfo
1218 public static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1219 if (empty($migrationInfo)) {
1223 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1224 $relTables = CRM_Dedupe_Merger
::relTables();
1225 $moveTables = $locBlocks = $tableOperations = array();
1226 foreach ($migrationInfo as $key => $value) {
1227 if ($value == $qfZeroBug) {
1230 if ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) ||
1231 substr($key, 0, 12) == 'move_custom_') &&
1234 $submitted[substr($key, 5)] = $value;
1236 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1237 $locField = explode('_', $key);
1238 $fieldName = $locField[2];
1239 $fieldCount = $locField[3];
1240 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1241 // default operation is overwrite.
1246 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1247 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1249 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1250 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1251 if (array_key_exists('operation', $migrationInfo)) {
1252 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1253 if (array_key_exists($key, $migrationInfo['operation'])) {
1254 $tableOperations[$table] = $migrationInfo['operation'][$key];
1261 // **** Do location related migration:
1262 if (!empty($locBlocks)) {
1263 $locComponent = array(
1267 'openid' => 'OpenID',
1268 'address' => 'Address',
1271 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
1272 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
1274 foreach ($locBlocks as $name => $block) {
1275 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1278 $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
1279 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1280 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1282 foreach ($block as $blkCount => $values) {
1283 $locTypeId = CRM_Utils_Array
::value('locTypeId', $values, 1);
1284 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1285 $otherBlockId = CRM_Utils_Array
::value($blkCount,
1286 $migrationInfo['other_details']['loc_block_ids'][$name]
1289 // keep 1-1 mapping for address - loc type.
1291 if (array_key_exists($name, $locComponent)) {
1292 $idKey = $locTypeId;
1295 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1296 $mainBlockId = CRM_Utils_Array
::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1299 if (!$otherBlockId) {
1303 // for the block which belongs to other-contact, link the contact to main-contact
1304 $otherBlockDAO = new $daoName();
1305 $otherBlockDAO->id
= $otherBlockId;
1306 $otherBlockDAO->contact_id
= $mainId;
1307 $otherBlockDAO->location_type_id
= $locTypeId;
1309 // if main contact already has primary & billing, set the flags to 0.
1310 if ($primaryDAOId) {
1311 $otherBlockDAO->is_primary
= 0;
1313 if ($billingDAOId) {
1314 $otherBlockDAO->is_billing
= 0;
1317 // overwrite - need to delete block which belongs to main-contact.
1318 if ($mainBlockId && ($operation == 2)) {
1319 $deleteDAO = new $daoName();
1320 $deleteDAO->id
= $mainBlockId;
1321 $deleteDAO->find(TRUE);
1323 // if we about to delete a primary / billing block, set the flags for new block
1324 // that we going to assign to main-contact
1325 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1326 $otherBlockDAO->is_primary
= 1;
1328 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1329 $otherBlockDAO->is_billing
= 1;
1332 $deleteDAO->delete();
1336 $otherBlockDAO->update();
1337 $otherBlockDAO->free();
1342 // **** Do tables related migrations
1343 if (!empty($moveTables)) {
1344 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1345 unset($moveTables, $tableOperations);
1348 // **** Do contact related migrations
1349 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId);
1351 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1352 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1353 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1354 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1355 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1356 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1357 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1358 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1359 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1361 // fix custom fields so they're edible by createProfileContact()
1362 static $treeCache = array();
1363 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1364 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree($migrationInfo['main_details']['contact_type'],
1365 CRM_Core_DAO
::$_nullObject, NULL, -1
1368 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1371 foreach ($cgTree as $key => $group) {
1372 if (!isset($group['fields'])) {
1375 foreach ($group['fields'] as $fid => $field) {
1376 $cFields[$fid]['attributes'] = $field;
1380 if (!isset($submitted)) {
1381 $submitted = array();
1383 foreach ($submitted as $key => $value) {
1384 if (substr($key, 0, 7) == 'custom_') {
1385 $fid = (int) substr($key, 7);
1386 if (empty($cFields[$fid])) {
1389 $htmlType = $cFields[$fid]['attributes']['html_type'];
1390 switch ($htmlType) {
1392 $customFiles[] = $fid;
1393 unset($submitted["custom_$fid"]);
1396 case 'Select Country':
1397 case 'Select State/Province':
1398 $submitted[$key] = CRM_Core_BAO_CustomField
::getDisplayValue($value, $fid, $cFields);
1402 case 'AdvMulti-Select':
1403 case 'Multi-Select':
1404 case 'Multi-Select Country':
1405 case 'Multi-Select State/Province':
1406 // Merge values from both contacts for multivalue fields, CRM-4385
1407 // get the existing custom values from db.
1408 $customParams = array('entityID' => $mainId, $key => TRUE);
1409 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1410 if (!empty($customfieldValues[$key])) {
1411 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1412 if (is_array($existingValue) && !empty($existingValue)) {
1413 $mergeValue = $submmtedCustomValue = array();
1415 $submmtedCustomValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1418 //hack to remove null and duplicate values from array.
1419 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1420 if ($v != '' && !in_array($v, $mergeValue)) {
1425 //keep state and country as array format.
1426 //for checkbox and m-select format w/ VALUE_SEPARATOR
1427 if (in_array($htmlType, array(
1432 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1434 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1437 $submitted[$key] = $mergeValue;
1441 elseif (in_array($htmlType, array(
1442 'Multi-Select Country',
1443 'Multi-Select State/Province',
1445 //we require submitted values should be in array format
1447 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1448 //hack to remove null values from array.
1449 $mergeValue = array();
1450 foreach ($mergeValueArray as $k => $v) {
1455 $submitted[$key] = $mergeValue;
1466 // **** Do file custom fields related migrations
1467 // FIXME: move this someplace else (one of the BAOs) after discussing
1468 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1469 // like, delete a file...
1471 if (!isset($customFiles)) {
1472 $customFiles = array();
1474 foreach ($customFiles as $customId) {
1475 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1477 // get the contact_id -> file_id mapping
1479 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1480 $dao = CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1481 while ($dao->fetch()) {
1482 $fileIds[$dao->entity_id
] = $dao->file_id
;
1486 // delete the main contact's file
1487 if (!empty($fileIds[$mainId])) {
1488 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1491 // move the other contact's file to main contact
1492 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1493 if (CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
1494 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1497 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1499 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1501 if (CRM_Core_DAO
::singleValueQuery("
1503 FROM civicrm_entity_file
1504 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1507 UPDATE civicrm_entity_file
1508 SET entity_id = {$mainId}
1509 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1513 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1514 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1516 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1519 // move view only custom fields CRM-5362
1520 $viewOnlyCustomFields = array();
1521 foreach ($submitted as $key => $value) {
1522 $fid = (int) substr($key, 7);
1523 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1524 $viewOnlyCustomFields[$key] = $value;
1528 // special case to set values for view only, CRM-5362
1529 if (!empty($viewOnlyCustomFields)) {
1530 $viewOnlyCustomFields['entityID'] = $mainId;
1531 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1534 // **** Delete other contact & update prev-next caching
1535 $otherParams = array(
1536 'contact_id' => $otherId,
1540 if (CRM_Core_Permission
::check('merge duplicate contacts') &&
1541 CRM_Core_Permission
::check('delete contacts')
1543 // if ext id is submitted then set it null for contact to be deleted
1544 if (!empty($submitted['external_identifier'])) {
1545 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1546 CRM_Core_DAO
::executeQuery($query);
1549 civicrm_api('contact', 'delete', $otherParams);
1550 CRM_Core_BAO_PrevNextCache
::deleteItem($otherId);
1555 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1559 // CRM-15681 merge sub_types
1560 if ($other_sub_types = CRM_Utils_array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1561 if ($main_sub_types = CRM_Utils_array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1562 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1565 $submitted['contact_sub_type'] = $other_sub_types;
1569 // **** Update contact related info for the main contact
1570 if (!empty($submitted)) {
1571 $submitted['contact_id'] = $mainId;
1573 //update current employer field
1574 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1575 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1576 $submitted['current_employer'] = $submitted['current_employer_id'];
1579 $submitted['current_employer'] = '';
1581 unset($submitted['current_employer_id']);
1584 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1585 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1586 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1588 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1589 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1592 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);
1596 CRM_Utils_Hook
::post('merge', 'Contact', $mainId, CRM_Core_DAO
::$_nullObject);
1603 * Array of field names which will be compared, so everything except ID.
1605 public static function getContactFields() {
1606 $contactFields = CRM_Contact_DAO_Contact
::fields();
1607 $invalidFields = array(
1609 'contact_is_deleted',
1615 'primary_contact_id',
1619 foreach ($contactFields as $field => $value) {
1620 if (in_array($field, $invalidFields)) {
1621 unset($contactFields[$field]);
1624 return array_keys($contactFields);
1628 * Added for CRM-12695
1629 * Based on the contactID provided
1630 * add/update membership(s) to related contacts
1632 * @param int $contactID
1634 public static function addMembershipToRealtedContacts($contactID) {
1635 $dao = new CRM_Member_DAO_Membership();
1636 $dao->contact_id
= $contactID;
1640 //checks membership of contact itself
1641 while ($dao->fetch()) {
1642 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1643 if ($relationshipTypeId) {
1644 $membershipParams = array(
1646 'contact_id' => $dao->contact_id
,
1647 'membership_type_id' => $dao->membership_type_id
,
1648 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1649 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1650 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1651 'source' => $dao->source
,
1652 'status_id' => $dao->status_id
,
1654 // create/update membership(s) for related contact(s)
1655 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1656 } // end of if relationshipTypeId