3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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
{
37 // FIXME: consider creating a common structure with cidRefs() and eidRefs()
38 // FIXME: the sub-pages references by the URLs should
39 // be loaded dynamically on the merge form instead
40 static function relTables() {
43 $config = CRM_Core_Config
::singleton();
44 if ($config->userSystem
->is_drupal
) {
45 $userRecordUrl = CRM_Utils_System
::url('user/%ufid');
46 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
48 elseif ($config->userFramework
== 'Joomla') {
49 $userRecordUrl = $config->userFrameworkVersion
> 1.5 ?
$config->userFrameworkBaseURL
. "index.php?option=com_users&view=user&task=user.edit&id=" . '%ufid' : $config->userFrameworkBaseURL
. "index2.php?option=com_users&view=user&task=edit&id[]=" . '%ufid';
50 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework
, 2 => '$ufname', 3 => '$ufid'));
55 'rel_table_contributions' => array(
56 'title' => ts('Contributions'),
57 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
58 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
60 'rel_table_contribution_page' => array(
61 'title' => ts('Contribution Pages'),
62 'tables' => array('civicrm_contribution_page'),
63 'url' => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
65 'rel_table_memberships' => array(
66 'title' => ts('Memberships'),
67 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
68 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
70 'rel_table_participants' => array(
71 'title' => ts('Participants'),
72 'tables' => array('civicrm_participant'),
73 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
75 'rel_table_events' => array(
76 'title' => ts('Events'),
77 'tables' => array('civicrm_event'),
78 'url' => CRM_Utils_System
::url('civicrm/event/manage', 'reset=1&cid=$cid'),
80 'rel_table_activities' => array(
81 'title' => ts('Activities'),
82 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
83 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
85 'rel_table_relationships' => array(
86 'title' => ts('Relationships'),
87 'tables' => array('civicrm_relationship'),
88 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
90 'rel_table_custom_groups' => array(
91 'title' => ts('Custom Groups'),
92 'tables' => array('civicrm_custom_group'),
93 'url' => CRM_Utils_System
::url('civicrm/admin/custom/group', 'reset=1'),
95 'rel_table_uf_groups' => array(
96 'title' => ts('Profiles'),
97 'tables' => array('civicrm_uf_group'),
98 'url' => CRM_Utils_System
::url('civicrm/admin/uf/group', 'reset=1'),
100 'rel_table_groups' => array(
101 'title' => ts('Groups'),
102 'tables' => array('civicrm_group_contact'),
103 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
105 'rel_table_notes' => array(
106 'title' => ts('Notes'),
107 'tables' => array('civicrm_note'),
108 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
110 'rel_table_tags' => array(
111 'title' => ts('Tags'),
112 'tables' => array('civicrm_entity_tag'),
113 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
115 'rel_table_mailings' => array(
116 'title' => ts('Mailings'),
117 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
118 'url' => CRM_Utils_System
::url('civicrm/mailing', 'reset=1&force=1&cid=$cid'),
120 'rel_table_cases' => array(
121 'title' => ts('Cases'),
122 'tables' => array('civicrm_case_contact'),
123 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
125 'rel_table_grants' => array(
126 'title' => ts('Grants'),
127 'tables' => array('civicrm_grant'),
128 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
130 'rel_table_pcp' => array(
131 'title' => ts('PCPs'),
132 'tables' => array('civicrm_pcp'),
133 'url' => CRM_Utils_System
::url('civicrm/contribute/pcp/manage', 'reset=1'),
135 'rel_table_pledges' => array(
136 'title' => ts('Pledges'),
137 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
138 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
140 'rel_table_users' => array(
142 'tables' => array('civicrm_uf_match'),
143 'url' => $userRecordUrl,
147 // Allow hook_civicrm_merge() to adjust $relTables
148 CRM_Utils_Hook
::merge('relTables', $relTables);
154 * Returns the related tables groups for which a contact has any info entered
156 static function getActiveRelTables($cid) {
160 $relTables = self
::relTables();
161 $cidRefs = self
::cidRefs();
162 $eidRefs = self
::eidRefs();
163 foreach ($relTables as $group => $params) {
165 foreach ($params['tables'] as $table) {
166 if (isset($cidRefs[$table])) {
167 foreach ($cidRefs[$table] as $field) {
168 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
171 if (isset($eidRefs[$table])) {
172 foreach ($eidRefs[$table] as $entityTable => $entityId) {
173 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
176 foreach ($sqls as $sql) {
177 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
183 return array_unique($groups);
187 * Return tables and their fields referencing civicrm_contact.contact_id explicitely
189 static function cidRefs() {
192 // FIXME: this should be generated dynamically from the schema's
193 // foreign keys referencing civicrm_contact(id)
195 'civicrm_acl_cache' => array('contact_id'),
196 'civicrm_activity_contact' => array('contact_id'),
197 'civicrm_case_contact' => array('contact_id'),
198 'civicrm_contact' => array('primary_contact_id'),
199 'civicrm_contribution' => array('contact_id', 'honor_contact_id'),
200 'civicrm_contribution_page' => array('created_id'),
201 'civicrm_contribution_recur' => array('contact_id'),
202 'civicrm_contribution_soft' => array('contact_id'),
203 'civicrm_custom_group' => array('created_id'),
204 'civicrm_entity_tag' => array('entity_id'),
205 'civicrm_event' => array('created_id'),
206 'civicrm_grant' => array('contact_id'),
207 'civicrm_group_contact' => array('contact_id'),
208 'civicrm_group_organization' => array('organization_id'),
209 'civicrm_log' => array('modified_id'),
210 'civicrm_mailing' => array('created_id', 'scheduled_id'),
211 'civicrm_mailing_event_queue' => array('contact_id'),
212 'civicrm_mailing_event_subscribe' => array('contact_id'),
213 'civicrm_membership' => array('contact_id'),
214 'civicrm_membership_log' => array('modified_id'),
215 'civicrm_membership_type' => array('member_of_contact_id'),
216 'civicrm_note' => array('contact_id'),
217 'civicrm_participant' => array('contact_id'),
218 'civicrm_pcp' => array('contact_id'),
219 'civicrm_relationship' => array('contact_id_a', 'contact_id_b'),
220 'civicrm_uf_match' => array('contact_id'),
221 'civicrm_uf_group' => array('created_id'),
222 'civicrm_pledge' => array('contact_id'),
225 // Add ContactReference custom fields CRM-9561
226 $sql = "SELECT cg.table_name, cf.column_name
227 FROM civicrm_custom_group cg, civicrm_custom_field cf
228 WHERE cg.id = cf.custom_group_id AND cf.data_type = 'ContactReference'";
229 $dao = CRM_Core_DAO
::executeQuery($sql);
230 while ($dao->fetch()) {
231 $cidRefs[$dao->table_name
][] = $dao->column_name
;
235 // Allow hook_civicrm_merge() to adjust $cidRefs
236 CRM_Utils_Hook
::merge('cidRefs', $cidRefs);
242 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
244 static function eidRefs() {
247 // FIXME: this should be generated dynamically from the schema
248 // tables that reference contacts with entity_{id,table}
250 'civicrm_acl' => array('entity_table' => 'entity_id'),
251 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
252 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
253 'civicrm_log' => array('entity_table' => 'entity_id'),
254 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
255 'civicrm_note' => array('entity_table' => 'entity_id'),
258 // Allow hook_civicrm_merge() to adjust $eidRefs
259 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
265 * Tables which require custom processing should declare functions to call here.
266 * Doing so will override normal processing.
268 static function cpTables() {
272 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
273 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
274 // Empty array == do nothing - this table is handled by mergeGroupContact
275 'civicrm_subscription_history' => array(),
276 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
283 * return payment related table.
285 static function paymentTables() {
288 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
295 * return payment update Query.
297 static function paymentSql($tableName, $mainContactId, $otherContactId) {
299 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
303 $paymentTables = self
::paymentTables();
304 if (!in_array($tableName, $paymentTables)) {
308 switch ($tableName) {
309 case 'civicrm_pledge':
311 UPDATE IGNORE civicrm_contribution contribution
312 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
313 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
314 SET contribution.contact_id = $mainContactId
315 WHERE pledge.contact_id = $otherContactId";
318 case 'civicrm_membership':
320 UPDATE IGNORE civicrm_contribution contribution
321 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
322 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
323 SET contribution.contact_id = $mainContactId
324 WHERE membership.contact_id = $otherContactId";
327 case 'civicrm_participant':
329 UPDATE IGNORE civicrm_contribution contribution
330 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
331 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
332 SET contribution.contact_id = $mainContactId
333 WHERE participant.contact_id = $otherContactId";
340 static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
342 if (!$tableName ||
!$mainId ||
!$otherId) {
347 switch ($tableName) {
348 case 'civicrm_membership':
349 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add'])
351 if ($mode == 'add') {
353 DELETE membership1.* FROM civicrm_membership membership1
354 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
355 AND membership1.contact_id = {$mainId}
356 AND membership2.contact_id = {$otherId} ";
358 if ($mode == 'payment') {
360 DELETE contribution.* FROM civicrm_contribution contribution
361 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
362 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
363 AND membership1.contact_id = {$mainId}
364 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
365 AND membership2.contact_id = {$otherId}";
369 case 'civicrm_uf_match':
370 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
371 // failing to meet intended result. Therefore we introduce this additonal query:
372 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
380 * Based on the provided two contact_ids and a set of tables, move the
381 * belongings of the other contact to the main one.
385 static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
386 $cidRefs = self
::cidRefs();
387 $eidRefs = self
::eidRefs();
388 $cpTables = self
::cpTables();
389 $paymentTables = self
::paymentTables();
390 $membershipMerge = FALSE; // CRM-12695
392 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
393 if ($tables !== FALSE) {
394 // if there are specific tables, sanitize the list
395 $affected = array_unique(array_intersect($affected, $tables));
398 // if there aren't any specific tables, don't affect the ones handled by relTables()
399 $relTables = self
::relTables();
401 foreach ($relTables as $params) {
402 $handled = array_merge($handled, $params['tables']);
404 $affected = array_diff($affected, $handled);
407 * Set $membershipMerge flag only once
408 * while doing contact related migration
409 * to call addMembershipToRealtedContacts()
410 * function only once.
411 * Since the current function (moveContactBelongings) is called twice
412 * with & without parameters $tables & $tableOperations
414 // retrieve main contact's related table(s)
415 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
416 // check if membership table exists in main contact's related table(s)
417 if (in_array('rel_table_memberships', $activeMainRelTables)) {
418 $membershipMerge = TRUE; // set membership flag - CRM-12695
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);
473 if ($membershipMerge) {
474 // call to function adding membership to related contacts
475 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
477 $transaction->commit();
481 * Find differences between contacts.
483 * @param array $main contact details
484 * @param array $other contact details
488 static function findDifferences($main, $other) {
490 'contact' => array(),
493 foreach (self
::getContactFields() as $validField) {
494 if (CRM_Utils_Array
::value($validField, $main) != CRM_Utils_Array
::value($validField, $other)) {
495 $result['contact'][] = $validField;
499 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
500 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
501 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
502 foreach ($keys as $key) {
503 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
504 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
505 if ($key1 != $key2) {
506 $result['custom'][] = $key;
513 * Function to batch merge a set of contacts based on rule-group and group.
515 * @param int $rgid rule group id
516 * @param int $gid group id
517 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
518 * Generally used with batch-merge.
519 * @param string $mode helps decide how to behave when there are conflicts.
520 * A 'safe' value skips the merge if there are any un-resolved conflicts.
521 * Does a force merge otherwise.
522 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
528 static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $redirectForPerformance = FALSE) {
529 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
530 $cacheKeyString = "merge {$contactType}";
531 $cacheKeyString .= $rgid ?
"_{$rgid}" : '_0';
532 $cacheKeyString .= $gid ?
"_{$gid}" : '_0';
533 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
534 pn.entity_id2 = de.contact_id2 )";
536 $limit = $redirectForPerformance ?
75 : 1;
537 $where = "de.id IS NULL LIMIT {$limit}";
539 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
540 if (empty($dupePairs) && !$redirectForPerformance) {
541 // If we haven't found any dupes, probably cache is empty.
542 // Try filling cache and give another try.
543 CRM_Core_BAO_PrevNextCache
::refillCache($rgid, $gid, $cacheKeyString);
544 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $where);
547 $cacheParams = array(
548 'cache_key_string' => $cacheKeyString,
552 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
556 * Function to merge given set of contacts. Performs core operation.
558 * @param array $dupePairs set of pair of contacts for whom merge is to be done.
559 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
560 * Generally used with batch-merge.
561 * @param string $mode helps decide how to behave when there are conflicts.
562 * A 'safe' value skips the merge if there are any un-resolved conflicts.
563 * Does a force merge otherwise (aggressive mode).
564 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
570 static function merge($dupePairs = array(
571 ), $cacheParams = array(), $mode = 'safe',
572 $autoFlip = TRUE, $redirectForPerformance = FALSE
574 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
575 $resultStats = array('merged' => array(), 'skipped' => array());
577 // we don't want dupe caching to get reset after every-merge, and therefore set the
578 // doNotResetCache flag
579 $config = CRM_Core_Config
::singleton();
580 $config->doNotResetCache
= 1;
582 while (!empty($dupePairs)) {
583 foreach ($dupePairs as $dupes) {
584 $mainId = $dupes['dstID'];
585 $otherId = $dupes['srcID'];
586 // make sure that $mainId is the one with lower id number
587 if ($autoFlip && ($mainId > $otherId)) {
588 $mainId = $dupes['srcID'];
589 $otherId = $dupes['dstID'];
591 if (!$mainId ||
!$otherId) {
596 // Generate var $migrationInfo. The variable structure is exactly same as
597 // $formValues submitted during a UI merge for a pair of contacts.
598 $rowsElementsAndInfo = &CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId);
600 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
602 // add additional details that we might need to resolve conflicts
603 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
604 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
605 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
606 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
608 // go ahead with merge if there is no conflict
609 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode)) {
610 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo);
611 $resultStats['merged'][] = array('main_d' => $mainId, 'other_id' => $otherId);
614 $resultStats['skipped'][] = array('main_d' => $mainId, 'other_id' => $otherId);
617 // delete entry from PrevNextCache table so we don't consider the pair next time
618 // pair may have been flipped, so make sure we delete using both orders
619 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString);
620 CRM_Core_BAO_PrevNextCache
::deletePair($otherId, $mainId, $cacheKeyString);
622 CRM_Core_DAO
::freeResult();
623 unset($rowsElementsAndInfo, $migrationInfo);
626 if ($cacheKeyString && !$redirectForPerformance) {
627 // retrieve next pair of dupes
628 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
629 $cacheParams['join'],
630 $cacheParams['where']
634 // do not proceed. Terminate the loop
642 * A function which uses various rules / algorithms for choosing which contact to bias to
643 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
645 * @param int $mainId main contact with whom merge has to happen
646 * @param int $otherId duplicate contact which would be deleted after merge operation
647 * @param array $migrationInfo array of information about which elements to merge.
648 * @param string $mode helps decide how to behave when there are conflicts.
649 * A 'safe' value skips the merge if there are any un-resolved conflicts.
650 * Does a force merge otherwise (aggressive mode).
655 static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe') {
656 $conflicts = array();
657 $migrationData = array(
658 'old_migration_info' => $migrationInfo,
661 $allLocationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
663 foreach ($migrationInfo as $key => $val) {
664 if ($val === "null") {
665 // Rule: no overwriting with empty values in any mode
666 unset($migrationInfo[$key]);
669 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
670 substr($key, 0, 12) == 'move_custom_'
671 ) and $val != NULL) {
672 // Rule: if both main-contact has other-contact, let $mode decide if to merge a
673 // particular field or not
674 if (!empty($migrationInfo['rows'][$key]['main'])) {
675 // if main also has a value its a conflict
676 if ($mode == 'safe') {
677 // note it down & lets wait for response from the hook.
678 // For no response skip this merge
679 $conflicts[$key] = NULL;
681 elseif ($mode == 'aggressive') {
682 // let the main-field be overwritten
687 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
688 $locField = explode('_', $key);
689 $fieldName = $locField[2];
690 $fieldCount = $locField[3];
692 // Rule: resolve address conflict if any -
693 if ($fieldName == 'address') {
694 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
695 if (CRM_Utils_Array
::value('main_loc_address', $migrationInfo) &&
696 array_key_exists("main_{$mainNewLocTypeId}", $migrationInfo['main_loc_address'])) {
697 // main loc already has some address for the loc-type. Its a overwrite situation.
699 // look for next available loc-type
701 foreach ($allLocationTypes as $typeId => $typeLabel) {
702 if (!array_key_exists("main_{$typeId}", $migrationInfo['main_loc_address'])) {
703 $newTypeId = $typeId;
707 // try insert address at new available loc-type
708 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
710 elseif ($mode == 'safe') {
711 // note it down & lets wait for response from the hook.
712 // For no response skip this merge
713 $conflicts[$key] = NULL;
715 elseif ($mode == 'aggressive') {
716 // let the loc-type-id be same as that of other-contact & go ahead
717 // with merge assuming aggressive mode
722 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
723 // for loc blocks other than address like email, phone .. if values are same no point in merging
724 // and adding redundant value
725 unset($migrationInfo[$key]);
730 // A hook to implement other algorithms for choosing which contact to bias to when
731 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
732 // merge happens with new values filled in here. For a particular field / row not to be merged
733 // field should be unset from fields_in_conflict.
734 $migrationData['fields_in_conflict'] = $conflicts;
735 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
736 $conflicts = $migrationData['fields_in_conflict'];
738 if (!empty($conflicts)) {
739 foreach ($conflicts as $key => $val) {
740 if ($val === NULL and $mode == 'safe') {
741 // un-resolved conflicts still present. Lets skip this merge.
745 // copy over the resolved values
746 $migrationInfo[$key] = $val;
754 * A function to build an array of information required by merge function and the merge UI.
756 * @param int $mainId main contact with whom merge has to happen
757 * @param int $otherId duplicate contact which would be deleted after merge operation
762 static function getRowsElementsAndInfo($mainId, $otherId) {
763 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
766 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
767 $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self
::getContactFields()));
768 $result = civicrm_api('contact', 'get', $params);
770 if (empty($result['values'][$cid]['contact_type'])) {
773 $
$moniker = $result['values'][$cid];
776 static $fields = array();
777 if (empty($fields)) {
778 $fields = CRM_Contact_DAO_Contact
::fields();
779 CRM_Core_DAO
::freeResult();
782 // FIXME: there must be a better way
783 foreach (array('main', 'other') as $moniker) {
784 $contact = &$
$moniker;
785 $preferred_communication_method = CRM_Utils_array
::value('preferred_communication_method', $contact);
786 $value = empty($preferred_communication_method) ?
array() : $preferred_communication_method;
787 $specialValues[$moniker] = array(
788 'preferred_communication_method' => $value,
791 if (CRM_Utils_array
::value('preferred_communication_method', $contact)){
792 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
793 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
794 implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $specialValues[$moniker]['preferred_communication_method']) :
795 $specialValues[$moniker]['preferred_communication_method'];
796 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $prefCommList . CRM_Core_DAO
::VALUE_SEPARATOR
;
799 'preferred_communication_method' =>
801 'newName' => 'preferred_communication_method_display',
802 'groupName' => 'preferred_communication_method',
805 CRM_Core_OptionGroup
::lookupValues($specialValues[$moniker], $names);
808 static $optionValueFields = array();
809 if (empty($optionValueFields)) {
810 $optionValueFields = CRM_Core_OptionValue
::getFields();
812 foreach ($optionValueFields as $field => $params) {
813 $fields[$field]['title'] = $params['title'];
816 $diffs = self
::findDifferences($main, $other);
818 $rows = $elements = $relTableElements = $migrationInfo = array();
820 foreach ($diffs['contact'] as $field) {
821 foreach (array('main', 'other') as $moniker) {
822 $contact = &$
$moniker;
823 $value = CRM_Utils_Array
::value($field, $contact);
824 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
825 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. trim($specialValues[$moniker][$field], CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
827 $label = isset($specialValues[$moniker]["{$field}_display"]) ?
$specialValues[$moniker]["{$field}_display"] : $value;
828 if (CRM_Utils_Array
::value('type', $fields[$field]) && $fields[$field]['type'] == CRM_Utils_Type
::T_DATE
) {
830 $value = str_replace('-', '', $value);
831 $label = CRM_Utils_Date
::customFormat($label);
837 elseif (CRM_Utils_Array
::value('type', $fields[$field]) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
838 if ($label === '0') {
841 if ($label === '1') {
844 } elseif ($field == 'individual_prefix' ||
$field == 'prefix_id') {
845 $label = CRM_Utils_Array
::value('prefix', $contact);
846 $value = CRM_Utils_Array
::value('prefix_id', $contact);
847 $field = 'prefix_id';
848 } elseif ($field == 'individual_suffix' ||
$field == 'suffix_id') {
849 $label = CRM_Utils_Array
::value('suffix', $contact);
850 $value = CRM_Utils_Array
::value('suffix_id', $contact);
851 $field = 'suffix_id';
853 $rows["move_$field"][$moniker] = $label;
854 if ($moniker == 'other') {
855 if ($value === NULL) {
858 if ($value === 0 or $value === '0') {
861 if (is_array($value) &&
862 !CRM_Utils_Array
::value(1, $value)) {
865 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
866 $migrationInfo["move_$field"] = $value;
869 $rows["move_$field"]['title'] = $fields[$field]['title'];
872 // handle location blocks.
873 $locationBlocks = array('email', 'phone', 'address');
874 $locations = array();
876 foreach ($locationBlocks as $block) {
877 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
879 $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
880 $count = $values['count'];
883 foreach ($values['values'] as $value) {
884 if ($block == 'address') {
885 CRM_Core_BAO_Address
::fixAddress($value);
886 $display = CRM_Utils_Address
::format($value);
887 $locations[$moniker][$block][$cnt] = $value;
888 $locations[$moniker][$block][$cnt]['display'] = $display;
891 $locations[$moniker][$block][$cnt] = $value;
899 if ($block == 'address') {
900 CRM_Core_BAO_Address
::fixAddress($values['values'][$id]);
901 $display = CRM_Utils_Address
::format($values['values'][$id]);
902 $locations[$moniker][$block][$cnt] = $values['values'][$id];
903 $locations[$moniker][$block][$cnt]['display'] = $display;
906 $locations[$moniker][$block][$cnt] = $values['values'][$id];
913 $allLocationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
915 $mainLocBlock = $locBlockIds = array();
916 $locBlockIds['main'] = $locBlockIds['other'] = array();
917 foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
918 $name = strtolower($block);
919 foreach (array('main', 'other') as $moniker) {
920 $locIndex = CRM_Utils_Array
::value($moniker, $locations);
921 $blockValue = CRM_Utils_Array
::value($name, $locIndex, array());
922 if (empty($blockValue)) {
923 $locValue[$moniker][$name] = 0;
924 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
927 $locValue[$moniker][$name] = TRUE;
928 foreach ($blockValue as $count => $blkValues) {
930 $locTypeId = $blkValues['location_type_id'];
934 if ($name == 'address') {
935 $fldName = 'display';
937 $locLabel[$moniker][$name][$count] = CRM_Utils_Array
::value($fldName,
940 $locTypes[$moniker][$name][$count] = $locTypeId;
941 if ($moniker == 'main' && in_array($name, $locationBlocks)) {
942 $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array
::value($fldName,
945 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
948 $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
954 if ($locValue['other'][$name] != 0) {
955 foreach ($locLabel['other'][$name] as $count => $value) {
956 $locTypeId = $locTypes['other'][$name][$count];
957 $rows["move_location_{$name}_$count"]['other'] = $value;
958 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array
::value($count,
959 $locLabel['main'][$name]
961 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
965 3 => $allLocationTypes[$locTypeId]
969 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
970 $migrationInfo["move_location_{$name}_{$count}"] = 1;
972 // make sure default location type is always on top
973 $mainLocTypeId = CRM_Utils_Array
::value($count, $locTypes['main'][$name], $locTypeId);
974 $locTypeValues = $allLocationTypes;
975 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
976 unset($locTypeValues[$mainLocTypeId]);
978 // keep 1-1 mapping for address - location type.
980 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
981 $js = array('onChange' => "mergeBlock('$name', this, $count );");
984 'select', "location[{$name}][$count][locTypeId]", NULL,
985 $defaultLocType +
$locTypeValues, $js,
987 // keep location-type-id same as that of other-contact
988 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
990 if ($name != 'address') {
991 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
992 // always use add operation
993 $migrationInfo['location'][$name][$count]['operation'] = 1;
999 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1000 $config = CRM_Core_Config
::singleton();
1001 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1005 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1006 $mainUser = user_load($mainUfId);
1008 elseif ($config->userFramework
== 'Joomla') {
1009 $mainUser = JFactory
::getUser($mainUfId);
1012 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1016 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1017 $otherUser = user_load($otherUfId);
1019 elseif ($config->userFramework
== 'Joomla') {
1020 $otherUser = JFactory
::getUser($otherUfId);
1024 $relTables = CRM_Dedupe_Merger
::relTables();
1025 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1026 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1027 foreach ($relTables as $name => $null) {
1028 if (!in_array($name, $activeRelTables) &&
1029 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1031 unset($relTables[$name]);
1035 $relTableElements[] = array('checkbox', "move_$name");
1036 $migrationInfo["move_$name"] = 1;
1038 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1039 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1040 if ($name == 'rel_table_users') {
1041 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1042 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1043 $find = array('$ufid', '$ufname');
1045 $replace = array($mainUfId, $mainUser->name
);
1046 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1049 $replace = array($otherUfId, $otherUser->name
);
1050 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1053 if ($name == 'rel_table_memberships') {
1054 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1055 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1058 foreach ($relTables as $name => $null) {
1059 $relTables["move_$name"] = $relTables[$name];
1060 unset($relTables[$name]);
1063 // handle custom fields
1064 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $mainId, -1,
1065 CRM_Utils_Array
::value('contact_sub_type', $main)
1067 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], CRM_Core_DAO
::$_nullObject, $otherId, -1,
1068 CRM_Utils_Array
::value('contact_sub_type', $other)
1070 CRM_Core_DAO
::freeResult();
1072 foreach ($otherTree as $gid => $group) {
1073 $foundField = FALSE;
1074 if (!isset($group['fields'])) {
1078 foreach ($group['fields'] as $fid => $field) {
1079 if (in_array($fid, $diffs['custom'])) {
1081 $rows["custom_group_$gid"]['title'] = $group['title'];
1084 if (CRM_Utils_Array
::value('customValue', $mainTree[$gid]['fields'][$fid])) {
1085 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1086 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1092 if (CRM_Utils_Array
::value('customValue', $otherTree[$gid]['fields'][$fid])) {
1093 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1094 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup
::formatCustomValues($values,
1097 if ($values['data'] === 0 ||
$values['data'] === '0') {
1098 $values['data'] = $qfZeroBug;
1100 $value = ($values['data']) ?
$values['data'] : $value;
1103 $rows["move_custom_$fid"]['title'] = $field['label'];
1105 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1106 $migrationInfo["move_custom_$fid"] = $value;
1112 'elements' => $elements,
1113 'rel_table_elements' => $relTableElements,
1114 'main_loc_block' => $mainLocBlock,
1115 'rel_tables' => $relTables,
1116 'main_details' => $main,
1117 'other_details' => $other,
1118 'migration_info' => $migrationInfo,
1121 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1122 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1128 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1129 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1130 * A superset of moveContactBelongings() function.
1132 * @param int $mainId main contact with whom merge has to happen
1133 * @param int $otherId duplicate contact which would be deleted after merge operation
1138 static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1139 if (empty($migrationInfo)) {
1143 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1144 $relTables = CRM_Dedupe_Merger
::relTables();
1145 $moveTables = $locBlocks = $tableOperations = array();
1146 foreach ($migrationInfo as $key => $value) {
1147 if ($value == $qfZeroBug) {
1150 if ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
1151 substr($key, 0, 12) == 'move_custom_'
1152 ) and $value != NULL) {
1153 $submitted[substr($key, 5)] = $value;
1155 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1156 $locField = explode('_', $key);
1157 $fieldName = $locField[2];
1158 $fieldCount = $locField[3];
1159 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1160 // default operation is overwrite.
1165 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1166 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1168 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1169 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1170 if (array_key_exists('operation', $migrationInfo)) {
1171 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1172 if (array_key_exists($key, $migrationInfo['operation'])) {
1173 $tableOperations[$table] = $migrationInfo['operation'][$key];
1181 // **** Do location related migration:
1182 if (!empty($locBlocks)) {
1183 $locComponent = array(
1187 'openid' => 'OpenID',
1188 'address' => 'Address',
1191 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_primary' => 1));
1192 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, array('is_billing' => 1));
1194 foreach ($locBlocks as $name => $block) {
1195 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1198 $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
1199 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1200 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1202 foreach ($block as $blkCount => $values) {
1203 $locTypeId = CRM_Utils_Array
::value('locTypeId', $values, 1);
1204 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1205 $otherBlockId = CRM_Utils_Array
::value($blkCount,
1206 $migrationInfo['other_details']['loc_block_ids'][$name]
1209 // keep 1-1 mapping for address - loc type.
1211 if (array_key_exists($name, $locComponent)) {
1212 $idKey = $locTypeId;
1215 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1216 $mainBlockId = CRM_Utils_Array
::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1219 if (!$otherBlockId) {
1223 // for the block which belongs to other-contact, link the contact to main-contact
1224 $otherBlockDAO = new $daoName();
1225 $otherBlockDAO->id
= $otherBlockId;
1226 $otherBlockDAO->contact_id
= $mainId;
1227 $otherBlockDAO->location_type_id
= $locTypeId;
1229 // if main contact already has primary & billing, set the flags to 0.
1230 if ($primaryDAOId) {
1231 $otherBlockDAO->is_primary
= 0;
1233 if ($billingDAOId) {
1234 $otherBlockDAO->is_billing
= 0;
1237 // overwrite - need to delete block which belongs to main-contact.
1238 if ($mainBlockId && ($operation == 2)) {
1239 $deleteDAO = new $daoName();
1240 $deleteDAO->id
= $mainBlockId;
1241 $deleteDAO->find(TRUE);
1243 // if we about to delete a primary / billing block, set the flags for new block
1244 // that we going to assign to main-contact
1245 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1246 $otherBlockDAO->is_primary
= 1;
1248 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1249 $otherBlockDAO->is_billing
= 1;
1252 $deleteDAO->delete();
1256 $otherBlockDAO->update();
1257 $otherBlockDAO->free();
1262 // **** Do tables related migrations
1263 if (!empty($moveTables)) {
1264 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1265 unset($moveTables, $tableOperations);
1268 // **** Do contact related migrations
1269 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId);
1271 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1272 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1273 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1274 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1275 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1276 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1277 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1278 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1280 // fix custom fields so they're edible by createProfileContact()
1281 static $treeCache = array();
1282 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1283 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup
::getTree($migrationInfo['main_details']['contact_type'],
1284 CRM_Core_DAO
::$_nullObject, NULL, -1
1287 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1290 foreach ($cgTree as $key => $group) {
1291 if (!isset($group['fields'])) {
1294 foreach ($group['fields'] as $fid => $field) {
1295 $cFields[$fid]['attributes'] = $field;
1299 if (!isset($submitted)) {
1300 $submitted = array();
1302 foreach ($submitted as $key => $value) {
1303 if (substr($key, 0, 7) == 'custom_') {
1304 $fid = (int) substr($key, 7);
1305 $htmlType = $cFields[$fid]['attributes']['html_type'];
1306 switch ($htmlType) {
1308 $customFiles[] = $fid;
1309 unset($submitted["custom_$fid"]);
1312 case 'Select Country':
1313 case 'Select State/Province':
1314 $submitted[$key] = CRM_Core_BAO_CustomField
::getDisplayValue($value, $fid, $cFields);
1318 case 'AdvMulti-Select':
1319 case 'Multi-Select':
1320 case 'Multi-Select Country':
1321 case 'Multi-Select State/Province':
1322 // Merge values from both contacts for multivalue fields, CRM-4385
1323 // get the existing custom values from db.
1324 $customParams = array('entityID' => $mainId, $key => TRUE);
1325 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1326 if (CRM_Utils_array
::value($key, $customfieldValues)) {
1327 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1328 if (is_array($existingValue) && !empty($existingValue)) {
1329 $mergeValue = $submmtedCustomValue = array();
1331 $submmtedCustomValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1334 //hack to remove null and duplicate values from array.
1335 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1336 if ($v != '' && !in_array($v, $mergeValue)) {
1341 //keep state and country as array format.
1342 //for checkbox and m-select format w/ VALUE_SEPARATOR
1343 if (in_array($htmlType, array(
1344 'CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
1345 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1347 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1350 $submitted[$key] = $mergeValue;
1354 elseif (in_array($htmlType, array(
1355 'Multi-Select Country', 'Multi-Select State/Province'))) {
1356 //we require submitted values should be in array format
1358 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1359 //hack to remove null values from array.
1360 $mergeValue = array();
1361 foreach ($mergeValueArray as $k => $v) {
1366 $submitted[$key] = $mergeValue;
1377 // **** Do file custom fields related migrations
1378 // FIXME: move this someplace else (one of the BAOs) after discussing
1379 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1380 // like, delete a file...
1382 if (!isset($customFiles)) {
1383 $customFiles = array();
1385 foreach ($customFiles as $customId) {
1386 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
1388 // get the contact_id -> file_id mapping
1390 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1391 $dao = CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1392 while ($dao->fetch()) {
1393 $fileIds[$dao->entity_id
] = $dao->file_id
;
1397 // delete the main contact's file
1398 if (!empty($fileIds[$mainId])) {
1399 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1402 // move the other contact's file to main contact
1403 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1404 if ( CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}") ) {
1405 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1408 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1410 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1412 if ( CRM_Core_DAO
::singleValueQuery("
1414 FROM civicrm_entity_file
1415 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}") ) {
1417 UPDATE civicrm_entity_file
1418 SET entity_id = {$mainId}
1419 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1423 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1424 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1426 CRM_Core_DAO
::executeQuery($sql, CRM_Core_DAO
::$_nullArray);
1429 // move view only custom fields CRM-5362
1430 $viewOnlyCustomFields = array();
1431 foreach ($submitted as $key => $value) {
1432 $fid = (int) substr($key, 7);
1433 if (array_key_exists($fid, $cFields) &&
1434 CRM_Utils_Array
::value('is_view', $cFields[$fid]['attributes'])
1436 $viewOnlyCustomFields[$key] = $value;
1440 // special case to set values for view only, CRM-5362
1441 if (!empty($viewOnlyCustomFields)) {
1442 $viewOnlyCustomFields['entityID'] = $mainId;
1443 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1446 // **** Delete other contact & update prev-next caching
1447 $otherParams = array(
1448 'contact_id' => $otherId,
1452 if (CRM_Core_Permission
::check('merge duplicate contacts') &&
1453 CRM_Core_Permission
::check('delete contacts')
1455 // if ext id is submitted then set it null for contact to be deleted
1456 if (CRM_Utils_Array
::value('external_identifier', $submitted)) {
1457 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1458 CRM_Core_DAO
::executeQuery($query);
1461 civicrm_api('contact', 'delete', $otherParams);
1462 CRM_Core_BAO_PrevNextCache
::deleteItem($otherId);
1467 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1472 // **** Update contact related info for the main contact
1473 if (!empty($submitted)) {
1474 $submitted['contact_id'] = $mainId;
1476 //update current employer field
1477 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1478 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1479 $submitted['current_employer'] = $submitted['current_employer_id'];
1481 $submitted['current_employer'] = '';
1483 unset($submitted['current_employer_id']);
1486 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);
1494 * @return array of field names which will be compared, so everything except ID.
1496 static function getContactFields() {
1497 $contactFields = CRM_Contact_DAO_Contact
::fields();
1498 $invalidFields = array('api_key', 'contact_is_deleted', 'created_date', 'display_name', 'hash', 'id', 'modified_date',
1499 'primary_contact_id', 'sort_name', 'user_unique_id');
1500 foreach ($contactFields as $field => $value) {
1501 if (in_array($field, $invalidFields)) {
1502 unset($contactFields[$field]);
1505 return array_keys($contactFields);
1509 * Added for CRM-12695
1510 * Based on the contactId provided
1511 * add/update membership(s) to related contacts
1515 static function addMembershipToRealtedContacts($contactID) {
1516 $dao = new CRM_Member_DAO_Membership();
1517 $dao->contact_id
= $contactID;
1521 //checks membership of contact itself
1522 while ($dao->fetch()) {
1523 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1524 if ($relationshipTypeId) {
1525 $membershipParams = array(
1527 'contact_id' => $dao->contact_id
,
1528 'membership_type_id' => $dao->membership_type_id
,
1529 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1530 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1531 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1532 'source' => $dao->source
,
1533 'status_id' => $dao->status_id
1535 // create/update membership(s) for related contact(s)
1536 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1537 } // end of if relationshipTypeId