3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
35 class CRM_Dedupe_Merger
{
37 // FIXME: consider creating a common structure with cidRefs() and eidRefs()
38 // FIXME: the sub-pages references by the URLs should
39 // be loaded dynamically on the merge form instead
43 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 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 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 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 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
247 * @param string $request 'relTables' or 'cidRefs'
250 static function getMultiValueCustomSets($request) {
252 if ($data === NULL) {
254 'relTables' => array(),
255 'cidRefs' => array(),
257 $result = civicrm_api3('custom_group', 'get', array(
259 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
260 'return' => array('id', 'title', 'table_name', 'style'),
262 foreach($result['values'] as $custom) {
263 $data['cidRefs'][$custom['table_name']] = array('entity_id');
264 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
265 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
266 'title' => $custom['title'],
267 'tables' => array($custom['table_name']),
268 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
272 return $data[$request];
276 * Tables which require custom processing should declare functions to call here.
277 * Doing so will override normal processing.
279 static function cpTables() {
283 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
284 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
285 // Empty array == do nothing - this table is handled by mergeGroupContact
286 'civicrm_subscription_history' => array(),
287 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
294 * return payment related table.
296 static function paymentTables() {
299 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
306 * return payment update Query.
308 static function paymentSql($tableName, $mainContactId, $otherContactId) {
310 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
314 $paymentTables = self
::paymentTables();
315 if (!in_array($tableName, $paymentTables)) {
319 switch ($tableName) {
320 case 'civicrm_pledge':
322 UPDATE IGNORE civicrm_contribution contribution
323 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
324 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
325 SET contribution.contact_id = $mainContactId
326 WHERE pledge.contact_id = $otherContactId";
329 case 'civicrm_membership':
331 UPDATE IGNORE civicrm_contribution contribution
332 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
333 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
334 SET contribution.contact_id = $mainContactId
335 WHERE membership.contact_id = $otherContactId";
338 case 'civicrm_participant':
340 UPDATE IGNORE civicrm_contribution contribution
341 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
342 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
343 SET contribution.contact_id = $mainContactId
344 WHERE participant.contact_id = $otherContactId";
355 * @param array $tableOperations
356 * @param string $mode
360 static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
362 if (!$tableName ||
!$mainId ||
!$otherId) {
367 switch ($tableName) {
368 case 'civicrm_membership':
369 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add'])
371 if ($mode == 'add') {
373 DELETE membership1.* FROM civicrm_membership membership1
374 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
375 AND membership1.contact_id = {$mainId}
376 AND membership2.contact_id = {$otherId} ";
378 if ($mode == 'payment') {
380 DELETE contribution.* FROM civicrm_contribution contribution
381 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
382 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
383 AND membership1.contact_id = {$mainId}
384 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
385 AND membership2.contact_id = {$otherId}";
389 case 'civicrm_uf_match':
390 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
391 // failing to meet intended result. Therefore we introduce this additonal query:
392 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
400 * Based on the provided two contact_ids and a set of tables, move the
401 * belongings of the other contact to the main one.
405 static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
406 $cidRefs = self
::cidRefs();
407 $eidRefs = self
::eidRefs();
408 $cpTables = self
::cpTables();
409 $paymentTables = self
::paymentTables();
410 $membershipMerge = FALSE; // CRM-12695
412 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
413 if ($tables !== FALSE) {
414 // if there are specific tables, sanitize the list
415 $affected = array_unique(array_intersect($affected, $tables));
418 // if there aren't any specific tables, don't affect the ones handled by relTables()
419 $relTables = self
::relTables();
421 foreach ($relTables as $params) {
422 $handled = array_merge($handled, $params['tables']);
424 $affected = array_diff($affected, $handled);
427 * Set $membershipMerge flag only once
428 * while doing contact related migration
429 * to call addMembershipToRealtedContacts()
430 * function only once.
431 * Since the current function (moveContactBelongings) is called twice
432 * with & without parameters $tables & $tableOperations
434 // retrieve main contact's related table(s)
435 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
436 // check if membership table exists in main contact's related table(s)
437 if (in_array('rel_table_memberships', $activeMainRelTables)) {
438 $membershipMerge = TRUE; // set membership flag - CRM-12695
442 $mainId = (int) $mainId;
443 $otherId = (int) $otherId;
446 foreach ($affected as $table) {
447 // Call custom processing function for objects that require it
448 if (isset($cpTables[$table])) {
449 foreach ($cpTables[$table] as $className => $fnName) {
450 $className::$fnName($mainId, $otherId, $sqls);
452 // Skip normal processing
456 // use UPDATE IGNORE + DELETE query pair to skip on situations when
457 // there's a UNIQUE restriction on ($field, some_other_field) pair
458 if (isset($cidRefs[$table])) {
459 foreach ($cidRefs[$table] as $field) {
460 // carry related contributions CRM-5359
461 if (in_array($table, $paymentTables)) {
462 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
463 $sqls = array_merge($sqls, $paymentSqls);
465 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
466 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
467 $sqls = array_merge($sqls, $payOprSqls);
471 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
472 $sqls = array_merge($sqls, $preOperationSqls);
474 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
475 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
478 if (isset($eidRefs[$table])) {
479 foreach ($eidRefs[$table] as $entityTable => $entityId) {
480 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
481 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
486 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
487 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
489 // call the SQL queries in one transaction
490 $transaction = new CRM_Core_Transaction();
491 foreach ($sqls as $sql) {
492 CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, TRUE);
495 if ($membershipMerge) {
496 // call to function adding membership to related contacts
497 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
499 $transaction->commit();
503 * Find differences between contacts.
505 * @param array $main contact details
506 * @param array $other contact details
511 static function findDifferences($main, $other) {
513 'contact' => array(),
516 foreach (self
::getContactFields() as $validField) {
517 if (CRM_Utils_Array
::value($validField, $main) != CRM_Utils_Array
::value($validField, $other)) {
518 $result['contact'][] = $validField;
522 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
523 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
524 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
525 foreach ($keys as $key) {
526 // Exclude multi-value fields CRM-13836
527 if (strpos($key, '_')) {
530 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
531 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
532 if ($key1 != $key2) {
533 $result['custom'][] = $key;
540 * Function to batch merge a set of contacts based on rule-group and group.
542 * @param int $rgid rule group id
543 * @param int $gid group id
544 * @param string $mode helps decide how to behave when there are conflicts.
545 * A 'safe' value skips the merge if there are any un-resolved conflicts.
546 * Does a force merge otherwise.
547 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
550 * @param bool $redirectForPerformance
553 * @internal param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
554 * Generally used with batch-merge.
558 static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $redirectForPerformance = FALSE) {
559 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
560 $cacheKeyString = "merge {$contactType}";
561 $cacheKeyString .= $rgid ?
"_{$rgid}" : '_0';
562 $cacheKeyString .= $gid ?
"_{$gid}" : '_0';
563 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
564 pn.entity_id2 = de.contact_id2 )";
566 $limit = $redirectForPerformance ?
75 : 1;
567 $where = "de.id IS NULL LIMIT {$limit}";
569 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
570 if (empty($dupePairs) && !$redirectForPerformance) {
571 // If we haven't found any dupes, probably cache is empty.
572 // Try filling cache and give another try.
573 CRM_Core_BAO_PrevNextCache
::refillCache($rgid, $gid, $cacheKeyString);
574 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
577 $cacheParams = array(
578 'cache_key_string' => $cacheKeyString,
582 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
586 * Function to merge given set of contacts. Performs core operation.
588 * @param array $dupePairs set of pair of contacts for whom merge is to be done.
589 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
590 * Generally used with batch-merge.
591 * @param string $mode helps decide how to behave when there are conflicts.
592 * A 'safe' value skips the merge if there are any un-resolved conflicts.
593 * Does a force merge otherwise (aggressive mode).
594 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
597 * @param bool $redirectForPerformance
603 static function merge($dupePairs = array(
604 ), $cacheParams = array(), $mode = 'safe',
605 $autoFlip = TRUE, $redirectForPerformance = FALSE
607 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
608 $resultStats = array('merged' => array(), 'skipped' => array());
610 // we don't want dupe caching to get reset after every-merge, and therefore set the
611 // doNotResetCache flag
612 $config = CRM_Core_Config
::singleton();
613 $config->doNotResetCache
= 1;
615 while (!empty($dupePairs)) {
616 foreach ($dupePairs as $dupes) {
617 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
618 $mainId = $dupes['dstID'];
619 $otherId = $dupes['srcID'];
620 $isAutoFlip = CRM_Utils_Array
::value('auto_flip', $dupes, $autoFlip);
621 // if we can, make sure that $mainId is the one with lower id number
622 if ($isAutoFlip && ($mainId > $otherId)) {
623 $mainId = $dupes['srcID'];
624 $otherId = $dupes['dstID'];
626 if (!$mainId ||
!$otherId) {
631 // Generate var $migrationInfo. The variable structure is exactly same as
632 // $formValues submitted during a UI merge for a pair of contacts.
633 $rowsElementsAndInfo = &CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId);
635 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
637 // add additional details that we might need to resolve conflicts
638 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
639 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
640 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
641 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
643 // go ahead with merge if there is no conflict
644 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode)) {
645 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo);
646 $resultStats['merged'][] = array('main_d' => $mainId, 'other_id' => $otherId);
649 $resultStats['skipped'][] = array('main_d' => $mainId, 'other_id' => $otherId);
652 // delete entry from PrevNextCache table so we don't consider the pair next time
653 // pair may have been flipped, so make sure we delete using both orders
654 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString);
655 CRM_Core_BAO_PrevNextCache
::deletePair($otherId, $mainId, $cacheKeyString);
657 CRM_Core_DAO
::freeResult();
658 unset($rowsElementsAndInfo, $migrationInfo);
661 if ($cacheKeyString && !$redirectForPerformance) {
662 // retrieve next pair of dupes
663 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
664 $cacheParams['join'],
665 $cacheParams['where']
669 // do not proceed. Terminate the loop
677 * A function which uses various rules / algorithms for choosing which contact to bias to
678 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
680 * @param int $mainId main contact with whom merge has to happen
681 * @param int $otherId duplicate contact which would be deleted after merge operation
682 * @param array $migrationInfo array of information about which elements to merge.
683 * @param string $mode helps decide how to behave when there are conflicts.
684 * A 'safe' value skips the merge if there are any un-resolved conflicts.
685 * Does a force merge otherwise (aggressive mode).
691 static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe') {
692 $conflicts = array();
693 $migrationData = array(
694 'old_migration_info' => $migrationInfo,
697 $allLocationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
699 foreach ($migrationInfo as $key => $val) {
700 if ($val === "null") {
701 // Rule: no overwriting with empty values in any mode
702 unset($migrationInfo[$key]);
705 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
706 substr($key, 0, 12) == 'move_custom_'
707 ) and $val != NULL) {
708 // Rule: if both main-contact has other-contact, let $mode decide if to merge a
709 // particular field or not
710 if (!empty($migrationInfo['rows'][$key]['main'])) {
711 // if main also has a value its a conflict
712 if ($mode == 'safe') {
713 // note it down & lets wait for response from the hook.
714 // For no response skip this merge
715 $conflicts[$key] = NULL;
717 elseif ($mode == 'aggressive') {
718 // let the main-field be overwritten
723 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
724 $locField = explode('_', $key);
725 $fieldName = $locField[2];
726 $fieldCount = $locField[3];
728 // Rule: resolve address conflict if any -
729 if ($fieldName == 'address') {
730 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
731 if (!empty($migrationInfo['main_loc_address']) &&
732 array_key_exists("main_{$mainNewLocTypeId}", $migrationInfo['main_loc_address'])) {
733 // main loc already has some address for the loc-type. Its a overwrite situation.
735 // look for next available loc-type
737 foreach ($allLocationTypes as $typeId => $typeLabel) {
738 if (!array_key_exists("main_{$typeId}", $migrationInfo['main_loc_address'])) {
739 $newTypeId = $typeId;
743 // try insert address at new available loc-type
744 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
746 elseif ($mode == 'safe') {
747 // note it down & lets wait for response from the hook.
748 // For no response skip this merge
749 $conflicts[$key] = NULL;
751 elseif ($mode == 'aggressive') {
752 // let the loc-type-id be same as that of other-contact & go ahead
753 // with merge assuming aggressive mode
758 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
759 // for loc blocks other than address like email, phone .. if values are same no point in merging
760 // and adding redundant value
761 unset($migrationInfo[$key]);
766 // A hook to implement other algorithms for choosing which contact to bias to when
767 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
768 // merge happens with new values filled in here. For a particular field / row not to be merged
769 // field should be unset from fields_in_conflict.
770 $migrationData['fields_in_conflict'] = $conflicts;
771 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
772 $conflicts = $migrationData['fields_in_conflict'];
774 if (!empty($conflicts)) {
775 foreach ($conflicts as $key => $val) {
776 if ($val === NULL and $mode == 'safe') {
777 // un-resolved conflicts still present. Lets skip this merge.
781 // copy over the resolved values
782 $migrationInfo[$key] = $val;
790 * A function to build an array of information required by merge function and the merge UI.
792 * @param int $mainId main contact with whom merge has to happen
793 * @param int $otherId duplicate contact which would be deleted after merge operation
795 * @return array|bool|int
799 static function getRowsElementsAndInfo($mainId, $otherId) {
800 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
803 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
804 $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self
::getContactFields()));
805 $result = civicrm_api('contact', 'get', $params);
807 if (empty($result['values'][$cid]['contact_type'])) {
810 $
$moniker = $result['values'][$cid];
813 static $fields = array();
814 if (empty($fields)) {
815 $fields = CRM_Contact_DAO_Contact
::fields();
816 CRM_Core_DAO
::freeResult();
819 // get all contact subtypes
820 $contactSubTypes = CRM_Contact_BAO_ContactType
::subTypePairs(NULL, TRUE, '');
822 // FIXME: there must be a better way
823 foreach (array('main', 'other') as $moniker) {
824 $contact = &$
$moniker;
825 $preferred_communication_method = CRM_Utils_array
::value('preferred_communication_method', $contact);
826 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
827 $specialValues[$moniker] = array(
828 'preferred_communication_method' => $value,
829 'contact_sub_type' => $value,
830 'communication_style_id' => $value,
833 if (!empty($contact['preferred_communication_method'])){
834 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
835 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
836 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues[$moniker]['preferred_communication_method']) :
837 $specialValues[$moniker]['preferred_communication_method'];
838 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
841 'preferred_communication_method' =>
843 'newName' => 'preferred_communication_method_display',
844 'groupName' => 'preferred_communication_method',
847 CRM_Core_OptionGroup
::lookupValues($specialValues[$moniker], $names);
849 if (!empty($contact['contact_sub_type'])) {
850 $specialValues[$moniker]['contact_sub_type'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $contact['contact_sub_type']);
852 // fix contact sub type label for contact with sub type
854 foreach ($contact['contact_sub_type'] as $key => $value) {
855 $subtypes[] = CRM_Utils_Array
::retrieveValueRecursive($contactSubTypes, $value);
857 $contact['contact_sub_type_display'] = $specialValues[$moniker]['contact_sub_type_display'] = implode(', ', $subtypes);
860 if (!empty($contact['communication_style'])) {
861 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
865 static $optionValueFields = array();
866 if (empty($optionValueFields)) {
867 $optionValueFields = CRM_Core_OptionValue
::getFields();
869 foreach ($optionValueFields as $field => $params) {
870 $fields[$field]['title'] = $params['title'];
873 $diffs = self
::findDifferences($main, $other);
875 $rows = $elements = $relTableElements = $migrationInfo = array();
877 foreach ($diffs['contact'] as $field) {
878 foreach (array('main', 'other') as $moniker) {
879 $contact = &$
$moniker;
880 $value = CRM_Utils_Array
::value($field, $contact);
881 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
882 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
884 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
885 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
887 $value = str_replace('-', '', $value);
888 $label = CRM_Utils_Date
::customFormat($label);
894 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
895 if ($label === '0') {
898 if ($label === '1') {
902 elseif ($field == 'individual_prefix' ||
$field == 'prefix_id') {
903 $label = CRM_Utils_Array
::value('individual_prefix', $contact);
904 $value = CRM_Utils_Array
::value('prefix_id', $contact);
905 $field = 'prefix_id';
907 elseif ($field == 'individual_suffix' ||
$field == 'suffix_id') {
908 $label = CRM_Utils_Array
::value('individual_suffix', $contact);
909 $value = CRM_Utils_Array
::value('suffix_id', $contact);
910 $field = 'suffix_id';
912 $rows["move_$field"][$moniker] = $label;
913 if ($moniker == 'other') {
915 if ($value === NULL ||
$value == '') {
918 if ($value === 0 or $value === '0') {
921 if (is_array($value) && empty($value[1])) {
924 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
925 $migrationInfo["move_$field"] = $value;
928 $rows["move_$field"]['title'] = $fields[$field]['title'];
931 // handle location blocks.
932 $locationBlocks = array('email', 'phone', 'address');
933 $locations = array();
935 foreach ($locationBlocks as $block) {
936 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
938 $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
939 $count = $values['count'];
942 foreach ($values['values'] as $value) {
943 if ($block == 'address') {
944 CRM_Core_BAO_Address
::fixAddress($value);
945 $display = CRM_Utils_Address
::format($value);
946 $locations[$moniker][$block][$cnt] = $value;
947 $locations[$moniker][$block][$cnt]['display'] = $display;
950 $locations[$moniker][$block][$cnt] = $value;
958 if ($block == 'address') {
959 CRM_Core_BAO_Address
::fixAddress($values['values'][$id]);
960 $display = CRM_Utils_Address
::format($values['values'][$id]);
961 $locations[$moniker][$block][$cnt] = $values['values'][$id];
962 $locations[$moniker][$block][$cnt]['display'] = $display;
965 $locations[$moniker][$block][$cnt] = $values['values'][$id];
972 $allLocationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
974 $mainLocBlock = $locBlockIds = array();
975 $locBlockIds['main'] = $locBlockIds['other'] = array();
976 foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
977 $name = strtolower($block);
978 foreach (array('main', 'other') as $moniker) {
979 $locIndex = CRM_Utils_Array
::value($moniker, $locations);
980 $blockValue = CRM_Utils_Array
::value($name, $locIndex, array());
981 if (empty($blockValue)) {
982 $locValue[$moniker][$name] = 0;
983 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
986 $locValue[$moniker][$name] = TRUE;
987 foreach ($blockValue as $count => $blkValues) {
989 $locTypeId = $blkValues['location_type_id'];
993 if ($name == 'address') {
994 $fldName = 'display';
996 $locLabel[$moniker][$name][$count] = CRM_Utils_Array
::value($fldName,
999 $locTypes[$moniker][$name][$count] = $locTypeId;
1000 if ($moniker == 'main' && in_array($name, $locationBlocks)) {
1001 $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array
::value($fldName,
1004 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
1007 $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
1013 if ($locValue['other'][$name] != 0) {
1014 foreach ($locLabel['other'][$name] as $count => $value) {
1015 $locTypeId = $locTypes['other'][$name][$count];
1016 $rows["move_location_{$name}_$count"]['other'] = $value;
1017 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array
::value($count,
1018 $locLabel['main'][$name]
1020 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
1024 3 => $allLocationTypes[$locTypeId]
1028 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
1029 $migrationInfo["move_location_{$name}_{$count}"] = 1;
1031 // make sure default location type is always on top
1032 $mainLocTypeId = CRM_Utils_Array
::value($count, $locTypes['main'][$name], $locTypeId);
1033 $locTypeValues = $allLocationTypes;
1034 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
1035 unset($locTypeValues[$mainLocTypeId]);
1037 // keep 1-1 mapping for address - location type.
1039 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
1040 $js = array('onChange' => "mergeBlock('$name', this, $count );");
1042 $elements[] = array(
1043 'select', "location[{$name}][$count][locTypeId]", NULL,
1044 $defaultLocType +
$locTypeValues, $js,
1046 // keep location-type-id same as that of other-contact
1047 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
1049 if ($name != 'address') {
1050 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
1051 // always use add operation
1052 $migrationInfo['location'][$name][$count]['operation'] = 1;
1058 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1059 $config = CRM_Core_Config
::singleton();
1060 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1064 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1065 $mainUser = user_load($mainUfId);
1067 elseif ($config->userFramework
== 'Joomla') {
1068 $mainUser = JFactory
::getUser($mainUfId);
1071 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1075 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1076 $otherUser = user_load($otherUfId);
1078 elseif ($config->userFramework
== 'Joomla') {
1079 $otherUser = JFactory
::getUser($otherUfId);
1083 $relTables = CRM_Dedupe_Merger
::relTables();
1084 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1085 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1086 foreach ($relTables as $name => $null) {
1087 if (!in_array($name, $activeRelTables) &&
1088 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1090 unset($relTables[$name]);
1094 $relTableElements[] = array('checkbox', "move_$name");
1095 $migrationInfo["move_$name"] = 1;
1097 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1098 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1099 if ($name == 'rel_table_users') {
1100 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1101 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1102 $find = array('$ufid', '$ufname');
1104 $replace = array($mainUfId, $mainUser->name
);
1105 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1108 $replace = array($otherUfId, $otherUser->name
);
1109 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1112 if ($name == 'rel_table_memberships') {
1113 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1114 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1117 foreach ($relTables as $name => $null) {
1118 $relTables["move_$name"] = $relTables[$name];
1119 unset($relTables[$name]);
1122 // handle custom fields
1123 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $mainId, -1,
1124 CRM_Utils_Array
::value('contact_sub_type', $main)
1126 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $otherId, -1,
1127 CRM_Utils_Array
::value('contact_sub_type', $other)
1129 CRM_Core_DAO
::freeResult();
1131 foreach ($otherTree as $gid => $group) {
1132 $foundField = FALSE;
1133 if (!isset($group['fields'])) {
1137 foreach ($group['fields'] as $fid => $field) {
1138 if (in_array($fid, $diffs['custom'])) {
1140 $rows["custom_group_$gid"]['title'] = $group['title'];
1143 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1144 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1145 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1151 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1152 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1153 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1156 if ($values['data'] === 0 ||
$values['data'] === '0') {
1157 $values['data'] = $qfZeroBug;
1159 $value = ($values['data']) ?
$values['data'] : $value;
1162 $rows["move_custom_$fid"]['title'] = $field['label'];
1164 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1165 $migrationInfo["move_custom_$fid"] = $value;
1171 'elements' => $elements,
1172 'rel_table_elements' => $relTableElements,
1173 'main_loc_block' => $mainLocBlock,
1174 'rel_tables' => $relTables,
1175 'main_details' => $main,
1176 'other_details' => $other,
1177 'migration_info' => $migrationInfo,
1180 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1181 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1187 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1188 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1189 * A superset of moveContactBelongings() function.
1191 * @param int $mainId main contact with whom merge has to happen
1192 * @param int $otherId duplicate contact which would be deleted after merge operation
1194 * @param $migrationInfo
1200 static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1201 if (empty($migrationInfo)) {
1205 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1206 $relTables = CRM_Dedupe_Merger
::relTables();
1207 $moveTables = $locBlocks = $tableOperations = array();
1208 foreach ($migrationInfo as $key => $value) {
1209 if ($value == $qfZeroBug) {
1212 if ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) ||
1213 substr($key, 0, 12) == 'move_custom_') &&
1216 $submitted[substr($key, 5)] = $value;
1218 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1219 $locField = explode('_', $key);
1220 $fieldName = $locField[2];
1221 $fieldCount = $locField[3];
1222 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1223 // default operation is overwrite.
1228 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1229 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1231 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1232 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1233 if (array_key_exists('operation', $migrationInfo)) {
1234 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1235 if (array_key_exists($key, $migrationInfo['operation'])) {
1236 $tableOperations[$table] = $migrationInfo['operation'][$key];
1244 // **** Do location related migration:
1245 if (!empty($locBlocks)) {
1246 $locComponent = array(
1250 'openid' => 'OpenID',
1251 'address' => 'Address',
1254 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
1255 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
1257 foreach ($locBlocks as $name => $block) {
1258 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1261 $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
1262 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1263 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1265 foreach ($block as $blkCount => $values) {
1266 $locTypeId = CRM_Utils_Array
::value('locTypeId', $values, 1);
1267 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1268 $otherBlockId = CRM_Utils_Array
::value($blkCount,
1269 $migrationInfo['other_details']['loc_block_ids'][$name]
1272 // keep 1-1 mapping for address - loc type.
1274 if (array_key_exists($name, $locComponent)) {
1275 $idKey = $locTypeId;
1278 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1279 $mainBlockId = CRM_Utils_Array
::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1282 if (!$otherBlockId) {
1286 // for the block which belongs to other-contact, link the contact to main-contact
1287 $otherBlockDAO = new $daoName();
1288 $otherBlockDAO->id
= $otherBlockId;
1289 $otherBlockDAO->contact_id
= $mainId;
1290 $otherBlockDAO->location_type_id
= $locTypeId;
1292 // if main contact already has primary & billing, set the flags to 0.
1293 if ($primaryDAOId) {
1294 $otherBlockDAO->is_primary
= 0;
1296 if ($billingDAOId) {
1297 $otherBlockDAO->is_billing
= 0;
1300 // overwrite - need to delete block which belongs to main-contact.
1301 if ($mainBlockId && ($operation == 2)) {
1302 $deleteDAO = new $daoName();
1303 $deleteDAO->id
= $mainBlockId;
1304 $deleteDAO->find(TRUE);
1306 // if we about to delete a primary / billing block, set the flags for new block
1307 // that we going to assign to main-contact
1308 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1309 $otherBlockDAO->is_primary
= 1;
1311 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1312 $otherBlockDAO->is_billing
= 1;
1315 $deleteDAO->delete();
1319 $otherBlockDAO->update();
1320 $otherBlockDAO->free();
1325 // **** Do tables related migrations
1326 if (!empty($moveTables)) {
1327 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1328 unset($moveTables, $tableOperations);
1331 // **** Do contact related migrations
1332 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId);
1334 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1335 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1336 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1337 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1338 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1339 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1340 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1341 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1342 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1344 // fix custom fields so they're edible by createProfileContact()
1345 static $treeCache = array();
1346 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1347 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree($migrationInfo['main_details']['contact_type'],
1348 CRM_Core_DAO
::$_nullObject, NULL, -1
1351 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1354 foreach ($cgTree as $key => $group) {
1355 if (!isset($group['fields'])) {
1358 foreach ($group['fields'] as $fid => $field) {
1359 $cFields[$fid]['attributes'] = $field;
1363 if (!isset($submitted)) {
1364 $submitted = array();
1366 foreach ($submitted as $key => $value) {
1367 if (substr($key, 0, 7) == 'custom_') {
1368 $fid = (int) substr($key, 7);
1369 if (empty($cFields[$fid])) {
1372 $htmlType = $cFields[$fid]['attributes']['html_type'];
1373 switch ($htmlType) {
1375 $customFiles[] = $fid;
1376 unset($submitted["custom_$fid"]);
1379 case 'Select Country':
1380 case 'Select State/Province':
1381 $submitted[$key] = CRM_Core_BAO_CustomField
::getDisplayValue($value, $fid, $cFields);
1385 case 'AdvMulti-Select':
1386 case 'Multi-Select':
1387 case 'Multi-Select Country':
1388 case 'Multi-Select State/Province':
1389 // Merge values from both contacts for multivalue fields, CRM-4385
1390 // get the existing custom values from db.
1391 $customParams = array('entityID' => $mainId, $key => TRUE);
1392 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1393 if (!empty($customfieldValues[$key])) {
1394 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1395 if (is_array($existingValue) && !empty($existingValue)) {
1396 $mergeValue = $submmtedCustomValue = array();
1398 $submmtedCustomValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1401 //hack to remove null and duplicate values from array.
1402 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1403 if ($v != '' && !in_array($v, $mergeValue)) {
1408 //keep state and country as array format.
1409 //for checkbox and m-select format w/ VALUE_SEPARATOR
1410 if (in_array($htmlType, array(
1411 'CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
1412 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1414 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1417 $submitted[$key] = $mergeValue;
1421 elseif (in_array($htmlType, array(
1422 'Multi-Select Country', 'Multi-Select State/Province'))) {
1423 //we require submitted values should be in array format
1425 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1426 //hack to remove null values from array.
1427 $mergeValue = array();
1428 foreach ($mergeValueArray as $k => $v) {
1433 $submitted[$key] = $mergeValue;
1444 // **** Do file custom fields related migrations
1445 // FIXME: move this someplace else (one of the BAOs) after discussing
1446 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1447 // like, delete a file...
1449 if (!isset($customFiles)) {
1450 $customFiles = array();
1452 foreach ($customFiles as $customId) {
1453 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1455 // get the contact_id -> file_id mapping
1457 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1458 $dao = CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1459 while ($dao->fetch()) {
1460 $fileIds[$dao->entity_id
] = $dao->file_id
;
1464 // delete the main contact's file
1465 if (!empty($fileIds[$mainId])) {
1466 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1469 // move the other contact's file to main contact
1470 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1471 if ( CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}") ) {
1472 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1475 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1477 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1479 if ( CRM_Core_DAO
::singleValueQuery("
1481 FROM civicrm_entity_file
1482 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}") ) {
1484 UPDATE civicrm_entity_file
1485 SET entity_id = {$mainId}
1486 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1490 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1491 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1493 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1496 // move view only custom fields CRM-5362
1497 $viewOnlyCustomFields = array();
1498 foreach ($submitted as $key => $value) {
1499 $fid = (int) substr($key, 7);
1500 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1501 $viewOnlyCustomFields[$key] = $value;
1505 // special case to set values for view only, CRM-5362
1506 if (!empty($viewOnlyCustomFields)) {
1507 $viewOnlyCustomFields['entityID'] = $mainId;
1508 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1511 // **** Delete other contact & update prev-next caching
1512 $otherParams = array(
1513 'contact_id' => $otherId,
1517 if (CRM_Core_Permission
::check('merge duplicate contacts') &&
1518 CRM_Core_Permission
::check('delete contacts')
1520 // if ext id is submitted then set it null for contact to be deleted
1521 if (!empty($submitted['external_identifier'])) {
1522 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1523 CRM_Core_DAO
::executeQuery($query);
1526 civicrm_api('contact', 'delete', $otherParams);
1527 CRM_Core_BAO_PrevNextCache
::deleteItem($otherId);
1532 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1537 // **** Update contact related info for the main contact
1538 if (!empty($submitted)) {
1539 $submitted['contact_id'] = $mainId;
1541 //update current employer field
1542 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1543 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1544 $submitted['current_employer'] = $submitted['current_employer_id'];
1546 $submitted['current_employer'] = '';
1548 unset($submitted['current_employer_id']);
1551 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1552 if ( !isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id']) ) {
1553 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1555 if ( !isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id']) ) {
1556 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1559 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);
1567 * @return array of field names which will be compared, so everything except ID.
1569 static function getContactFields() {
1570 $contactFields = CRM_Contact_DAO_Contact
::fields();
1571 $invalidFields = array('api_key', 'contact_is_deleted', 'created_date', 'display_name', 'hash', 'id', 'modified_date',
1572 'primary_contact_id', 'sort_name', 'user_unique_id');
1573 foreach ($contactFields as $field => $value) {
1574 if (in_array($field, $invalidFields)) {
1575 unset($contactFields[$field]);
1578 return array_keys($contactFields);
1582 * Added for CRM-12695
1583 * Based on the contactId provided
1584 * add/update membership(s) to related contacts
1588 static function addMembershipToRealtedContacts($contactID) {
1589 $dao = new CRM_Member_DAO_Membership();
1590 $dao->contact_id
= $contactID;
1594 //checks membership of contact itself
1595 while ($dao->fetch()) {
1596 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1597 if ($relationshipTypeId) {
1598 $membershipParams = array(
1600 'contact_id' => $dao->contact_id
,
1601 'membership_type_id' => $dao->membership_type_id
,
1602 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1603 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1604 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1605 'source' => $dao->source
,
1606 'status_id' => $dao->status_id
1608 // create/update membership(s) for related contact(s)
1609 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1610 } // end of if relationshipTypeId