3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 class CRM_Dedupe_Merger
{
36 // FIXME: this should be auto-generated from the schema
37 static $validFields = array(
38 'addressee', 'addressee_custom', 'birth_date', 'contact_source', 'contact_type',
39 'deceased_date', 'do_not_email', 'do_not_mail', 'do_not_sms', 'do_not_phone',
40 'do_not_trade', 'external_identifier', 'email_greeting', 'email_greeting_custom', 'first_name', 'gender',
41 'home_URL', 'household_name', 'image_URL',
42 'individual_prefix', 'prefix_id', 'individual_suffix', 'suffix_id', 'is_deceased', 'is_opt_out',
43 'job_title', 'last_name', 'legal_identifier', 'legal_name',
44 'middle_name', 'nick_name', 'organization_name', 'postal_greeting', 'postal_greeting_custom',
45 'preferred_communication_method', 'preferred_mail_format', 'sic_code', 'current_employer_id'
48 // FIXME: consider creating a common structure with cidRefs() and eidRefs()
49 // FIXME: the sub-pages references by the URLs should
50 // be loaded dynamically on the merge form instead
51 static function relTables() {
54 $config = CRM_Core_Config
::singleton();
55 if ($config->userSystem
->is_drupal
) {
56 $userRecordUrl = CRM_Utils_System
::url('user/%ufid');
57 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
59 elseif ($config->userFramework
== 'Joomla') {
60 $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';
61 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
66 'rel_table_contributions' => array(
67 'title' => ts('Contributions'),
68 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
69 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
71 'rel_table_contribution_page' => array(
72 'title' => ts('Contribution Pages'),
73 'tables' => array('civicrm_contribution_page'),
74 'url' => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
76 'rel_table_memberships' => array(
77 'title' => ts('Memberships'),
78 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
79 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
81 'rel_table_participants' => array(
82 'title' => ts('Participants'),
83 'tables' => array('civicrm_participant'),
84 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
86 'rel_table_events' => array(
87 'title' => ts('Events'),
88 'tables' => array('civicrm_event'),
89 'url' => CRM_Utils_System
::url('civicrm/event/manage', 'reset=1&cid=$cid'),
91 'rel_table_activities' => array(
92 'title' => ts('Activities'),
93 'tables' => array('civicrm_activity', 'civicrm_activity_target', 'civicrm_activity_assignment'),
94 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
96 'rel_table_relationships' => array(
97 'title' => ts('Relationships'),
98 'tables' => array('civicrm_relationship'),
99 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
101 'rel_table_custom_groups' => array(
102 'title' => ts('Custom Groups'),
103 'tables' => array('civicrm_custom_group'),
104 'url' => CRM_Utils_System
::url('civicrm/admin/custom/group', 'reset=1'),
106 'rel_table_uf_groups' => array(
107 'title' => ts('Profiles'),
108 'tables' => array('civicrm_uf_group'),
109 'url' => CRM_Utils_System
::url('civicrm/admin/uf/group', 'reset=1'),
111 'rel_table_groups' => array(
112 'title' => ts('Groups'),
113 'tables' => array('civicrm_group_contact'),
114 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
116 'rel_table_notes' => array(
117 'title' => ts('Notes'),
118 'tables' => array('civicrm_note'),
119 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
121 'rel_table_tags' => array(
122 'title' => ts('Tags'),
123 'tables' => array('civicrm_entity_tag'),
124 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
126 'rel_table_mailings' => array(
127 'title' => ts('Mailings'),
128 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
129 'url' => CRM_Utils_System
::url('civicrm/mailing', 'reset=1&force=1&cid=$cid'),
131 'rel_table_cases' => array(
132 'title' => ts('Cases'),
133 'tables' => array('civicrm_case_contact'),
134 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
136 'rel_table_grants' => array(
137 'title' => ts('Grants'),
138 'tables' => array('civicrm_grant'),
139 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
141 'rel_table_pcp' => array(
142 'title' => ts('PCPs'),
143 'tables' => array('civicrm_pcp'),
144 'url' => CRM_Utils_System
::url('civicrm/contribute/pcp/manage', 'reset=1'),
146 'rel_table_pledges' => array(
147 'title' => ts('Pledges'),
148 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
149 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
151 'rel_table_users' => array(
153 'tables' => array('civicrm_uf_match'),
154 'url' => $userRecordUrl,
158 // Allow hook_civicrm_merge() to adjust $relTables
159 CRM_Utils_Hook
::merge('relTables', $relTables);
165 * Returns the related tables groups for which a contact has any info entered
167 static function getActiveRelTables($cid) {
171 $relTables = self
::relTables();
172 $cidRefs = self
::cidRefs();
173 $eidRefs = self
::eidRefs();
174 foreach ($relTables as $group => $params) {
176 foreach ($params['tables'] as $table) {
177 if (isset($cidRefs[$table])) {
178 foreach ($cidRefs[$table] as $field) {
179 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
182 if (isset($eidRefs[$table])) {
183 foreach ($eidRefs[$table] as $entityTable => $entityId) {
184 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
187 foreach ($sqls as $sql) {
188 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
194 return array_unique($groups);
198 * Return tables and their fields referencing civicrm_contact.contact_id explicitely
200 static function cidRefs() {
203 // FIXME: this should be generated dynamically from the schema's
204 // foreign keys referencing civicrm_contact(id)
206 'civicrm_acl_cache' => array('contact_id'),
207 'civicrm_activity' => array('source_contact_id'),
208 'civicrm_activity_assignment' => array('assignee_contact_id'),
209 'civicrm_activity_target' => array('target_contact_id'),
210 'civicrm_case_contact' => array('contact_id'),
211 'civicrm_contact' => array('primary_contact_id'),
212 'civicrm_contribution' => array('contact_id', 'honor_contact_id'),
213 'civicrm_contribution_page' => array('created_id'),
214 'civicrm_contribution_recur' => array('contact_id'),
215 'civicrm_contribution_soft' => array('contact_id'),
216 'civicrm_custom_group' => array('created_id'),
217 'civicrm_entity_tag' => array('entity_id'),
218 'civicrm_event' => array('created_id'),
219 'civicrm_grant' => array('contact_id'),
220 'civicrm_group_contact' => array('contact_id'),
221 'civicrm_group_organization' => array('organization_id'),
222 'civicrm_log' => array('modified_id'),
223 'civicrm_mailing' => array('created_id', 'scheduled_id'),
224 'civicrm_mailing_event_queue' => array('contact_id'),
225 'civicrm_mailing_event_subscribe' => array('contact_id'),
226 'civicrm_membership' => array('contact_id'),
227 'civicrm_membership_log' => array('modified_id'),
228 'civicrm_membership_type' => array('member_of_contact_id'),
229 'civicrm_note' => array('contact_id'),
230 'civicrm_participant' => array('contact_id'),
231 'civicrm_pcp' => array('contact_id'),
232 'civicrm_relationship' => array('contact_id_a', 'contact_id_b'),
233 'civicrm_uf_match' => array('contact_id'),
234 'civicrm_uf_group' => array('created_id'),
235 'civicrm_pledge' => array('contact_id'),
238 // Add ContactReference custom fields CRM-9561
239 $sql = "SELECT cg.table_name, cf.column_name
240 FROM civicrm_custom_group cg, civicrm_custom_field cf
241 WHERE cg.id = cf.custom_group_id AND cf.data_type = 'ContactReference'";
242 $dao = CRM_Core_DAO
::executeQuery($sql);
243 while ($dao->fetch()) {
244 $cidRefs[$dao->table_name
][] = $dao->column_name
;
248 // Allow hook_civicrm_merge() to adjust $cidRefs
249 CRM_Utils_Hook
::merge('cidRefs', $cidRefs);
255 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
257 static function eidRefs() {
260 // FIXME: this should be generated dynamically from the schema
261 // tables that reference contacts with entity_{id,table}
263 'civicrm_acl' => array('entity_table' => 'entity_id'),
264 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
265 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
266 'civicrm_log' => array('entity_table' => 'entity_id'),
267 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
268 'civicrm_note' => array('entity_table' => 'entity_id'),
269 'civicrm_project' => array('owner_entity_table' => 'owner_entity_id'),
270 'civicrm_task' => array('owner_entity_table' => 'owner_entity_id'),
271 'civicrm_task_status' => array('responsible_entity_table' => 'responsible_entity_id', 'target_entity_table' => 'target_entity_id'),
274 // Allow hook_civicrm_merge() to adjust $eidRefs
275 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
281 * Tables which require custom processing should declare functions to call here.
282 * Doing so will override normal processing.
284 static function cpTables() {
288 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
289 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
290 // Empty array == do nothing - this table is handled by mergeGroupContact
291 'civicrm_subscription_history' => array(),
292 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
299 * return payment related table.
301 static function paymentTables() {
304 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
311 * return payment update Query.
313 static function paymentSql($tableName, $mainContactId, $otherContactId) {
315 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
319 $paymentTables = self
::paymentTables();
320 if (!in_array($tableName, $paymentTables)) {
324 switch ($tableName) {
325 case 'civicrm_pledge':
327 UPDATE IGNORE civicrm_contribution contribution
328 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
329 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
330 SET contribution.contact_id = $mainContactId
331 WHERE pledge.contact_id = $otherContactId";
334 case 'civicrm_membership':
336 UPDATE IGNORE civicrm_contribution contribution
337 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
338 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
339 SET contribution.contact_id = $mainContactId
340 WHERE membership.contact_id = $otherContactId";
343 case 'civicrm_participant':
345 UPDATE IGNORE civicrm_contribution contribution
346 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
347 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
348 SET contribution.contact_id = $mainContactId
349 WHERE participant.contact_id = $otherContactId";
356 static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
358 if (!$tableName ||
!$mainId ||
!$otherId) {
363 switch ($tableName) {
364 case 'civicrm_membership':
365 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add'])
367 if ($mode == 'add') {
369 DELETE membership1.* FROM civicrm_membership membership1
370 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
371 AND membership1.contact_id = {$mainId}
372 AND membership2.contact_id = {$otherId} ";
374 if ($mode == 'payment') {
376 DELETE contribution.* FROM civicrm_contribution contribution
377 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
378 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
379 AND membership1.contact_id = {$mainId}
380 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
381 AND membership2.contact_id = {$otherId}";
385 case 'civicrm_uf_match':
386 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
387 // failing to meet intended result. Therefore we introduce this additonal query:
388 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
396 * Based on the provided two contact_ids and a set of tables, move the
397 * belongings of the other contact to the main one.
401 static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
402 $cidRefs = self
::cidRefs();
403 $eidRefs = self
::eidRefs();
404 $cpTables = self
::cpTables();
405 $paymentTables = self
::paymentTables();
407 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
408 if ($tables !== FALSE) {
409 // if there are specific tables, sanitize the list
410 $affected = array_unique(array_intersect($affected, $tables));
413 // if there aren't any specific tables, don't affect the ones handled by relTables()
414 $relTables = self
::relTables();
416 foreach ($relTables as $params) {
417 $handled = array_merge($handled, $params['tables']);
419 $affected = array_diff($affected, $handled);
422 $mainId = (int) $mainId;
423 $otherId = (int) $otherId;
426 foreach ($affected as $table) {
427 // Call custom processing function for objects that require it
428 if (isset($cpTables[$table])) {
429 foreach ($cpTables[$table] as $className => $fnName) {
430 $className::$fnName($mainId, $otherId, $sqls);
432 // Skip normal processing
436 // use UPDATE IGNORE + DELETE query pair to skip on situations when
437 // there's a UNIQUE restriction on ($field, some_other_field) pair
438 if (isset($cidRefs[$table])) {
439 foreach ($cidRefs[$table] as $field) {
440 // carry related contributions CRM-5359
441 if (in_array($table, $paymentTables)) {
442 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
443 $sqls = array_merge($sqls, $payOprSqls);
445 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
446 $sqls = array_merge($sqls, $paymentSqls);
449 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
450 $sqls = array_merge($sqls, $preOperationSqls);
452 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
453 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
456 if (isset($eidRefs[$table])) {
457 foreach ($eidRefs[$table] as $entityTable => $entityId) {
458 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
459 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
464 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
465 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
467 // call the SQL queries in one transaction
468 $transaction = new CRM_Core_Transaction();
469 foreach ($sqls as $sql) {
470 CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, TRUE);
472 $transaction->commit();
476 * Find differences between contacts.
478 * @param array $main contact details
479 * @param array $other contact details
483 static function findDifferences($main, $other) {
485 'contact' => array(),
488 foreach (self
::$validFields as $validField) {
489 if (CRM_Utils_Array
::value($validField, $main) != CRM_Utils_Array
::value($validField, $other)) {
490 $result['contact'][] = $validField;
494 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
495 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
496 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
497 foreach ($keys as $key) {
498 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
499 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
500 if ($key1 != $key2) {
501 $result['custom'][] = $key;
508 * Function to batch merge a set of contacts based on rule-group and group.
510 * @param int $rgid rule group id
511 * @param int $gid group id
512 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
513 * Generally used with batch-merge.
514 * @param string $mode helps decide how to behave when there are conflicts.
515 * A 'safe' value skips the merge if there are any un-resolved conflicts.
516 * Does a force merge otherwise.
517 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
523 static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $redirectForPerformance = FALSE) {
524 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
525 $cacheKeyString = "merge {$contactType}";
526 $cacheKeyString .= $rgid ?
"_{$rgid}" : '_0';
527 $cacheKeyString .= $gid ?
"_{$gid}" : '_0';
528 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
529 pn.entity_id2 = de.contact_id2 )";
531 $limit = $redirectForPerformance ?
75 : 1;
532 $where = "de.id IS NULL LIMIT {$limit}";
534 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
535 if (empty($dupePairs) && !$redirectForPerformance) {
536 // If we haven't found any dupes, probably cache is empty.
537 // Try filling cache and give another try.
538 CRM_Core_BAO_PrevNextCache
::refillCache($rgid, $gid, $cacheKeyString);
539 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
542 $cacheParams = array(
543 'cache_key_string' => $cacheKeyString,
547 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
551 * Function to merge given set of contacts. Performs core operation.
553 * @param array $dupePairs set of pair of contacts for whom merge is to be done.
554 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
555 * Generally used with batch-merge.
556 * @param string $mode helps decide how to behave when there are conflicts.
557 * A 'safe' value skips the merge if there are any un-resolved conflicts.
558 * Does a force merge otherwise (aggressive mode).
559 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
565 static function merge($dupePairs = array(
566 ), $cacheParams = array(), $mode = 'safe',
567 $autoFlip = TRUE, $redirectForPerformance = FALSE
569 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
570 $resultStats = array('merged' => array(), 'skipped' => array());
572 // we don't want dupe caching to get reset after every-merge, and therefore set the
573 // doNotResetCache flag
574 $config = CRM_Core_Config
::singleton();
575 $config->doNotResetCache
= 1;
577 while (!empty($dupePairs)) {
578 foreach ($dupePairs as $dupes) {
579 $mainId = $dupes['dstID'];
580 $otherId = $dupes['srcID'];
581 // make sure that $mainId is the one with lower id number
582 if ($autoFlip && ($mainId > $otherId)) {
583 $mainId = $dupes['srcID'];
584 $otherId = $dupes['dstID'];
586 if (!$mainId ||
!$otherId) {
591 // Generate var $migrationInfo. The variable structure is exactly same as
592 // $formValues submitted during a UI merge for a pair of contacts.
593 $rowsElementsAndInfo = &CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId);
595 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
597 // add additional details that we might need to resolve conflicts
598 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
599 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
600 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
601 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
603 // go ahead with merge if there is no conflict
604 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode)) {
605 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo);
606 $resultStats['merged'][] = array('main_d' => $mainId, 'other_id' => $otherId);
609 $resultStats['skipped'][] = array('main_d' => $mainId, 'other_id' => $otherId);
612 // delete entry from PrevNextCache table so we don't consider the pair next time
613 // pair may have been flipped, so make sure we delete using both orders
614 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString);
615 CRM_Core_BAO_PrevNextCache
::deletePair($otherId, $mainId, $cacheKeyString);
617 CRM_Core_DAO
::freeResult();
618 unset($rowsElementsAndInfo, $migrationInfo);
621 if ($cacheKeyString && !$redirectForPerformance) {
622 // retrieve next pair of dupes
623 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
624 $cacheParams['join'],
625 $cacheParams['where']
629 // do not proceed. Terminate the loop
637 * A function which uses various rules / algorithms for choosing which contact to bias to
638 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
640 * @param int $mainId main contact with whom merge has to happen
641 * @param int $otherId duplicate contact which would be deleted after merge operation
642 * @param array $migrationInfo array of information about which elements to merge.
643 * @param string $mode helps decide how to behave when there are conflicts.
644 * A 'safe' value skips the merge if there are any un-resolved conflicts.
645 * Does a force merge otherwise (aggressive mode).
650 static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe') {
651 $conflicts = array();
652 $migrationData = array(
653 'old_migration_info' => $migrationInfo,
656 $allLocationTypes = CRM_Core_PseudoConstant
::locationType();
658 foreach ($migrationInfo as $key => $val) {
659 if ($val === "null") {
660 // Rule: no overwriting with empty values in any mode
661 unset($migrationInfo[$key]);
664 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::$validFields) or
665 substr($key, 0, 12) == 'move_custom_'
666 ) and $val != NULL) {
667 // Rule: if both main-contact has other-contact, let $mode decide if to merge a
668 // particular field or not
669 if (!empty($migrationInfo['rows'][$key]['main'])) {
670 // if main also has a value its a conflict
671 if ($mode == 'safe') {
672 // note it down & lets wait for response from the hook.
673 // For no response skip this merge
674 $conflicts[$key] = NULL;
676 elseif ($mode == 'aggressive') {
677 // let the main-field be overwritten
682 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
683 $locField = explode('_', $key);
684 $fieldName = $locField[2];
685 $fieldCount = $locField[3];
687 // Rule: resolve address conflict if any -
688 if ($fieldName == 'address') {
689 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
690 if (CRM_Utils_Array
::value('main_loc_address', $migrationInfo) &&
691 array_key_exists("main_{$mainNewLocTypeId}", $migrationInfo['main_loc_address'])) {
692 // main loc already has some address for the loc-type. Its a overwrite situation.
694 // look for next available loc-type
696 foreach ($allLocationTypes as $typeId => $typeLabel) {
697 if (!array_key_exists("main_{$typeId}", $migrationInfo['main_loc_address'])) {
698 $newTypeId = $typeId;
702 // try insert address at new available loc-type
703 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
705 elseif ($mode == 'safe') {
706 // note it down & lets wait for response from the hook.
707 // For no response skip this merge
708 $conflicts[$key] = NULL;
710 elseif ($mode == 'aggressive') {
711 // let the loc-type-id be same as that of other-contact & go ahead
712 // with merge assuming aggressive mode
717 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
718 // for loc blocks other than address like email, phone .. if values are same no point in merging
719 // and adding redundant value
720 unset($migrationInfo[$key]);
725 // A hook to implement other algorithms for choosing which contact to bias to when
726 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
727 // merge happens with new values filled in here. For a particular field / row not to be merged
728 // field should be unset from fields_in_conflict.
729 $migrationData['fields_in_conflict'] = $conflicts;
730 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
731 $conflicts = $migrationData['fields_in_conflict'];
733 if (!empty($conflicts)) {
734 foreach ($conflicts as $key => $val) {
735 if ($val === NULL and $mode == 'safe') {
736 // un-resolved conflicts still present. Lets skip this merge.
740 // copy over the resolved values
741 $migrationInfo[$key] = $val;
749 * A function to build an array of information required by merge function and the merge UI.
751 * @param int $mainId main contact with whom merge has to happen
752 * @param int $otherId duplicate contact which would be deleted after merge operation
757 static function getRowsElementsAndInfo($mainId, $otherId) {
758 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
761 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
762 $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self
::$validFields));
763 $result = civicrm_api('contact', 'get', $params);
765 if (empty($result['values'][$cid]['contact_type'])) {
768 $
$moniker = $result['values'][$cid];
771 static $fields = array();
772 if (empty($fields)) {
773 $fields = CRM_Contact_DAO_Contact
::fields();
774 CRM_Core_DAO
::freeResult();
777 // FIXME: there must be a better way
778 foreach (array('main', 'other') as $moniker) {
779 $contact = &$
$moniker;
780 $preferred_communication_method = CRM_Utils_array
::value('preferred_communication_method', $contact);
781 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
782 $specialValues[$moniker] = array(
783 'preferred_communication_method' => $value,
786 if (CRM_Utils_array
::value('preferred_communication_method', $contact)){
787 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
788 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
789 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues[$moniker]['preferred_communication_method']) :
790 $specialValues[$moniker]['preferred_communication_method'];
791 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
794 'preferred_communication_method' =>
796 'newName' => 'preferred_communication_method_display',
797 'groupName' => 'preferred_communication_method',
800 CRM_Core_OptionGroup
::lookupValues($specialValues[$moniker], $names);
803 static $optionValueFields = array();
804 if (empty($optionValueFields)) {
805 $optionValueFields = CRM_Core_OptionValue
::getFields();
807 foreach ($optionValueFields as $field => $params) {
808 $fields[$field]['title'] = $params['title'];
811 $diffs = self
::findDifferences($main, $other);
813 $rows = $elements = $relTableElements = $migrationInfo = array();
815 foreach ($diffs['contact'] as $field) {
816 foreach (array('main', 'other') as $moniker) {
817 $contact = &$
$moniker;
818 $value = CRM_Utils_Array
::value($field, $contact);
819 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
820 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
822 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
823 if (CRM_Utils_Array
::value('type', $fields[$field]) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
825 $value = str_replace('-', '', $value);
826 $label = CRM_Utils_Date
::customFormat($label);
832 elseif (CRM_Utils_Array
::value('type', $fields[$field]) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
833 if ($label === '0') {
836 if ($label === '1') {
839 } elseif ($field == 'individual_prefix' ||
$field == 'prefix_id') {
840 $label = CRM_Utils_Array
::value('prefix', $contact);
841 $value = CRM_Utils_Array
::value('prefix_id', $contact);
842 $field = 'prefix_id';
843 } elseif ($field == 'individual_suffix' ||
$field == 'suffix_id') {
844 $label = CRM_Utils_Array
::value('suffix', $contact);
845 $value = CRM_Utils_Array
::value('suffix_id', $contact);
846 $field = 'suffix_id';
848 $rows["move_$field"][$moniker] = $label;
849 if ($moniker == 'other') {
850 if ($value === NULL) {
853 if ($value === 0 or $value === '0') {
856 if (is_array($value) &&
857 !CRM_Utils_Array
::value(1, $value)) {
860 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
861 $migrationInfo["move_$field"] = $value;
864 $rows["move_$field"]['title'] = $fields[$field]['title'];
867 // handle location blocks.
868 $locationBlocks = array('email', 'phone', 'address');
869 $locations = array();
871 foreach ($locationBlocks as $block) {
872 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
874 $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
875 $count = $values['count'];
878 foreach ($values['values'] as $value) {
879 if ($block == 'address') {
880 CRM_Core_BAO_Address
::fixAddress($value);
881 $display = CRM_Utils_Address
::format($value);
882 $locations[$moniker][$block][$cnt] = $value;
883 $locations[$moniker][$block][$cnt]['display'] = $display;
886 $locations[$moniker][$block][$cnt] = $value;
894 if ($block == 'address') {
895 CRM_Core_BAO_Address
::fixAddress($values['values'][$id]);
896 $display = CRM_Utils_Address
::format($values['values'][$id]);
897 $locations[$moniker][$block][$cnt] = $values['values'][$id];
898 $locations[$moniker][$block][$cnt]['display'] = $display;
901 $locations[$moniker][$block][$cnt] = $values['values'][$id];
908 $allLocationTypes = CRM_Core_PseudoConstant
::locationType();
910 $mainLocBlock = $locBlockIds = array();
911 $locBlockIds['main'] = $locBlockIds['other'] = array();
912 foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
913 $name = strtolower($block);
914 foreach (array('main', 'other') as $moniker) {
915 $locIndex = CRM_Utils_Array
::value($moniker, $locations);
916 $blockValue = CRM_Utils_Array
::value($name, $locIndex, array());
917 if (empty($blockValue)) {
918 $locValue[$moniker][$name] = 0;
919 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
922 $locValue[$moniker][$name] = TRUE;
923 foreach ($blockValue as $count => $blkValues) {
925 $locTypeId = $blkValues['location_type_id'];
929 if ($name == 'address') {
930 $fldName = 'display';
932 $locLabel[$moniker][$name][$count] = CRM_Utils_Array
::value($fldName,
935 $locTypes[$moniker][$name][$count] = $locTypeId;
936 if ($moniker == 'main' && in_array($name, $locationBlocks)) {
937 $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array
::value($fldName,
940 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
943 $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
949 if ($locValue['other'][$name] != 0) {
950 foreach ($locLabel['other'][$name] as $count => $value) {
951 $locTypeId = $locTypes['other'][$name][$count];
952 $rows["move_location_{$name}_$count"]['other'] = $value;
953 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array
::value($count,
954 $locLabel['main'][$name]
956 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
960 3 => $allLocationTypes[$locTypeId]
964 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
965 $migrationInfo["move_location_{$name}_{$count}"] = 1;
967 // make sure default location type is always on top
968 $mainLocTypeId = CRM_Utils_Array
::value($count, $locTypes['main'][$name], $locTypeId);
969 $locTypeValues = $allLocationTypes;
970 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
971 unset($locTypeValues[$mainLocTypeId]);
973 // keep 1-1 mapping for address - location type.
975 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
976 $js = array('onChange' => "mergeBlock('$name', this, $count );");
979 'select', "location[{$name}][$count][locTypeId]", NULL,
980 $defaultLocType +
$locTypeValues, $js,
982 // keep location-type-id same as that of other-contact
983 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
985 if ($name != 'address') {
986 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
987 // always use add operation
988 $migrationInfo['location'][$name][$count]['operation'] = 1;
994 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
995 $config = CRM_Core_Config
::singleton();
996 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1000 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1001 $mainUser = user_load($mainUfId);
1003 elseif ($config->userFramework
== 'Joomla') {
1004 $mainUser = JFactory
::getUser($mainUfId);
1007 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1011 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1012 $otherUser = user_load($otherUfId);
1014 elseif ($config->userFramework
== 'Joomla') {
1015 $otherUser = JFactory
::getUser($otherUfId);
1019 $relTables = CRM_Dedupe_Merger
::relTables();
1020 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1021 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1022 foreach ($relTables as $name => $null) {
1023 if (!in_array($name, $activeRelTables) &&
1024 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1026 unset($relTables[$name]);
1030 $relTableElements[] = array('checkbox', "move_$name");
1031 $migrationInfo["move_$name"] = 1;
1033 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1034 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1035 if ($name == 'rel_table_users') {
1036 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1037 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1038 $find = array('$ufid', '$ufname');
1040 $replace = array($mainUfId, $mainUser->name
);
1041 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1044 $replace = array($otherUfId, $otherUser->name
);
1045 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1048 if ($name == 'rel_table_memberships') {
1049 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1050 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1053 foreach ($relTables as $name => $null) {
1054 $relTables["move_$name"] = $relTables[$name];
1055 unset($relTables[$name]);
1058 // handle custom fields
1059 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $mainId, -1,
1060 CRM_Utils_Array
::value('contact_sub_type', $main)
1062 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $otherId, -1,
1063 CRM_Utils_Array
::value('contact_sub_type', $other)
1065 CRM_Core_DAO
::freeResult();
1067 foreach ($otherTree as $gid => $group) {
1068 $foundField = FALSE;
1069 if (!isset($group['fields'])) {
1073 foreach ($group['fields'] as $fid => $field) {
1074 if (in_array($fid, $diffs['custom'])) {
1076 $rows["custom_group_$gid"]['title'] = $group['title'];
1079 if (CRM_Utils_Array
::value('customValue', $mainTree[$gid]['fields'][$fid])) {
1080 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1081 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1087 if (CRM_Utils_Array
::value('customValue', $otherTree[$gid]['fields'][$fid])) {
1088 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1089 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1092 if ($values['data'] === 0 ||
$values['data'] === '0') {
1093 $values['data'] = $qfZeroBug;
1095 $value = ($values['data']) ?
$values['data'] : $value;
1098 $rows["move_custom_$fid"]['title'] = $field['label'];
1100 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1101 $migrationInfo["move_custom_$fid"] = $value;
1107 'elements' => $elements,
1108 'rel_table_elements' => $relTableElements,
1109 'main_loc_block' => $mainLocBlock,
1110 'rel_tables' => $relTables,
1111 'main_details' => $main,
1112 'other_details' => $other,
1113 'migration_info' => $migrationInfo,
1116 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1117 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1123 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1124 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1125 * A superset of moveContactBelongings() function.
1127 * @param int $mainId main contact with whom merge has to happen
1128 * @param int $otherId duplicate contact which would be deleted after merge operation
1133 static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1134 if (empty($migrationInfo)) {
1138 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1139 $relTables = CRM_Dedupe_Merger
::relTables();
1140 $moveTables = $locBlocks = $tableOperations = array();
1141 foreach ($migrationInfo as $key => $value) {
1142 if ($value == $qfZeroBug) {
1145 if ((in_array(substr($key, 5), CRM_Dedupe_Merger
::$validFields) or
1146 substr($key, 0, 12) == 'move_custom_'
1147 ) and $value != NULL) {
1148 $submitted[substr($key, 5)] = $value;
1150 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1151 $locField = explode('_', $key);
1152 $fieldName = $locField[2];
1153 $fieldCount = $locField[3];
1154 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1155 // default operation is overwrite.
1160 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1161 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1163 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1164 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1165 if (array_key_exists('operation', $migrationInfo)) {
1166 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1167 if (array_key_exists($key, $migrationInfo['operation'])) {
1168 $tableOperations[$table] = $migrationInfo['operation'][$key];
1176 // **** Do location related migration:
1177 if (!empty($locBlocks)) {
1178 $locComponent = array(
1182 'openid' => 'OpenID',
1183 'address' => 'Address',
1186 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
1187 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
1189 foreach ($locBlocks as $name => $block) {
1190 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1193 $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
1194 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1195 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1197 foreach ($block as $blkCount => $values) {
1198 $locTypeId = CRM_Utils_Array
::value('locTypeId', $values, 1);
1199 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1200 $otherBlockId = CRM_Utils_Array
::value($blkCount,
1201 $migrationInfo['other_details']['loc_block_ids'][$name]
1204 // keep 1-1 mapping for address - loc type.
1206 if (array_key_exists($name, $locComponent)) {
1207 $idKey = $locTypeId;
1210 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1211 $mainBlockId = CRM_Utils_Array
::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1214 if (!$otherBlockId) {
1218 // for the block which belongs to other-contact, link the contact to main-contact
1219 $otherBlockDAO = new $daoName();
1220 $otherBlockDAO->id
= $otherBlockId;
1221 $otherBlockDAO->contact_id
= $mainId;
1222 $otherBlockDAO->location_type_id
= $locTypeId;
1224 // if main contact already has primary & billing, set the flags to 0.
1225 if ($primaryDAOId) {
1226 $otherBlockDAO->is_primary
= 0;
1228 if ($billingDAOId) {
1229 $otherBlockDAO->is_billing
= 0;
1232 // overwrite - need to delete block which belongs to main-contact.
1233 if ($mainBlockId && ($operation == 2)) {
1234 $deleteDAO = new $daoName();
1235 $deleteDAO->id
= $mainBlockId;
1236 $deleteDAO->find(TRUE);
1238 // if we about to delete a primary / billing block, set the flags for new block
1239 // that we going to assign to main-contact
1240 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1241 $otherBlockDAO->is_primary
= 1;
1243 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1244 $otherBlockDAO->is_billing
= 1;
1247 $deleteDAO->delete();
1251 $otherBlockDAO->update();
1252 $otherBlockDAO->free();
1257 // **** Do tables related migrations
1258 if (!empty($moveTables)) {
1259 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1260 unset($moveTables, $tableOperations);
1263 // **** Do contact related migrations
1264 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId);
1266 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1267 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1268 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1269 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1270 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1271 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1272 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1273 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1275 // fix custom fields so they're edible by createProfileContact()
1276 static $treeCache = array();
1277 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1278 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree($migrationInfo['main_details']['contact_type'],
1279 CRM_Core_DAO
::$_nullObject, NULL, -1
1282 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1285 foreach ($cgTree as $key => $group) {
1286 if (!isset($group['fields'])) {
1289 foreach ($group['fields'] as $fid => $field) {
1290 $cFields[$fid]['attributes'] = $field;
1294 if (!isset($submitted)) {
1295 $submitted = array();
1297 foreach ($submitted as $key => $value) {
1298 if (substr($key, 0, 7) == 'custom_') {
1299 $fid = (int) substr($key, 7);
1300 $htmlType = $cFields[$fid]['attributes']['html_type'];
1301 switch ($htmlType) {
1303 $customFiles[] = $fid;
1304 unset($submitted["custom_$fid"]);
1307 case 'Select Country':
1308 case 'Select State/Province':
1309 $submitted[$key] = CRM_Core_BAO_CustomField
::getDisplayValue($value, $fid, $cFields);
1313 case 'AdvMulti-Select':
1314 case 'Multi-Select':
1315 case 'Multi-Select Country':
1316 case 'Multi-Select State/Province':
1317 // Merge values from both contacts for multivalue fields, CRM-4385
1318 // get the existing custom values from db.
1319 $customParams = array('entityID' => $mainId, $key => TRUE);
1320 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1321 if (CRM_Utils_array
::value($key, $customfieldValues)) {
1322 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1323 if (is_array($existingValue) && !empty($existingValue)) {
1324 $mergeValue = $submmtedCustomValue = array();
1326 $submmtedCustomValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1329 //hack to remove null and duplicate values from array.
1330 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1331 if ($v != '' && !in_array($v, $mergeValue)) {
1336 //keep state and country as array format.
1337 //for checkbox and m-select format w/ VALUE_SEPARATOR
1338 if (in_array($htmlType, array(
1339 'CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
1340 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1342 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1345 $submitted[$key] = $mergeValue;
1349 elseif (in_array($htmlType, array(
1350 'Multi-Select Country', 'Multi-Select State/Province'))) {
1351 //we require submitted values should be in array format
1353 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1354 //hack to remove null values from array.
1355 $mergeValue = array();
1356 foreach ($mergeValueArray as $k => $v) {
1361 $submitted[$key] = $mergeValue;
1372 // **** Do file custom fields related migrations
1373 // FIXME: move this someplace else (one of the BAOs) after discussing
1374 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1375 // like, delete a file...
1377 if (!isset($customFiles)) {
1378 $customFiles = array();
1380 foreach ($customFiles as $customId) {
1381 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1383 // get the contact_id -> file_id mapping
1385 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1386 $dao = CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1387 while ($dao->fetch()) {
1388 $fileIds[$dao->entity_id
] = $dao->file_id
;
1392 // delete the main contact's file
1393 if (!empty($fileIds[$mainId])) {
1394 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1397 // move the other contact's file to main contact
1398 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1399 if ( CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}") ) {
1400 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1403 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1405 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1407 if ( CRM_Core_DAO
::singleValueQuery("
1409 FROM civicrm_entity_file
1410 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}") ) {
1412 UPDATE civicrm_entity_file
1413 SET entity_id = {$mainId}
1414 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1418 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1419 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1421 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1424 // move view only custom fields CRM-5362
1425 $viewOnlyCustomFields = array();
1426 foreach ($submitted as $key => $value) {
1427 $fid = (int) substr($key, 7);
1428 if (array_key_exists($fid, $cFields) &&
1429 CRM_Utils_Array
::value('is_view', $cFields[$fid]['attributes'])
1431 $viewOnlyCustomFields[$key] = $value;
1435 // special case to set values for view only, CRM-5362
1436 if (!empty($viewOnlyCustomFields)) {
1437 $viewOnlyCustomFields['entityID'] = $mainId;
1438 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1441 // **** Delete other contact & update prev-next caching
1442 $otherParams = array(
1443 'contact_id' => $otherId,
1447 if (CRM_Core_Permission
::check('merge duplicate contacts') &&
1448 CRM_Core_Permission
::check('delete contacts')
1450 // if ext id is submitted then set it null for contact to be deleted
1451 if (CRM_Utils_Array
::value('external_identifier', $submitted)) {
1452 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1453 CRM_Core_DAO
::executeQuery($query);
1456 civicrm_api('contact', 'delete', $otherParams);
1457 CRM_Core_BAO_PrevNextCache
::deleteItem($otherId);
1462 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1467 // **** Update contact related info for the main contact
1468 if (!empty($submitted)) {
1469 $submitted['contact_id'] = $mainId;
1471 //update current employer field
1472 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1473 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1474 $submitted['current_employer'] = $submitted['current_employer_id'];
1476 $submitted['current_employer'] = '';
1478 unset($submitted['current_employer_id']);
1481 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);