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_contact'),
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_contact' => array('contact_id'),
209 'civicrm_case_contact' => array('contact_id'),
210 'civicrm_contact' => array('primary_contact_id'),
211 'civicrm_contribution' => array('contact_id', 'honor_contact_id'),
212 'civicrm_contribution_page' => array('created_id'),
213 'civicrm_contribution_recur' => array('contact_id'),
214 'civicrm_contribution_soft' => array('contact_id'),
215 'civicrm_custom_group' => array('created_id'),
216 'civicrm_entity_tag' => array('entity_id'),
217 'civicrm_event' => array('created_id'),
218 'civicrm_grant' => array('contact_id'),
219 'civicrm_group_contact' => array('contact_id'),
220 'civicrm_group_organization' => array('organization_id'),
221 'civicrm_log' => array('modified_id'),
222 'civicrm_mailing' => array('created_id', 'scheduled_id'),
223 'civicrm_mailing_event_queue' => array('contact_id'),
224 'civicrm_mailing_event_subscribe' => array('contact_id'),
225 'civicrm_membership' => array('contact_id'),
226 'civicrm_membership_log' => array('modified_id'),
227 'civicrm_membership_type' => array('member_of_contact_id'),
228 'civicrm_note' => array('contact_id'),
229 'civicrm_participant' => array('contact_id'),
230 'civicrm_pcp' => array('contact_id'),
231 'civicrm_relationship' => array('contact_id_a', 'contact_id_b'),
232 'civicrm_uf_match' => array('contact_id'),
233 'civicrm_uf_group' => array('created_id'),
234 'civicrm_pledge' => array('contact_id'),
237 // Add ContactReference custom fields CRM-9561
238 $sql = "SELECT cg.table_name, cf.column_name
239 FROM civicrm_custom_group cg, civicrm_custom_field cf
240 WHERE cg.id = cf.custom_group_id AND cf.data_type = 'ContactReference'";
241 $dao = CRM_Core_DAO
::executeQuery($sql);
242 while ($dao->fetch()) {
243 $cidRefs[$dao->table_name
][] = $dao->column_name
;
247 // Allow hook_civicrm_merge() to adjust $cidRefs
248 CRM_Utils_Hook
::merge('cidRefs', $cidRefs);
254 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
256 static function eidRefs() {
259 // FIXME: this should be generated dynamically from the schema
260 // tables that reference contacts with entity_{id,table}
262 'civicrm_acl' => array('entity_table' => 'entity_id'),
263 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
264 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
265 'civicrm_log' => array('entity_table' => 'entity_id'),
266 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
267 'civicrm_note' => array('entity_table' => 'entity_id'),
268 'civicrm_project' => array('owner_entity_table' => 'owner_entity_id'),
269 'civicrm_task' => array('owner_entity_table' => 'owner_entity_id'),
270 'civicrm_task_status' => array('responsible_entity_table' => 'responsible_entity_id', 'target_entity_table' => 'target_entity_id'),
273 // Allow hook_civicrm_merge() to adjust $eidRefs
274 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
280 * Tables which require custom processing should declare functions to call here.
281 * Doing so will override normal processing.
283 static function cpTables() {
287 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
288 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
289 // Empty array == do nothing - this table is handled by mergeGroupContact
290 'civicrm_subscription_history' => array(),
291 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
298 * return payment related table.
300 static function paymentTables() {
303 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
310 * return payment update Query.
312 static function paymentSql($tableName, $mainContactId, $otherContactId) {
314 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
318 $paymentTables = self
::paymentTables();
319 if (!in_array($tableName, $paymentTables)) {
323 switch ($tableName) {
324 case 'civicrm_pledge':
326 UPDATE IGNORE civicrm_contribution contribution
327 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
328 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
329 SET contribution.contact_id = $mainContactId
330 WHERE pledge.contact_id = $otherContactId";
333 case 'civicrm_membership':
335 UPDATE IGNORE civicrm_contribution contribution
336 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
337 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
338 SET contribution.contact_id = $mainContactId
339 WHERE membership.contact_id = $otherContactId";
342 case 'civicrm_participant':
344 UPDATE IGNORE civicrm_contribution contribution
345 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
346 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
347 SET contribution.contact_id = $mainContactId
348 WHERE participant.contact_id = $otherContactId";
355 static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
357 if (!$tableName ||
!$mainId ||
!$otherId) {
362 switch ($tableName) {
363 case 'civicrm_membership':
364 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add'])
366 if ($mode == 'add') {
368 DELETE membership1.* FROM civicrm_membership membership1
369 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
370 AND membership1.contact_id = {$mainId}
371 AND membership2.contact_id = {$otherId} ";
373 if ($mode == 'payment') {
375 DELETE contribution.* FROM civicrm_contribution contribution
376 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
377 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
378 AND membership1.contact_id = {$mainId}
379 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
380 AND membership2.contact_id = {$otherId}";
384 case 'civicrm_uf_match':
385 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
386 // failing to meet intended result. Therefore we introduce this additonal query:
387 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
395 * Based on the provided two contact_ids and a set of tables, move the
396 * belongings of the other contact to the main one.
400 static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
401 $cidRefs = self
::cidRefs();
402 $eidRefs = self
::eidRefs();
403 $cpTables = self
::cpTables();
404 $paymentTables = self
::paymentTables();
406 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
407 if ($tables !== FALSE) {
408 // if there are specific tables, sanitize the list
409 $affected = array_unique(array_intersect($affected, $tables));
412 // if there aren't any specific tables, don't affect the ones handled by relTables()
413 $relTables = self
::relTables();
415 foreach ($relTables as $params) {
416 $handled = array_merge($handled, $params['tables']);
418 $affected = array_diff($affected, $handled);
421 $mainId = (int) $mainId;
422 $otherId = (int) $otherId;
425 foreach ($affected as $table) {
426 // Call custom processing function for objects that require it
427 if (isset($cpTables[$table])) {
428 foreach ($cpTables[$table] as $className => $fnName) {
429 $className::$fnName($mainId, $otherId, $sqls);
431 // Skip normal processing
435 // use UPDATE IGNORE + DELETE query pair to skip on situations when
436 // there's a UNIQUE restriction on ($field, some_other_field) pair
437 if (isset($cidRefs[$table])) {
438 foreach ($cidRefs[$table] as $field) {
439 // carry related contributions CRM-5359
440 if (in_array($table, $paymentTables)) {
441 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
442 $sqls = array_merge($sqls, $payOprSqls);
444 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
445 $sqls = array_merge($sqls, $paymentSqls);
448 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
449 $sqls = array_merge($sqls, $preOperationSqls);
451 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
452 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
455 if (isset($eidRefs[$table])) {
456 foreach ($eidRefs[$table] as $entityTable => $entityId) {
457 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
458 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
463 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
464 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
466 // call the SQL queries in one transaction
467 $transaction = new CRM_Core_Transaction();
468 foreach ($sqls as $sql) {
469 CRM_Core_DAO
::executeQuery($sql, array(), TRUE, NULL, TRUE);
471 $transaction->commit();
475 * Find differences between contacts.
477 * @param array $main contact details
478 * @param array $other contact details
482 static function findDifferences($main, $other) {
484 'contact' => array(),
487 foreach (self
::$validFields as $validField) {
488 if (CRM_Utils_Array
::value($validField, $main) != CRM_Utils_Array
::value($validField, $other)) {
489 $result['contact'][] = $validField;
493 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
494 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
495 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
496 foreach ($keys as $key) {
497 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
498 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
499 if ($key1 != $key2) {
500 $result['custom'][] = $key;
507 * Function to batch merge a set of contacts based on rule-group and group.
509 * @param int $rgid rule group id
510 * @param int $gid group id
511 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
512 * Generally used with batch-merge.
513 * @param string $mode helps decide how to behave when there are conflicts.
514 * A 'safe' value skips the merge if there are any un-resolved conflicts.
515 * Does a force merge otherwise.
516 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
522 static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $redirectForPerformance = FALSE) {
523 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
524 $cacheKeyString = "merge {$contactType}";
525 $cacheKeyString .= $rgid ?
"_{$rgid}" : '_0';
526 $cacheKeyString .= $gid ?
"_{$gid}" : '_0';
527 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
528 pn.entity_id2 = de.contact_id2 )";
530 $limit = $redirectForPerformance ?
75 : 1;
531 $where = "de.id IS NULL LIMIT {$limit}";
533 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
534 if (empty($dupePairs) && !$redirectForPerformance) {
535 // If we haven't found any dupes, probably cache is empty.
536 // Try filling cache and give another try.
537 CRM_Core_BAO_PrevNextCache
::refillCache($rgid, $gid, $cacheKeyString);
538 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
541 $cacheParams = array(
542 'cache_key_string' => $cacheKeyString,
546 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
550 * Function to merge given set of contacts. Performs core operation.
552 * @param array $dupePairs set of pair of contacts for whom merge is to be done.
553 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
554 * Generally used with batch-merge.
555 * @param string $mode helps decide how to behave when there are conflicts.
556 * A 'safe' value skips the merge if there are any un-resolved conflicts.
557 * Does a force merge otherwise (aggressive mode).
558 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
564 static function merge($dupePairs = array(
565 ), $cacheParams = array(), $mode = 'safe',
566 $autoFlip = TRUE, $redirectForPerformance = FALSE
568 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
569 $resultStats = array('merged' => array(), 'skipped' => array());
571 // we don't want dupe caching to get reset after every-merge, and therefore set the
572 // doNotResetCache flag
573 $config = CRM_Core_Config
::singleton();
574 $config->doNotResetCache
= 1;
576 while (!empty($dupePairs)) {
577 foreach ($dupePairs as $dupes) {
578 $mainId = $dupes['dstID'];
579 $otherId = $dupes['srcID'];
580 // make sure that $mainId is the one with lower id number
581 if ($autoFlip && ($mainId > $otherId)) {
582 $mainId = $dupes['srcID'];
583 $otherId = $dupes['dstID'];
585 if (!$mainId ||
!$otherId) {
590 // Generate var $migrationInfo. The variable structure is exactly same as
591 // $formValues submitted during a UI merge for a pair of contacts.
592 $rowsElementsAndInfo = &CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId);
594 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
596 // add additional details that we might need to resolve conflicts
597 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
598 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
599 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
600 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
602 // go ahead with merge if there is no conflict
603 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode)) {
604 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo);
605 $resultStats['merged'][] = array('main_d' => $mainId, 'other_id' => $otherId);
608 $resultStats['skipped'][] = array('main_d' => $mainId, 'other_id' => $otherId);
611 // delete entry from PrevNextCache table so we don't consider the pair next time
612 // pair may have been flipped, so make sure we delete using both orders
613 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString);
614 CRM_Core_BAO_PrevNextCache
::deletePair($otherId, $mainId, $cacheKeyString);
616 CRM_Core_DAO
::freeResult();
617 unset($rowsElementsAndInfo, $migrationInfo);
620 if ($cacheKeyString && !$redirectForPerformance) {
621 // retrieve next pair of dupes
622 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
623 $cacheParams['join'],
624 $cacheParams['where']
628 // do not proceed. Terminate the loop
636 * A function which uses various rules / algorithms for choosing which contact to bias to
637 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
639 * @param int $mainId main contact with whom merge has to happen
640 * @param int $otherId duplicate contact which would be deleted after merge operation
641 * @param array $migrationInfo array of information about which elements to merge.
642 * @param string $mode helps decide how to behave when there are conflicts.
643 * A 'safe' value skips the merge if there are any un-resolved conflicts.
644 * Does a force merge otherwise (aggressive mode).
649 static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe') {
650 $conflicts = array();
651 $migrationData = array(
652 'old_migration_info' => $migrationInfo,
655 $allLocationTypes = CRM_Core_PseudoConstant
::locationType();
657 foreach ($migrationInfo as $key => $val) {
658 if ($val === "null") {
659 // Rule: no overwriting with empty values in any mode
660 unset($migrationInfo[$key]);
663 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::$validFields) or
664 substr($key, 0, 12) == 'move_custom_'
665 ) and $val != NULL) {
666 // Rule: if both main-contact has other-contact, let $mode decide if to merge a
667 // particular field or not
668 if (!empty($migrationInfo['rows'][$key]['main'])) {
669 // if main also has a value its a conflict
670 if ($mode == 'safe') {
671 // note it down & lets wait for response from the hook.
672 // For no response skip this merge
673 $conflicts[$key] = NULL;
675 elseif ($mode == 'aggressive') {
676 // let the main-field be overwritten
681 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
682 $locField = explode('_', $key);
683 $fieldName = $locField[2];
684 $fieldCount = $locField[3];
686 // Rule: resolve address conflict if any -
687 if ($fieldName == 'address') {
688 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
689 if (CRM_Utils_Array
::value('main_loc_address', $migrationInfo) &&
690 array_key_exists("main_{$mainNewLocTypeId}", $migrationInfo['main_loc_address'])) {
691 // main loc already has some address for the loc-type. Its a overwrite situation.
693 // look for next available loc-type
695 foreach ($allLocationTypes as $typeId => $typeLabel) {
696 if (!array_key_exists("main_{$typeId}", $migrationInfo['main_loc_address'])) {
697 $newTypeId = $typeId;
701 // try insert address at new available loc-type
702 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
704 elseif ($mode == 'safe') {
705 // note it down & lets wait for response from the hook.
706 // For no response skip this merge
707 $conflicts[$key] = NULL;
709 elseif ($mode == 'aggressive') {
710 // let the loc-type-id be same as that of other-contact & go ahead
711 // with merge assuming aggressive mode
716 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
717 // for loc blocks other than address like email, phone .. if values are same no point in merging
718 // and adding redundant value
719 unset($migrationInfo[$key]);
724 // A hook to implement other algorithms for choosing which contact to bias to when
725 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
726 // merge happens with new values filled in here. For a particular field / row not to be merged
727 // field should be unset from fields_in_conflict.
728 $migrationData['fields_in_conflict'] = $conflicts;
729 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
730 $conflicts = $migrationData['fields_in_conflict'];
732 if (!empty($conflicts)) {
733 foreach ($conflicts as $key => $val) {
734 if ($val === NULL and $mode == 'safe') {
735 // un-resolved conflicts still present. Lets skip this merge.
739 // copy over the resolved values
740 $migrationInfo[$key] = $val;
748 * A function to build an array of information required by merge function and the merge UI.
750 * @param int $mainId main contact with whom merge has to happen
751 * @param int $otherId duplicate contact which would be deleted after merge operation
756 static function getRowsElementsAndInfo($mainId, $otherId) {
757 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
760 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
761 $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self
::$validFields));
762 $result = civicrm_api('contact', 'get', $params);
764 if (empty($result['values'][$cid]['contact_type'])) {
767 $
$moniker = $result['values'][$cid];
770 static $fields = array();
771 if (empty($fields)) {
772 $fields = CRM_Contact_DAO_Contact
::fields();
773 CRM_Core_DAO
::freeResult();
776 // FIXME: there must be a better way
777 foreach (array('main', 'other') as $moniker) {
778 $contact = &$
$moniker;
779 $preferred_communication_method = CRM_Utils_array
::value('preferred_communication_method', $contact);
780 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
781 $specialValues[$moniker] = array(
782 'preferred_communication_method' => $value,
785 if (CRM_Utils_array
::value('preferred_communication_method', $contact)){
786 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
787 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
788 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues[$moniker]['preferred_communication_method']) :
789 $specialValues[$moniker]['preferred_communication_method'];
790 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
793 'preferred_communication_method' =>
795 'newName' => 'preferred_communication_method_display',
796 'groupName' => 'preferred_communication_method',
799 CRM_Core_OptionGroup
::lookupValues($specialValues[$moniker], $names);
802 static $optionValueFields = array();
803 if (empty($optionValueFields)) {
804 $optionValueFields = CRM_Core_OptionValue
::getFields();
806 foreach ($optionValueFields as $field => $params) {
807 $fields[$field]['title'] = $params['title'];
810 $diffs = self
::findDifferences($main, $other);
812 $rows = $elements = $relTableElements = $migrationInfo = array();
814 foreach ($diffs['contact'] as $field) {
815 foreach (array('main', 'other') as $moniker) {
816 $contact = &$
$moniker;
817 $value = CRM_Utils_Array
::value($field, $contact);
818 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
819 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
821 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
822 if (CRM_Utils_Array
::value('type', $fields[$field]) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
824 $value = str_replace('-', '', $value);
825 $label = CRM_Utils_Date
::customFormat($label);
831 elseif (CRM_Utils_Array
::value('type', $fields[$field]) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
832 if ($label === '0') {
835 if ($label === '1') {
838 } elseif ($field == 'individual_prefix' ||
$field == 'prefix_id') {
839 $label = CRM_Utils_Array
::value('prefix', $contact);
840 $value = CRM_Utils_Array
::value('prefix_id', $contact);
841 $field = 'prefix_id';
842 } elseif ($field == 'individual_suffix' ||
$field == 'suffix_id') {
843 $label = CRM_Utils_Array
::value('suffix', $contact);
844 $value = CRM_Utils_Array
::value('suffix_id', $contact);
845 $field = 'suffix_id';
847 $rows["move_$field"][$moniker] = $label;
848 if ($moniker == 'other') {
849 if ($value === NULL) {
852 if ($value === 0 or $value === '0') {
855 if (is_array($value) &&
856 !CRM_Utils_Array
::value(1, $value)) {
859 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
860 $migrationInfo["move_$field"] = $value;
863 $rows["move_$field"]['title'] = $fields[$field]['title'];
866 // handle location blocks.
867 $locationBlocks = array('email', 'phone', 'address');
868 $locations = array();
870 foreach ($locationBlocks as $block) {
871 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
873 $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
874 $count = $values['count'];
877 foreach ($values['values'] as $value) {
878 if ($block == 'address') {
879 CRM_Core_BAO_Address
::fixAddress($value);
880 $display = CRM_Utils_Address
::format($value);
881 $locations[$moniker][$block][$cnt] = $value;
882 $locations[$moniker][$block][$cnt]['display'] = $display;
885 $locations[$moniker][$block][$cnt] = $value;
893 if ($block == 'address') {
894 CRM_Core_BAO_Address
::fixAddress($values['values'][$id]);
895 $display = CRM_Utils_Address
::format($values['values'][$id]);
896 $locations[$moniker][$block][$cnt] = $values['values'][$id];
897 $locations[$moniker][$block][$cnt]['display'] = $display;
900 $locations[$moniker][$block][$cnt] = $values['values'][$id];
907 $allLocationTypes = CRM_Core_PseudoConstant
::locationType();
909 $mainLocBlock = $locBlockIds = array();
910 $locBlockIds['main'] = $locBlockIds['other'] = array();
911 foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
912 $name = strtolower($block);
913 foreach (array('main', 'other') as $moniker) {
914 $locIndex = CRM_Utils_Array
::value($moniker, $locations);
915 $blockValue = CRM_Utils_Array
::value($name, $locIndex, array());
916 if (empty($blockValue)) {
917 $locValue[$moniker][$name] = 0;
918 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
921 $locValue[$moniker][$name] = TRUE;
922 foreach ($blockValue as $count => $blkValues) {
924 $locTypeId = $blkValues['location_type_id'];
928 if ($name == 'address') {
929 $fldName = 'display';
931 $locLabel[$moniker][$name][$count] = CRM_Utils_Array
::value($fldName,
934 $locTypes[$moniker][$name][$count] = $locTypeId;
935 if ($moniker == 'main' && in_array($name, $locationBlocks)) {
936 $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array
::value($fldName,
939 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
942 $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
948 if ($locValue['other'][$name] != 0) {
949 foreach ($locLabel['other'][$name] as $count => $value) {
950 $locTypeId = $locTypes['other'][$name][$count];
951 $rows["move_location_{$name}_$count"]['other'] = $value;
952 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array
::value($count,
953 $locLabel['main'][$name]
955 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
959 3 => $allLocationTypes[$locTypeId]
963 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
964 $migrationInfo["move_location_{$name}_{$count}"] = 1;
966 // make sure default location type is always on top
967 $mainLocTypeId = CRM_Utils_Array
::value($count, $locTypes['main'][$name], $locTypeId);
968 $locTypeValues = $allLocationTypes;
969 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
970 unset($locTypeValues[$mainLocTypeId]);
972 // keep 1-1 mapping for address - location type.
974 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
975 $js = array('onChange' => "mergeBlock('$name', this, $count );");
978 'select', "location[{$name}][$count][locTypeId]", NULL,
979 $defaultLocType +
$locTypeValues, $js,
981 // keep location-type-id same as that of other-contact
982 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
984 if ($name != 'address') {
985 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
986 // always use add operation
987 $migrationInfo['location'][$name][$count]['operation'] = 1;
993 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
994 $config = CRM_Core_Config
::singleton();
995 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
999 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1000 $mainUser = user_load($mainUfId);
1002 elseif ($config->userFramework
== 'Joomla') {
1003 $mainUser = JFactory
::getUser($mainUfId);
1006 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1010 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1011 $otherUser = user_load($otherUfId);
1013 elseif ($config->userFramework
== 'Joomla') {
1014 $otherUser = JFactory
::getUser($otherUfId);
1018 $relTables = CRM_Dedupe_Merger
::relTables();
1019 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1020 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1021 foreach ($relTables as $name => $null) {
1022 if (!in_array($name, $activeRelTables) &&
1023 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1025 unset($relTables[$name]);
1029 $relTableElements[] = array('checkbox', "move_$name");
1030 $migrationInfo["move_$name"] = 1;
1032 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1033 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1034 if ($name == 'rel_table_users') {
1035 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1036 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1037 $find = array('$ufid', '$ufname');
1039 $replace = array($mainUfId, $mainUser->name
);
1040 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1043 $replace = array($otherUfId, $otherUser->name
);
1044 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1047 if ($name == 'rel_table_memberships') {
1048 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1049 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1052 foreach ($relTables as $name => $null) {
1053 $relTables["move_$name"] = $relTables[$name];
1054 unset($relTables[$name]);
1057 // handle custom fields
1058 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $mainId, -1,
1059 CRM_Utils_Array
::value('contact_sub_type', $main)
1061 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $otherId, -1,
1062 CRM_Utils_Array
::value('contact_sub_type', $other)
1064 CRM_Core_DAO
::freeResult();
1066 foreach ($otherTree as $gid => $group) {
1067 $foundField = FALSE;
1068 if (!isset($group['fields'])) {
1072 foreach ($group['fields'] as $fid => $field) {
1073 if (in_array($fid, $diffs['custom'])) {
1075 $rows["custom_group_$gid"]['title'] = $group['title'];
1078 if (CRM_Utils_Array
::value('customValue', $mainTree[$gid]['fields'][$fid])) {
1079 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1080 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1086 if (CRM_Utils_Array
::value('customValue', $otherTree[$gid]['fields'][$fid])) {
1087 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1088 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1091 if ($values['data'] === 0 ||
$values['data'] === '0') {
1092 $values['data'] = $qfZeroBug;
1094 $value = ($values['data']) ?
$values['data'] : $value;
1097 $rows["move_custom_$fid"]['title'] = $field['label'];
1099 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1100 $migrationInfo["move_custom_$fid"] = $value;
1106 'elements' => $elements,
1107 'rel_table_elements' => $relTableElements,
1108 'main_loc_block' => $mainLocBlock,
1109 'rel_tables' => $relTables,
1110 'main_details' => $main,
1111 'other_details' => $other,
1112 'migration_info' => $migrationInfo,
1115 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1116 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1122 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1123 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1124 * A superset of moveContactBelongings() function.
1126 * @param int $mainId main contact with whom merge has to happen
1127 * @param int $otherId duplicate contact which would be deleted after merge operation
1132 static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1133 if (empty($migrationInfo)) {
1137 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1138 $relTables = CRM_Dedupe_Merger
::relTables();
1139 $moveTables = $locBlocks = $tableOperations = array();
1140 foreach ($migrationInfo as $key => $value) {
1141 if ($value == $qfZeroBug) {
1144 if ((in_array(substr($key, 5), CRM_Dedupe_Merger
::$validFields) or
1145 substr($key, 0, 12) == 'move_custom_'
1146 ) and $value != NULL) {
1147 $submitted[substr($key, 5)] = $value;
1149 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1150 $locField = explode('_', $key);
1151 $fieldName = $locField[2];
1152 $fieldCount = $locField[3];
1153 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1154 // default operation is overwrite.
1159 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1160 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1162 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1163 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1164 if (array_key_exists('operation', $migrationInfo)) {
1165 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1166 if (array_key_exists($key, $migrationInfo['operation'])) {
1167 $tableOperations[$table] = $migrationInfo['operation'][$key];
1175 // **** Do location related migration:
1176 if (!empty($locBlocks)) {
1177 $locComponent = array(
1181 'openid' => 'OpenID',
1182 'address' => 'Address',
1185 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
1186 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
1188 foreach ($locBlocks as $name => $block) {
1189 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1192 $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
1193 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1194 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1196 foreach ($block as $blkCount => $values) {
1197 $locTypeId = CRM_Utils_Array
::value('locTypeId', $values, 1);
1198 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1199 $otherBlockId = CRM_Utils_Array
::value($blkCount,
1200 $migrationInfo['other_details']['loc_block_ids'][$name]
1203 // keep 1-1 mapping for address - loc type.
1205 if (array_key_exists($name, $locComponent)) {
1206 $idKey = $locTypeId;
1209 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1210 $mainBlockId = CRM_Utils_Array
::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1213 if (!$otherBlockId) {
1217 // for the block which belongs to other-contact, link the contact to main-contact
1218 $otherBlockDAO = new $daoName();
1219 $otherBlockDAO->id
= $otherBlockId;
1220 $otherBlockDAO->contact_id
= $mainId;
1221 $otherBlockDAO->location_type_id
= $locTypeId;
1223 // if main contact already has primary & billing, set the flags to 0.
1224 if ($primaryDAOId) {
1225 $otherBlockDAO->is_primary
= 0;
1227 if ($billingDAOId) {
1228 $otherBlockDAO->is_billing
= 0;
1231 // overwrite - need to delete block which belongs to main-contact.
1232 if ($mainBlockId && ($operation == 2)) {
1233 $deleteDAO = new $daoName();
1234 $deleteDAO->id
= $mainBlockId;
1235 $deleteDAO->find(TRUE);
1237 // if we about to delete a primary / billing block, set the flags for new block
1238 // that we going to assign to main-contact
1239 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1240 $otherBlockDAO->is_primary
= 1;
1242 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1243 $otherBlockDAO->is_billing
= 1;
1246 $deleteDAO->delete();
1250 $otherBlockDAO->update();
1251 $otherBlockDAO->free();
1256 // **** Do tables related migrations
1257 if (!empty($moveTables)) {
1258 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1259 unset($moveTables, $tableOperations);
1262 // **** Do contact related migrations
1263 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId);
1265 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1266 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1267 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1268 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1269 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1270 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1271 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1272 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1274 // fix custom fields so they're edible by createProfileContact()
1275 static $treeCache = array();
1276 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1277 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree($migrationInfo['main_details']['contact_type'],
1278 CRM_Core_DAO
::$_nullObject, NULL, -1
1281 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1284 foreach ($cgTree as $key => $group) {
1285 if (!isset($group['fields'])) {
1288 foreach ($group['fields'] as $fid => $field) {
1289 $cFields[$fid]['attributes'] = $field;
1293 if (!isset($submitted)) {
1294 $submitted = array();
1296 foreach ($submitted as $key => $value) {
1297 if (substr($key, 0, 7) == 'custom_') {
1298 $fid = (int) substr($key, 7);
1299 $htmlType = $cFields[$fid]['attributes']['html_type'];
1300 switch ($htmlType) {
1302 $customFiles[] = $fid;
1303 unset($submitted["custom_$fid"]);
1306 case 'Select Country':
1307 case 'Select State/Province':
1308 $submitted[$key] = CRM_Core_BAO_CustomField
::getDisplayValue($value, $fid, $cFields);
1312 case 'AdvMulti-Select':
1313 case 'Multi-Select':
1314 case 'Multi-Select Country':
1315 case 'Multi-Select State/Province':
1316 // Merge values from both contacts for multivalue fields, CRM-4385
1317 // get the existing custom values from db.
1318 $customParams = array('entityID' => $mainId, $key => TRUE);
1319 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1320 if (CRM_Utils_array
::value($key, $customfieldValues)) {
1321 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1322 if (is_array($existingValue) && !empty($existingValue)) {
1323 $mergeValue = $submmtedCustomValue = array();
1325 $submmtedCustomValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1328 //hack to remove null and duplicate values from array.
1329 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1330 if ($v != '' && !in_array($v, $mergeValue)) {
1335 //keep state and country as array format.
1336 //for checkbox and m-select format w/ VALUE_SEPARATOR
1337 if (in_array($htmlType, array(
1338 'CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
1339 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1341 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1344 $submitted[$key] = $mergeValue;
1348 elseif (in_array($htmlType, array(
1349 'Multi-Select Country', 'Multi-Select State/Province'))) {
1350 //we require submitted values should be in array format
1352 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1353 //hack to remove null values from array.
1354 $mergeValue = array();
1355 foreach ($mergeValueArray as $k => $v) {
1360 $submitted[$key] = $mergeValue;
1371 // **** Do file custom fields related migrations
1372 // FIXME: move this someplace else (one of the BAOs) after discussing
1373 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1374 // like, delete a file...
1376 if (!isset($customFiles)) {
1377 $customFiles = array();
1379 foreach ($customFiles as $customId) {
1380 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1382 // get the contact_id -> file_id mapping
1384 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1385 $dao = CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1386 while ($dao->fetch()) {
1387 $fileIds[$dao->entity_id
] = $dao->file_id
;
1391 // delete the main contact's file
1392 if (!empty($fileIds[$mainId])) {
1393 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1396 // move the other contact's file to main contact
1397 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1398 if ( CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}") ) {
1399 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1402 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1404 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1406 if ( CRM_Core_DAO
::singleValueQuery("
1408 FROM civicrm_entity_file
1409 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}") ) {
1411 UPDATE civicrm_entity_file
1412 SET entity_id = {$mainId}
1413 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1417 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1418 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1420 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1423 // move view only custom fields CRM-5362
1424 $viewOnlyCustomFields = array();
1425 foreach ($submitted as $key => $value) {
1426 $fid = (int) substr($key, 7);
1427 if (array_key_exists($fid, $cFields) &&
1428 CRM_Utils_Array
::value('is_view', $cFields[$fid]['attributes'])
1430 $viewOnlyCustomFields[$key] = $value;
1434 // special case to set values for view only, CRM-5362
1435 if (!empty($viewOnlyCustomFields)) {
1436 $viewOnlyCustomFields['entityID'] = $mainId;
1437 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1440 // **** Delete other contact & update prev-next caching
1441 $otherParams = array(
1442 'contact_id' => $otherId,
1446 if (CRM_Core_Permission
::check('merge duplicate contacts') &&
1447 CRM_Core_Permission
::check('delete contacts')
1449 // if ext id is submitted then set it null for contact to be deleted
1450 if (CRM_Utils_Array
::value('external_identifier', $submitted)) {
1451 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1452 CRM_Core_DAO
::executeQuery($query);
1455 civicrm_api('contact', 'delete', $otherParams);
1456 CRM_Core_BAO_PrevNextCache
::deleteItem($otherId);
1461 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1466 // **** Update contact related info for the main contact
1467 if (!empty($submitted)) {
1468 $submitted['contact_id'] = $mainId;
1470 //update current employer field
1471 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1472 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1473 $submitted['current_employer'] = $submitted['current_employer_id'];
1475 $submitted['current_employer'] = '';
1477 unset($submitted['current_employer_id']);
1480 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);