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
40 static function relTables() {
43 $config = CRM_Core_Config
::singleton();
44 if ($config->userSystem
->is_drupal
) {
45 $userRecordUrl = CRM_Utils_System
::url('user/%ufid');
46 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
48 elseif ($config->userFramework
== 'Joomla') {
49 $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';
50 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
55 'rel_table_contributions' => array(
56 'title' => ts('Contributions'),
57 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
58 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
60 'rel_table_contribution_page' => array(
61 'title' => ts('Contribution Pages'),
62 'tables' => array('civicrm_contribution_page'),
63 'url' => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
65 'rel_table_memberships' => array(
66 'title' => ts('Memberships'),
67 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
68 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
70 'rel_table_participants' => array(
71 'title' => ts('Participants'),
72 'tables' => array('civicrm_participant'),
73 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
75 'rel_table_events' => array(
76 'title' => ts('Events'),
77 'tables' => array('civicrm_event'),
78 'url' => CRM_Utils_System
::url('civicrm/event/manage', 'reset=1&cid=$cid'),
80 'rel_table_activities' => array(
81 'title' => ts('Activities'),
82 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
83 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
85 'rel_table_relationships' => array(
86 'title' => ts('Relationships'),
87 'tables' => array('civicrm_relationship'),
88 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
90 'rel_table_custom_groups' => array(
91 'title' => ts('Custom Groups'),
92 'tables' => array('civicrm_custom_group'),
93 'url' => CRM_Utils_System
::url('civicrm/admin/custom/group', 'reset=1'),
95 'rel_table_uf_groups' => array(
96 'title' => ts('Profiles'),
97 'tables' => array('civicrm_uf_group'),
98 'url' => CRM_Utils_System
::url('civicrm/admin/uf/group', 'reset=1'),
100 'rel_table_groups' => array(
101 'title' => ts('Groups'),
102 'tables' => array('civicrm_group_contact'),
103 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
105 'rel_table_notes' => array(
106 'title' => ts('Notes'),
107 'tables' => array('civicrm_note'),
108 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
110 'rel_table_tags' => array(
111 'title' => ts('Tags'),
112 'tables' => array('civicrm_entity_tag'),
113 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
115 'rel_table_mailings' => array(
116 'title' => ts('Mailings'),
117 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
118 'url' => CRM_Utils_System
::url('civicrm/mailing', 'reset=1&force=1&cid=$cid'),
120 'rel_table_cases' => array(
121 'title' => ts('Cases'),
122 'tables' => array('civicrm_case_contact'),
123 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
125 'rel_table_grants' => array(
126 'title' => ts('Grants'),
127 'tables' => array('civicrm_grant'),
128 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
130 'rel_table_pcp' => array(
131 'title' => ts('PCPs'),
132 'tables' => array('civicrm_pcp'),
133 'url' => CRM_Utils_System
::url('civicrm/contribute/pcp/manage', 'reset=1'),
135 'rel_table_pledges' => array(
136 'title' => ts('Pledges'),
137 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
138 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
140 'rel_table_users' => array(
142 'tables' => array('civicrm_uf_match'),
143 'url' => $userRecordUrl,
147 $relTables +
= self
::getMultiValueCustomSets('relTables');
149 // Allow hook_civicrm_merge() to adjust $relTables
150 CRM_Utils_Hook
::merge('relTables', $relTables);
156 * Returns the related tables groups for which a contact has any info entered
158 static function getActiveRelTables($cid) {
162 $relTables = self
::relTables();
163 $cidRefs = self
::cidRefs();
164 $eidRefs = self
::eidRefs();
165 foreach ($relTables as $group => $params) {
167 foreach ($params['tables'] as $table) {
168 if (isset($cidRefs[$table])) {
169 foreach ($cidRefs[$table] as $field) {
170 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
173 if (isset($eidRefs[$table])) {
174 foreach ($eidRefs[$table] as $entityTable => $entityId) {
175 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
178 foreach ($sqls as $sql) {
179 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
185 return array_unique($groups);
189 * Return tables and their fields referencing civicrm_contact.contact_id explicitly
191 static function cidRefs() {
198 FROM information_schema.key_column_usage
200 referenced_table_schema = database() AND
201 referenced_table_name = 'civicrm_contact' AND
202 referenced_column_name = 'id';
204 $dao = CRM_Core_DAO
::executeQuery($sql);
205 while ($dao->fetch()) {
206 $cidRefs[$dao->table_name
][] = $dao->column_name
;
210 // Allow hook_civicrm_merge() to adjust $cidRefs
211 CRM_Utils_Hook
::merge('cidRefs', $cidRefs);
217 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
219 static function eidRefs() {
222 // FIXME: this should be generated dynamically from the schema
223 // tables that reference contacts with entity_{id,table}
225 'civicrm_acl' => array('entity_table' => 'entity_id'),
226 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
227 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
228 'civicrm_log' => array('entity_table' => 'entity_id'),
229 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
230 'civicrm_note' => array('entity_table' => 'entity_id'),
233 // Allow hook_civicrm_merge() to adjust $eidRefs
234 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
240 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
241 * @param string $request 'relTables' or 'cidRefs'
244 static function getMultiValueCustomSets($request) {
246 if ($data === NULL) {
248 'relTables' => array(),
249 'cidRefs' => array(),
251 $result = civicrm_api3('custom_group', 'get', array(
253 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
254 'return' => array('id', 'title', 'table_name', 'style'),
256 foreach($result['values'] as $custom) {
257 $data['cidRefs'][$custom['table_name']] = array('entity_id');
258 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
259 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
260 'title' => $custom['title'],
261 'tables' => array($custom['table_name']),
262 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
266 return $data[$request];
270 * Tables which require custom processing should declare functions to call here.
271 * Doing so will override normal processing.
273 static function cpTables() {
277 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
278 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
279 // Empty array == do nothing - this table is handled by mergeGroupContact
280 'civicrm_subscription_history' => array(),
281 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
288 * return payment related table.
290 static function paymentTables() {
293 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
300 * return payment update Query.
302 static function paymentSql($tableName, $mainContactId, $otherContactId) {
304 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
308 $paymentTables = self
::paymentTables();
309 if (!in_array($tableName, $paymentTables)) {
313 switch ($tableName) {
314 case 'civicrm_pledge':
316 UPDATE IGNORE civicrm_contribution contribution
317 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
318 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
319 SET contribution.contact_id = $mainContactId
320 WHERE pledge.contact_id = $otherContactId";
323 case 'civicrm_membership':
325 UPDATE IGNORE civicrm_contribution contribution
326 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
327 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
328 SET contribution.contact_id = $mainContactId
329 WHERE membership.contact_id = $otherContactId";
332 case 'civicrm_participant':
334 UPDATE IGNORE civicrm_contribution contribution
335 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
336 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
337 SET contribution.contact_id = $mainContactId
338 WHERE participant.contact_id = $otherContactId";
345 static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
347 if (!$tableName ||
!$mainId ||
!$otherId) {
352 switch ($tableName) {
353 case 'civicrm_membership':
354 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add'])
356 if ($mode == 'add') {
358 DELETE membership1.* FROM civicrm_membership membership1
359 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
360 AND membership1.contact_id = {$mainId}
361 AND membership2.contact_id = {$otherId} ";
363 if ($mode == 'payment') {
365 DELETE contribution.* FROM civicrm_contribution contribution
366 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
367 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
368 AND membership1.contact_id = {$mainId}
369 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
370 AND membership2.contact_id = {$otherId}";
374 case 'civicrm_uf_match':
375 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
376 // failing to meet intended result. Therefore we introduce this additonal query:
377 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
385 * Based on the provided two contact_ids and a set of tables, move the
386 * belongings of the other contact to the main one.
390 static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
391 $cidRefs = self
::cidRefs();
392 $eidRefs = self
::eidRefs();
393 $cpTables = self
::cpTables();
394 $paymentTables = self
::paymentTables();
395 $membershipMerge = FALSE; // CRM-12695
397 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
398 if ($tables !== FALSE) {
399 // if there are specific tables, sanitize the list
400 $affected = array_unique(array_intersect($affected, $tables));
403 // if there aren't any specific tables, don't affect the ones handled by relTables()
404 $relTables = self
::relTables();
406 foreach ($relTables as $params) {
407 $handled = array_merge($handled, $params['tables']);
409 $affected = array_diff($affected, $handled);
412 * Set $membershipMerge flag only once
413 * while doing contact related migration
414 * to call addMembershipToRealtedContacts()
415 * function only once.
416 * Since the current function (moveContactBelongings) is called twice
417 * with & without parameters $tables & $tableOperations
419 // retrieve main contact's related table(s)
420 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
421 // check if membership table exists in main contact's related table(s)
422 if (in_array('rel_table_memberships', $activeMainRelTables)) {
423 $membershipMerge = TRUE; // set membership flag - CRM-12695
427 $mainId = (int) $mainId;
428 $otherId = (int) $otherId;
431 foreach ($affected as $table) {
432 // Call custom processing function for objects that require it
433 if (isset($cpTables[$table])) {
434 foreach ($cpTables[$table] as $className => $fnName) {
435 $className::$fnName($mainId, $otherId, $sqls);
437 // Skip normal processing
441 // use UPDATE IGNORE + DELETE query pair to skip on situations when
442 // there's a UNIQUE restriction on ($field, some_other_field) pair
443 if (isset($cidRefs[$table])) {
444 foreach ($cidRefs[$table] as $field) {
445 // carry related contributions CRM-5359
446 if (in_array($table, $paymentTables)) {
447 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
448 $sqls = array_merge($sqls, $payOprSqls);
450 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
451 $sqls = array_merge($sqls, $paymentSqls);
454 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
455 $sqls = array_merge($sqls, $preOperationSqls);
457 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
458 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
461 if (isset($eidRefs[$table])) {
462 foreach ($eidRefs[$table] as $entityTable => $entityId) {
463 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
464 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
469 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
470 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
472 // call the SQL queries in one transaction
473 $transaction = new CRM_Core_Transaction();
474 foreach ($sqls as $sql) {
475 CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, TRUE);
478 if ($membershipMerge) {
479 // call to function adding membership to related contacts
480 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
482 $transaction->commit();
486 * Find differences between contacts.
488 * @param array $main contact details
489 * @param array $other contact details
494 static function findDifferences($main, $other) {
496 'contact' => array(),
499 foreach (self
::getContactFields() as $validField) {
500 if (CRM_Utils_Array
::value($validField, $main) != CRM_Utils_Array
::value($validField, $other)) {
501 $result['contact'][] = $validField;
505 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
506 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
507 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
508 foreach ($keys as $key) {
509 // Exclude multi-value fields CRM-13836
510 if (strpos($key, '_')) {
513 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
514 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
515 if ($key1 != $key2) {
516 $result['custom'][] = $key;
523 * Function to batch merge a set of contacts based on rule-group and group.
525 * @param int $rgid rule group id
526 * @param int $gid group id
527 * @param string $mode helps decide how to behave when there are conflicts.
528 * A 'safe' value skips the merge if there are any un-resolved conflicts.
529 * Does a force merge otherwise.
530 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
533 * @param bool $redirectForPerformance
536 * @internal param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
537 * Generally used with batch-merge.
541 static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $redirectForPerformance = FALSE) {
542 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
543 $cacheKeyString = "merge {$contactType}";
544 $cacheKeyString .= $rgid ?
"_{$rgid}" : '_0';
545 $cacheKeyString .= $gid ?
"_{$gid}" : '_0';
546 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
547 pn.entity_id2 = de.contact_id2 )";
549 $limit = $redirectForPerformance ?
75 : 1;
550 $where = "de.id IS NULL LIMIT {$limit}";
552 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
553 if (empty($dupePairs) && !$redirectForPerformance) {
554 // If we haven't found any dupes, probably cache is empty.
555 // Try filling cache and give another try.
556 CRM_Core_BAO_PrevNextCache
::refillCache($rgid, $gid, $cacheKeyString);
557 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
560 $cacheParams = array(
561 'cache_key_string' => $cacheKeyString,
565 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
569 * Function to merge given set of contacts. Performs core operation.
571 * @param array $dupePairs set of pair of contacts for whom merge is to be done.
572 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
573 * Generally used with batch-merge.
574 * @param string $mode helps decide how to behave when there are conflicts.
575 * A 'safe' value skips the merge if there are any un-resolved conflicts.
576 * Does a force merge otherwise (aggressive mode).
577 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
580 * @param bool $redirectForPerformance
586 static function merge($dupePairs = array(
587 ), $cacheParams = array(), $mode = 'safe',
588 $autoFlip = TRUE, $redirectForPerformance = FALSE
590 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
591 $resultStats = array('merged' => array(), 'skipped' => array());
593 // we don't want dupe caching to get reset after every-merge, and therefore set the
594 // doNotResetCache flag
595 $config = CRM_Core_Config
::singleton();
596 $config->doNotResetCache
= 1;
598 while (!empty($dupePairs)) {
599 foreach ($dupePairs as $dupes) {
600 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
601 $mainId = $dupes['dstID'];
602 $otherId = $dupes['srcID'];
603 $isAutoFlip = CRM_Utils_Array
::value('auto_flip', $dupes, $autoFlip);
604 // if we can, make sure that $mainId is the one with lower id number
605 if ($isAutoFlip && ($mainId > $otherId)) {
606 $mainId = $dupes['srcID'];
607 $otherId = $dupes['dstID'];
609 if (!$mainId ||
!$otherId) {
614 // Generate var $migrationInfo. The variable structure is exactly same as
615 // $formValues submitted during a UI merge for a pair of contacts.
616 $rowsElementsAndInfo = &CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId);
618 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
620 // add additional details that we might need to resolve conflicts
621 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
622 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
623 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
624 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
626 // go ahead with merge if there is no conflict
627 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode)) {
628 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo);
629 $resultStats['merged'][] = array('main_d' => $mainId, 'other_id' => $otherId);
632 $resultStats['skipped'][] = array('main_d' => $mainId, 'other_id' => $otherId);
635 // delete entry from PrevNextCache table so we don't consider the pair next time
636 // pair may have been flipped, so make sure we delete using both orders
637 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString);
638 CRM_Core_BAO_PrevNextCache
::deletePair($otherId, $mainId, $cacheKeyString);
640 CRM_Core_DAO
::freeResult();
641 unset($rowsElementsAndInfo, $migrationInfo);
644 if ($cacheKeyString && !$redirectForPerformance) {
645 // retrieve next pair of dupes
646 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
647 $cacheParams['join'],
648 $cacheParams['where']
652 // do not proceed. Terminate the loop
660 * A function which uses various rules / algorithms for choosing which contact to bias to
661 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
663 * @param int $mainId main contact with whom merge has to happen
664 * @param int $otherId duplicate contact which would be deleted after merge operation
665 * @param array $migrationInfo array of information about which elements to merge.
666 * @param string $mode helps decide how to behave when there are conflicts.
667 * A 'safe' value skips the merge if there are any un-resolved conflicts.
668 * Does a force merge otherwise (aggressive mode).
674 static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe') {
675 $conflicts = array();
676 $migrationData = array(
677 'old_migration_info' => $migrationInfo,
680 $allLocationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
682 foreach ($migrationInfo as $key => $val) {
683 if ($val === "null") {
684 // Rule: no overwriting with empty values in any mode
685 unset($migrationInfo[$key]);
688 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
689 substr($key, 0, 12) == 'move_custom_'
690 ) and $val != NULL) {
691 // Rule: if both main-contact has other-contact, let $mode decide if to merge a
692 // particular field or not
693 if (!empty($migrationInfo['rows'][$key]['main'])) {
694 // if main also has a value its a conflict
695 if ($mode == 'safe') {
696 // note it down & lets wait for response from the hook.
697 // For no response skip this merge
698 $conflicts[$key] = NULL;
700 elseif ($mode == 'aggressive') {
701 // let the main-field be overwritten
706 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
707 $locField = explode('_', $key);
708 $fieldName = $locField[2];
709 $fieldCount = $locField[3];
711 // Rule: resolve address conflict if any -
712 if ($fieldName == 'address') {
713 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
714 if (!empty($migrationInfo['main_loc_address']) &&
715 array_key_exists("main_{$mainNewLocTypeId}", $migrationInfo['main_loc_address'])) {
716 // main loc already has some address for the loc-type. Its a overwrite situation.
718 // look for next available loc-type
720 foreach ($allLocationTypes as $typeId => $typeLabel) {
721 if (!array_key_exists("main_{$typeId}", $migrationInfo['main_loc_address'])) {
722 $newTypeId = $typeId;
726 // try insert address at new available loc-type
727 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
729 elseif ($mode == 'safe') {
730 // note it down & lets wait for response from the hook.
731 // For no response skip this merge
732 $conflicts[$key] = NULL;
734 elseif ($mode == 'aggressive') {
735 // let the loc-type-id be same as that of other-contact & go ahead
736 // with merge assuming aggressive mode
741 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
742 // for loc blocks other than address like email, phone .. if values are same no point in merging
743 // and adding redundant value
744 unset($migrationInfo[$key]);
749 // A hook to implement other algorithms for choosing which contact to bias to when
750 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
751 // merge happens with new values filled in here. For a particular field / row not to be merged
752 // field should be unset from fields_in_conflict.
753 $migrationData['fields_in_conflict'] = $conflicts;
754 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
755 $conflicts = $migrationData['fields_in_conflict'];
757 if (!empty($conflicts)) {
758 foreach ($conflicts as $key => $val) {
759 if ($val === NULL and $mode == 'safe') {
760 // un-resolved conflicts still present. Lets skip this merge.
764 // copy over the resolved values
765 $migrationInfo[$key] = $val;
773 * A function to build an array of information required by merge function and the merge UI.
775 * @param int $mainId main contact with whom merge has to happen
776 * @param int $otherId duplicate contact which would be deleted after merge operation
778 * @return array|bool|int
782 static function getRowsElementsAndInfo($mainId, $otherId) {
783 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
786 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
787 $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self
::getContactFields()));
788 $result = civicrm_api('contact', 'get', $params);
790 if (empty($result['values'][$cid]['contact_type'])) {
793 $
$moniker = $result['values'][$cid];
796 static $fields = array();
797 if (empty($fields)) {
798 $fields = CRM_Contact_DAO_Contact
::fields();
799 CRM_Core_DAO
::freeResult();
802 // FIXME: there must be a better way
803 foreach (array('main', 'other') as $moniker) {
804 $contact = &$
$moniker;
805 $preferred_communication_method = CRM_Utils_array
::value('preferred_communication_method', $contact);
806 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
807 $specialValues[$moniker] = array(
808 'preferred_communication_method' => $value,
811 if (!empty($contact['preferred_communication_method'])){
812 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
813 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
814 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues[$moniker]['preferred_communication_method']) :
815 $specialValues[$moniker]['preferred_communication_method'];
816 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
819 'preferred_communication_method' =>
821 'newName' => 'preferred_communication_method_display',
822 'groupName' => 'preferred_communication_method',
825 CRM_Core_OptionGroup
::lookupValues($specialValues[$moniker], $names);
828 static $optionValueFields = array();
829 if (empty($optionValueFields)) {
830 $optionValueFields = CRM_Core_OptionValue
::getFields();
832 foreach ($optionValueFields as $field => $params) {
833 $fields[$field]['title'] = $params['title'];
836 $diffs = self
::findDifferences($main, $other);
838 $rows = $elements = $relTableElements = $migrationInfo = array();
840 foreach ($diffs['contact'] as $field) {
841 foreach (array('main', 'other') as $moniker) {
842 $contact = &$
$moniker;
843 $value = CRM_Utils_Array
::value($field, $contact);
844 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
845 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
847 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
848 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
850 $value = str_replace('-', '', $value);
851 $label = CRM_Utils_Date
::customFormat($label);
857 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
858 if ($label === '0') {
861 if ($label === '1') {
865 elseif ($field == 'individual_prefix' ||
$field == 'prefix_id') {
866 $label = CRM_Utils_Array
::value('individual_prefix', $contact);
867 $value = CRM_Utils_Array
::value('prefix_id', $contact);
868 $field = 'prefix_id';
870 elseif ($field == 'individual_suffix' ||
$field == 'suffix_id') {
871 $label = CRM_Utils_Array
::value('individual_suffix', $contact);
872 $value = CRM_Utils_Array
::value('suffix_id', $contact);
873 $field = 'suffix_id';
875 $rows["move_$field"][$moniker] = $label;
876 if ($moniker == 'other') {
878 if ($value === NULL ||
$value == '') {
881 if ($value === 0 or $value === '0') {
884 if (is_array($value) && empty($value[1])) {
887 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
888 $migrationInfo["move_$field"] = $value;
891 $rows["move_$field"]['title'] = $fields[$field]['title'];
894 // handle location blocks.
895 $locationBlocks = array('email', 'phone', 'address');
896 $locations = array();
898 foreach ($locationBlocks as $block) {
899 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
901 $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
902 $count = $values['count'];
905 foreach ($values['values'] as $value) {
906 if ($block == 'address') {
907 CRM_Core_BAO_Address
::fixAddress($value);
908 $display = CRM_Utils_Address
::format($value);
909 $locations[$moniker][$block][$cnt] = $value;
910 $locations[$moniker][$block][$cnt]['display'] = $display;
913 $locations[$moniker][$block][$cnt] = $value;
921 if ($block == 'address') {
922 CRM_Core_BAO_Address
::fixAddress($values['values'][$id]);
923 $display = CRM_Utils_Address
::format($values['values'][$id]);
924 $locations[$moniker][$block][$cnt] = $values['values'][$id];
925 $locations[$moniker][$block][$cnt]['display'] = $display;
928 $locations[$moniker][$block][$cnt] = $values['values'][$id];
935 $allLocationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
937 $mainLocBlock = $locBlockIds = array();
938 $locBlockIds['main'] = $locBlockIds['other'] = array();
939 foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
940 $name = strtolower($block);
941 foreach (array('main', 'other') as $moniker) {
942 $locIndex = CRM_Utils_Array
::value($moniker, $locations);
943 $blockValue = CRM_Utils_Array
::value($name, $locIndex, array());
944 if (empty($blockValue)) {
945 $locValue[$moniker][$name] = 0;
946 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
949 $locValue[$moniker][$name] = TRUE;
950 foreach ($blockValue as $count => $blkValues) {
952 $locTypeId = $blkValues['location_type_id'];
956 if ($name == 'address') {
957 $fldName = 'display';
959 $locLabel[$moniker][$name][$count] = CRM_Utils_Array
::value($fldName,
962 $locTypes[$moniker][$name][$count] = $locTypeId;
963 if ($moniker == 'main' && in_array($name, $locationBlocks)) {
964 $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array
::value($fldName,
967 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
970 $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
976 if ($locValue['other'][$name] != 0) {
977 foreach ($locLabel['other'][$name] as $count => $value) {
978 $locTypeId = $locTypes['other'][$name][$count];
979 $rows["move_location_{$name}_$count"]['other'] = $value;
980 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array
::value($count,
981 $locLabel['main'][$name]
983 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
987 3 => $allLocationTypes[$locTypeId]
991 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
992 $migrationInfo["move_location_{$name}_{$count}"] = 1;
994 // make sure default location type is always on top
995 $mainLocTypeId = CRM_Utils_Array
::value($count, $locTypes['main'][$name], $locTypeId);
996 $locTypeValues = $allLocationTypes;
997 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
998 unset($locTypeValues[$mainLocTypeId]);
1000 // keep 1-1 mapping for address - location type.
1002 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
1003 $js = array('onChange' => "mergeBlock('$name', this, $count );");
1005 $elements[] = array(
1006 'select', "location[{$name}][$count][locTypeId]", NULL,
1007 $defaultLocType +
$locTypeValues, $js,
1009 // keep location-type-id same as that of other-contact
1010 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
1012 if ($name != 'address') {
1013 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
1014 // always use add operation
1015 $migrationInfo['location'][$name][$count]['operation'] = 1;
1021 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1022 $config = CRM_Core_Config
::singleton();
1023 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1027 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1028 $mainUser = user_load($mainUfId);
1030 elseif ($config->userFramework
== 'Joomla') {
1031 $mainUser = JFactory
::getUser($mainUfId);
1034 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1038 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1039 $otherUser = user_load($otherUfId);
1041 elseif ($config->userFramework
== 'Joomla') {
1042 $otherUser = JFactory
::getUser($otherUfId);
1046 $relTables = CRM_Dedupe_Merger
::relTables();
1047 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1048 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1049 foreach ($relTables as $name => $null) {
1050 if (!in_array($name, $activeRelTables) &&
1051 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1053 unset($relTables[$name]);
1057 $relTableElements[] = array('checkbox', "move_$name");
1058 $migrationInfo["move_$name"] = 1;
1060 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1061 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1062 if ($name == 'rel_table_users') {
1063 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1064 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1065 $find = array('$ufid', '$ufname');
1067 $replace = array($mainUfId, $mainUser->name
);
1068 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1071 $replace = array($otherUfId, $otherUser->name
);
1072 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1075 if ($name == 'rel_table_memberships') {
1076 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1077 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1080 foreach ($relTables as $name => $null) {
1081 $relTables["move_$name"] = $relTables[$name];
1082 unset($relTables[$name]);
1085 // handle custom fields
1086 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $mainId, -1,
1087 CRM_Utils_Array
::value('contact_sub_type', $main)
1089 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $otherId, -1,
1090 CRM_Utils_Array
::value('contact_sub_type', $other)
1092 CRM_Core_DAO
::freeResult();
1094 foreach ($otherTree as $gid => $group) {
1095 $foundField = FALSE;
1096 if (!isset($group['fields'])) {
1100 foreach ($group['fields'] as $fid => $field) {
1101 if (in_array($fid, $diffs['custom'])) {
1103 $rows["custom_group_$gid"]['title'] = $group['title'];
1106 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1107 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1108 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1114 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1115 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1116 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1119 if ($values['data'] === 0 ||
$values['data'] === '0') {
1120 $values['data'] = $qfZeroBug;
1122 $value = ($values['data']) ?
$values['data'] : $value;
1125 $rows["move_custom_$fid"]['title'] = $field['label'];
1127 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1128 $migrationInfo["move_custom_$fid"] = $value;
1134 'elements' => $elements,
1135 'rel_table_elements' => $relTableElements,
1136 'main_loc_block' => $mainLocBlock,
1137 'rel_tables' => $relTables,
1138 'main_details' => $main,
1139 'other_details' => $other,
1140 'migration_info' => $migrationInfo,
1143 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1144 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1150 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1151 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1152 * A superset of moveContactBelongings() function.
1154 * @param int $mainId main contact with whom merge has to happen
1155 * @param int $otherId duplicate contact which would be deleted after merge operation
1157 * @param $migrationInfo
1163 static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1164 if (empty($migrationInfo)) {
1168 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1169 $relTables = CRM_Dedupe_Merger
::relTables();
1170 $moveTables = $locBlocks = $tableOperations = array();
1171 foreach ($migrationInfo as $key => $value) {
1172 if ($value == $qfZeroBug) {
1175 if ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) ||
1176 substr($key, 0, 12) == 'move_custom_') &&
1179 $submitted[substr($key, 5)] = $value;
1181 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1182 $locField = explode('_', $key);
1183 $fieldName = $locField[2];
1184 $fieldCount = $locField[3];
1185 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1186 // default operation is overwrite.
1191 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1192 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1194 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1195 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1196 if (array_key_exists('operation', $migrationInfo)) {
1197 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1198 if (array_key_exists($key, $migrationInfo['operation'])) {
1199 $tableOperations[$table] = $migrationInfo['operation'][$key];
1207 // **** Do location related migration:
1208 if (!empty($locBlocks)) {
1209 $locComponent = array(
1213 'openid' => 'OpenID',
1214 'address' => 'Address',
1217 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
1218 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
1220 foreach ($locBlocks as $name => $block) {
1221 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1224 $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
1225 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1226 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1228 foreach ($block as $blkCount => $values) {
1229 $locTypeId = CRM_Utils_Array
::value('locTypeId', $values, 1);
1230 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1231 $otherBlockId = CRM_Utils_Array
::value($blkCount,
1232 $migrationInfo['other_details']['loc_block_ids'][$name]
1235 // keep 1-1 mapping for address - loc type.
1237 if (array_key_exists($name, $locComponent)) {
1238 $idKey = $locTypeId;
1241 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1242 $mainBlockId = CRM_Utils_Array
::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1245 if (!$otherBlockId) {
1249 // for the block which belongs to other-contact, link the contact to main-contact
1250 $otherBlockDAO = new $daoName();
1251 $otherBlockDAO->id
= $otherBlockId;
1252 $otherBlockDAO->contact_id
= $mainId;
1253 $otherBlockDAO->location_type_id
= $locTypeId;
1255 // if main contact already has primary & billing, set the flags to 0.
1256 if ($primaryDAOId) {
1257 $otherBlockDAO->is_primary
= 0;
1259 if ($billingDAOId) {
1260 $otherBlockDAO->is_billing
= 0;
1263 // overwrite - need to delete block which belongs to main-contact.
1264 if ($mainBlockId && ($operation == 2)) {
1265 $deleteDAO = new $daoName();
1266 $deleteDAO->id
= $mainBlockId;
1267 $deleteDAO->find(TRUE);
1269 // if we about to delete a primary / billing block, set the flags for new block
1270 // that we going to assign to main-contact
1271 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1272 $otherBlockDAO->is_primary
= 1;
1274 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1275 $otherBlockDAO->is_billing
= 1;
1278 $deleteDAO->delete();
1282 $otherBlockDAO->update();
1283 $otherBlockDAO->free();
1288 // **** Do tables related migrations
1289 if (!empty($moveTables)) {
1290 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1291 unset($moveTables, $tableOperations);
1294 // **** Do contact related migrations
1295 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId);
1297 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1298 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1299 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1300 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1301 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1302 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1303 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1304 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1305 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1307 // fix custom fields so they're edible by createProfileContact()
1308 static $treeCache = array();
1309 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1310 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree($migrationInfo['main_details']['contact_type'],
1311 CRM_Core_DAO
::$_nullObject, NULL, -1
1314 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1317 foreach ($cgTree as $key => $group) {
1318 if (!isset($group['fields'])) {
1321 foreach ($group['fields'] as $fid => $field) {
1322 $cFields[$fid]['attributes'] = $field;
1326 if (!isset($submitted)) {
1327 $submitted = array();
1329 foreach ($submitted as $key => $value) {
1330 if (substr($key, 0, 7) == 'custom_') {
1331 $fid = (int) substr($key, 7);
1332 $htmlType = $cFields[$fid]['attributes']['html_type'];
1333 switch ($htmlType) {
1335 $customFiles[] = $fid;
1336 unset($submitted["custom_$fid"]);
1339 case 'Select Country':
1340 case 'Select State/Province':
1341 $submitted[$key] = CRM_Core_BAO_CustomField
::getDisplayValue($value, $fid, $cFields);
1345 case 'AdvMulti-Select':
1346 case 'Multi-Select':
1347 case 'Multi-Select Country':
1348 case 'Multi-Select State/Province':
1349 // Merge values from both contacts for multivalue fields, CRM-4385
1350 // get the existing custom values from db.
1351 $customParams = array('entityID' => $mainId, $key => TRUE);
1352 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1353 if (!empty($customfieldValues[$key])) {
1354 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1355 if (is_array($existingValue) && !empty($existingValue)) {
1356 $mergeValue = $submmtedCustomValue = array();
1358 $submmtedCustomValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1361 //hack to remove null and duplicate values from array.
1362 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1363 if ($v != '' && !in_array($v, $mergeValue)) {
1368 //keep state and country as array format.
1369 //for checkbox and m-select format w/ VALUE_SEPARATOR
1370 if (in_array($htmlType, array(
1371 'CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
1372 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1374 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1377 $submitted[$key] = $mergeValue;
1381 elseif (in_array($htmlType, array(
1382 'Multi-Select Country', 'Multi-Select State/Province'))) {
1383 //we require submitted values should be in array format
1385 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1386 //hack to remove null values from array.
1387 $mergeValue = array();
1388 foreach ($mergeValueArray as $k => $v) {
1393 $submitted[$key] = $mergeValue;
1404 // **** Do file custom fields related migrations
1405 // FIXME: move this someplace else (one of the BAOs) after discussing
1406 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1407 // like, delete a file...
1409 if (!isset($customFiles)) {
1410 $customFiles = array();
1412 foreach ($customFiles as $customId) {
1413 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1415 // get the contact_id -> file_id mapping
1417 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1418 $dao = CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1419 while ($dao->fetch()) {
1420 $fileIds[$dao->entity_id
] = $dao->file_id
;
1424 // delete the main contact's file
1425 if (!empty($fileIds[$mainId])) {
1426 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1429 // move the other contact's file to main contact
1430 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1431 if ( CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}") ) {
1432 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1435 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1437 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1439 if ( CRM_Core_DAO
::singleValueQuery("
1441 FROM civicrm_entity_file
1442 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}") ) {
1444 UPDATE civicrm_entity_file
1445 SET entity_id = {$mainId}
1446 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1450 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1451 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1453 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1456 // move view only custom fields CRM-5362
1457 $viewOnlyCustomFields = array();
1458 foreach ($submitted as $key => $value) {
1459 $fid = (int) substr($key, 7);
1460 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1461 $viewOnlyCustomFields[$key] = $value;
1465 // special case to set values for view only, CRM-5362
1466 if (!empty($viewOnlyCustomFields)) {
1467 $viewOnlyCustomFields['entityID'] = $mainId;
1468 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1471 // **** Delete other contact & update prev-next caching
1472 $otherParams = array(
1473 'contact_id' => $otherId,
1477 if (CRM_Core_Permission
::check('merge duplicate contacts') &&
1478 CRM_Core_Permission
::check('delete contacts')
1480 // if ext id is submitted then set it null for contact to be deleted
1481 if (!empty($submitted['external_identifier'])) {
1482 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1483 CRM_Core_DAO
::executeQuery($query);
1486 civicrm_api('contact', 'delete', $otherParams);
1487 CRM_Core_BAO_PrevNextCache
::deleteItem($otherId);
1492 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1497 // **** Update contact related info for the main contact
1498 if (!empty($submitted)) {
1499 $submitted['contact_id'] = $mainId;
1501 //update current employer field
1502 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1503 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1504 $submitted['current_employer'] = $submitted['current_employer_id'];
1506 $submitted['current_employer'] = '';
1508 unset($submitted['current_employer_id']);
1511 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1512 if ( !isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id']) ) {
1513 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1515 if ( !isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id']) ) {
1516 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1519 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);
1527 * @return array of field names which will be compared, so everything except ID.
1529 static function getContactFields() {
1530 $contactFields = CRM_Contact_DAO_Contact
::fields();
1531 $invalidFields = array('api_key', 'contact_is_deleted', 'created_date', 'display_name', 'hash', 'id', 'modified_date',
1532 'primary_contact_id', 'sort_name', 'user_unique_id');
1533 foreach ($contactFields as $field => $value) {
1534 if (in_array($field, $invalidFields)) {
1535 unset($contactFields[$field]);
1538 return array_keys($contactFields);
1542 * Added for CRM-12695
1543 * Based on the contactId provided
1544 * add/update membership(s) to related contacts
1548 static function addMembershipToRealtedContacts($contactID) {
1549 $dao = new CRM_Member_DAO_Membership();
1550 $dao->contact_id
= $contactID;
1554 //checks membership of contact itself
1555 while ($dao->fetch()) {
1556 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1557 if ($relationshipTypeId) {
1558 $membershipParams = array(
1560 'contact_id' => $dao->contact_id
,
1561 'membership_type_id' => $dao->membership_type_id
,
1562 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1563 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1564 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1565 'source' => $dao->source
,
1566 'status_id' => $dao->status_id
1568 // create/update membership(s) for related contact(s)
1569 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1570 } // end of if relationshipTypeId