Merge pull request #4686 from lcdservices/CRM-15698-b
[civicrm-core.git] / CRM / Dedupe / Merger.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Dedupe_Merger {
6a488035
TO
36
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
e0ef6999
EM
40 /**
41 * @return array
42 */
6a488035
TO
43 static function relTables() {
44 static $relTables;
45
46 $config = CRM_Core_Config::singleton();
47 if ($config->userSystem->is_drupal) {
48 $userRecordUrl = CRM_Utils_System::url('user/%ufid');
49 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
50 }
51 elseif ($config->userFramework == 'Joomla') {
52 $userRecordUrl = $config->userFrameworkVersion > 1.5 ? $config->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . '%ufid' : $config->userFrameworkBaseURL . "index2.php?option=com_users&view=user&task=edit&id[]=" . '%ufid';
53 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
54 }
55
56 if (!$relTables) {
57 $relTables = array(
58 'rel_table_contributions' => array(
59 'title' => ts('Contributions'),
60 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
61 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
62 ),
63 'rel_table_contribution_page' => array(
64 'title' => ts('Contribution Pages'),
65 'tables' => array('civicrm_contribution_page'),
66 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
67 ),
68 'rel_table_memberships' => array(
69 'title' => ts('Memberships'),
70 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
71 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
72 ),
73 'rel_table_participants' => array(
74 'title' => ts('Participants'),
75 'tables' => array('civicrm_participant'),
76 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
77 ),
78 'rel_table_events' => array(
79 'title' => ts('Events'),
80 'tables' => array('civicrm_event'),
81 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
82 ),
83 'rel_table_activities' => array(
84 'title' => ts('Activities'),
91da6cd5 85 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
6a488035
TO
86 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
87 ),
88 'rel_table_relationships' => array(
89 'title' => ts('Relationships'),
90 'tables' => array('civicrm_relationship'),
91 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
92 ),
93 'rel_table_custom_groups' => array(
94 'title' => ts('Custom Groups'),
95 'tables' => array('civicrm_custom_group'),
96 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
97 ),
98 'rel_table_uf_groups' => array(
99 'title' => ts('Profiles'),
100 'tables' => array('civicrm_uf_group'),
101 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
102 ),
103 'rel_table_groups' => array(
104 'title' => ts('Groups'),
105 'tables' => array('civicrm_group_contact'),
106 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
107 ),
108 'rel_table_notes' => array(
109 'title' => ts('Notes'),
110 'tables' => array('civicrm_note'),
111 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
112 ),
113 'rel_table_tags' => array(
114 'title' => ts('Tags'),
115 'tables' => array('civicrm_entity_tag'),
116 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
117 ),
118 'rel_table_mailings' => array(
119 'title' => ts('Mailings'),
120 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
121 'url' => CRM_Utils_System::url('civicrm/mailing', 'reset=1&force=1&cid=$cid'),
122 ),
123 'rel_table_cases' => array(
124 'title' => ts('Cases'),
125 'tables' => array('civicrm_case_contact'),
126 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
127 ),
128 'rel_table_grants' => array(
129 'title' => ts('Grants'),
130 'tables' => array('civicrm_grant'),
131 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
132 ),
133 'rel_table_pcp' => array(
134 'title' => ts('PCPs'),
135 'tables' => array('civicrm_pcp'),
136 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
137 ),
138 'rel_table_pledges' => array(
139 'title' => ts('Pledges'),
140 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
141 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
142 ),
143 'rel_table_users' => array(
144 'title' => $title,
145 'tables' => array('civicrm_uf_match'),
146 'url' => $userRecordUrl,
147 ),
148 );
149
76c53278
CW
150 $relTables += self::getMultiValueCustomSets('relTables');
151
6a488035
TO
152 // Allow hook_civicrm_merge() to adjust $relTables
153 CRM_Utils_Hook::merge('relTables', $relTables);
154 }
155 return $relTables;
156 }
157
158 /**
159 * Returns the related tables groups for which a contact has any info entered
160 */
161 static function getActiveRelTables($cid) {
162 $cid = (int) $cid;
163 $groups = array();
164
165 $relTables = self::relTables();
166 $cidRefs = self::cidRefs();
167 $eidRefs = self::eidRefs();
168 foreach ($relTables as $group => $params) {
169 $sqls = array();
170 foreach ($params['tables'] as $table) {
171 if (isset($cidRefs[$table])) {
172 foreach ($cidRefs[$table] as $field) {
173 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
174 }
175 }
176 if (isset($eidRefs[$table])) {
177 foreach ($eidRefs[$table] as $entityTable => $entityId) {
178 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
179 }
180 }
181 foreach ($sqls as $sql) {
182 if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
183 $groups[] = $group;
184 }
185 }
186 }
187 }
188 return array_unique($groups);
189 }
190
191 /**
e4f8c98c 192 * Return tables and their fields referencing civicrm_contact.contact_id explicitly
6a488035
TO
193 */
194 static function cidRefs() {
195 static $cidRefs;
196 if (!$cidRefs) {
e4f8c98c 197 $sql = "
198SELECT
199 table_name,
200 column_name
201FROM information_schema.key_column_usage
202WHERE
203 referenced_table_schema = database() AND
204 referenced_table_name = 'civicrm_contact' AND
205 referenced_column_name = 'id';
206 ";
6a488035
TO
207 $dao = CRM_Core_DAO::executeQuery($sql);
208 while ($dao->fetch()) {
209 $cidRefs[$dao->table_name][] = $dao->column_name;
210 }
64b3569d 211
212 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
213 $cidRefs['civicrm_entity_tag'][] = 'entity_id';
6a488035
TO
214 $dao->free();
215
216 // Allow hook_civicrm_merge() to adjust $cidRefs
217 CRM_Utils_Hook::merge('cidRefs', $cidRefs);
218 }
219 return $cidRefs;
220 }
221
222 /**
223 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
224 */
225 static function eidRefs() {
226 static $eidRefs;
227 if (!$eidRefs) {
228 // FIXME: this should be generated dynamically from the schema
229 // tables that reference contacts with entity_{id,table}
230 $eidRefs = array(
231 'civicrm_acl' => array('entity_table' => 'entity_id'),
232 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
233 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
234 'civicrm_log' => array('entity_table' => 'entity_id'),
235 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
236 'civicrm_note' => array('entity_table' => 'entity_id'),
6a488035
TO
237 );
238
239 // Allow hook_civicrm_merge() to adjust $eidRefs
240 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
241 }
242 return $eidRefs;
243 }
244
9da04f20
AS
245 /**
246 * Return tables using locations
247 */
248 static function locTables() {
249 static $locTables;
250 if (!$locTables) {
251 $locTables = array( 'civicrm_email', 'civicrm_address', 'civicrm_phone' );
252
253 // Allow hook_civicrm_merge() to adjust $locTables
254 CRM_Utils_Hook::merge('locTables', $locTables);
255 }
256 return $locTables;
257 }
258
76c53278
CW
259 /**
260 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
261 * @param string $request 'relTables' or 'cidRefs'
262 * @see CRM-13836
263 */
264 static function getMultiValueCustomSets($request) {
265 static $data = NULL;
266 if ($data === NULL) {
267 $data = array(
268 'relTables' => array(),
269 'cidRefs' => array(),
270 );
271 $result = civicrm_api3('custom_group', 'get', array(
272 'is_multiple' => 1,
273 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
274 'return' => array('id', 'title', 'table_name', 'style'),
275 ));
276 foreach($result['values'] as $custom) {
277 $data['cidRefs'][$custom['table_name']] = array('entity_id');
278 $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
279 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
280 'title' => $custom['title'],
281 'tables' => array($custom['table_name']),
282 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
283 );
284 }
285 }
286 return $data[$request];
287 }
288
6a488035
TO
289 /**
290 * Tables which require custom processing should declare functions to call here.
291 * Doing so will override normal processing.
292 */
293 static function cpTables() {
294 static $tables;
295 if (!$tables) {
296 $tables = array(
297 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
298 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
299 // Empty array == do nothing - this table is handled by mergeGroupContact
300 'civicrm_subscription_history' => array(),
301 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
302 );
303 }
304 return $tables;
305 }
306
307 /**
100fef9d 308 * Return payment related table.
6a488035
TO
309 */
310 static function paymentTables() {
311 static $tables;
312 if (!$tables) {
313 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
314 }
315
316 return $tables;
317 }
318
319 /**
100fef9d 320 * Return payment update Query.
6a488035
TO
321 */
322 static function paymentSql($tableName, $mainContactId, $otherContactId) {
323 $sqls = array();
324 if (!$tableName || !$mainContactId || !$otherContactId) {
325 return $sqls;
326 }
327
328 $paymentTables = self::paymentTables();
329 if (!in_array($tableName, $paymentTables)) {
330 return $sqls;
331 }
332
333 switch ($tableName) {
334 case 'civicrm_pledge':
335 $sqls[] = "
336 UPDATE IGNORE civicrm_contribution contribution
337INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
338INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
339 SET contribution.contact_id = $mainContactId
340 WHERE pledge.contact_id = $otherContactId";
341 break;
342
343 case 'civicrm_membership':
344 $sqls[] = "
345 UPDATE IGNORE civicrm_contribution contribution
346INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
347INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
348 SET contribution.contact_id = $mainContactId
349 WHERE membership.contact_id = $otherContactId";
350 break;
351
352 case 'civicrm_participant':
353 $sqls[] = "
354 UPDATE IGNORE civicrm_contribution contribution
355INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
356INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
357 SET contribution.contact_id = $mainContactId
358 WHERE participant.contact_id = $otherContactId";
359 break;
360 }
361
362 return $sqls;
363 }
364
e0ef6999 365 /**
100fef9d
CW
366 * @param int $mainId
367 * @param int $otherId
368 * @param string $tableName
e0ef6999
EM
369 * @param array $tableOperations
370 * @param string $mode
371 *
372 * @return array
373 */
6a488035
TO
374 static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
375 $sqls = array();
376 if (!$tableName || !$mainId || !$otherId) {
377 return $sqls;
378 }
379
380
381 switch ($tableName) {
382 case 'civicrm_membership':
383 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add'])
384 break;
385 if ($mode == 'add') {
386 $sqls[] = "
387DELETE membership1.* FROM civicrm_membership membership1
388 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
389 AND membership1.contact_id = {$mainId}
390 AND membership2.contact_id = {$otherId} ";
391 }
392 if ($mode == 'payment') {
393 $sqls[] = "
394DELETE contribution.* FROM civicrm_contribution contribution
395INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
396INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
397 AND membership1.contact_id = {$mainId}
398INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
399 AND membership2.contact_id = {$otherId}";
400 }
401 break;
402
403 case 'civicrm_uf_match':
404 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
405 // failing to meet intended result. Therefore we introduce this additonal query:
406 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
407 break;
408 }
409
410 return $sqls;
411 }
412
413 /**
414 * Based on the provided two contact_ids and a set of tables, move the
415 * belongings of the other contact to the main one.
416 *
417 * @static
418 */
419 static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
420 $cidRefs = self::cidRefs();
421 $eidRefs = self::eidRefs();
422 $cpTables = self::cpTables();
423 $paymentTables = self::paymentTables();
ada104d5 424 $membershipMerge = FALSE; // CRM-12695
6a488035
TO
425
426 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
427 if ($tables !== FALSE) {
428 // if there are specific tables, sanitize the list
429 $affected = array_unique(array_intersect($affected, $tables));
430 }
431 else {
432 // if there aren't any specific tables, don't affect the ones handled by relTables()
9da04f20 433 // also don't affect tables in locTables() CRM-15658
6a488035 434 $relTables = self::relTables();
9da04f20 435 $handled = self::locTables();
6a488035
TO
436 foreach ($relTables as $params) {
437 $handled = array_merge($handled, $params['tables']);
438 }
439 $affected = array_diff($affected, $handled);
ada104d5
AW
440 /**
441 * CRM-12695
442 * Set $membershipMerge flag only once
443 * while doing contact related migration
444 * to call addMembershipToRealtedContacts()
445 * function only once.
446 * Since the current function (moveContactBelongings) is called twice
447 * with & without parameters $tables & $tableOperations
448 */
449 // retrieve main contact's related table(s)
450 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
451 // check if membership table exists in main contact's related table(s)
452 if (in_array('rel_table_memberships', $activeMainRelTables)) {
453 $membershipMerge = TRUE; // set membership flag - CRM-12695
454 }
6a488035
TO
455 }
456
457 $mainId = (int) $mainId;
458 $otherId = (int) $otherId;
459
460 $sqls = array();
461 foreach ($affected as $table) {
462 // Call custom processing function for objects that require it
463 if (isset($cpTables[$table])) {
464 foreach ($cpTables[$table] as $className => $fnName) {
465 $className::$fnName($mainId, $otherId, $sqls);
466 }
467 // Skip normal processing
468 continue;
469 }
b3fdbf3d 470
6a488035
TO
471 // use UPDATE IGNORE + DELETE query pair to skip on situations when
472 // there's a UNIQUE restriction on ($field, some_other_field) pair
473 if (isset($cidRefs[$table])) {
474 foreach ($cidRefs[$table] as $field) {
475 // carry related contributions CRM-5359
476 if (in_array($table, $paymentTables)) {
6a488035
TO
477 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
478 $sqls = array_merge($sqls, $paymentSqls);
71560cf3
C
479
480 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
481 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
482 $sqls = array_merge($sqls, $payOprSqls);
483 }
6a488035
TO
484 }
485
486 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
487 $sqls = array_merge($sqls, $preOperationSqls);
488
489 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
490 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
491 }
492 }
493 if (isset($eidRefs[$table])) {
494 foreach ($eidRefs[$table] as $entityTable => $entityId) {
495 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
496 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
497 }
498 }
499 }
500
501 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
502 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
503
504 // call the SQL queries in one transaction
505 $transaction = new CRM_Core_Transaction();
506 foreach ($sqls as $sql) {
507 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE);
508 }
ada104d5
AW
509 // CRM-12695
510 if ($membershipMerge) {
511 // call to function adding membership to related contacts
512 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
513 }
6a488035
TO
514 $transaction->commit();
515 }
516
517 /**
518 * Find differences between contacts.
b3fdbf3d 519 *
6a488035
TO
520 * @param array $main contact details
521 * @param array $other contact details
522 *
77b97be7 523 * @return array
6a488035
TO
524 * @static
525 */
526 static function findDifferences($main, $other) {
527 $result = array(
528 'contact' => array(),
529 'custom' => array(),
530 );
16254ae1 531 foreach (self::getContactFields() as $validField) {
6a488035
TO
532 if (CRM_Utils_Array::value($validField, $main) != CRM_Utils_Array::value($validField, $other)) {
533 $result['contact'][] = $validField;
534 }
535 }
536
537 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
538 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
539 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
540 foreach ($keys as $key) {
76c53278
CW
541 // Exclude multi-value fields CRM-13836
542 if (strpos($key, '_')) {
543 continue;
544 }
6a488035
TO
545 $key1 = CRM_Utils_Array::value($key, $mainEvs);
546 $key2 = CRM_Utils_Array::value($key, $otherEvs);
547 if ($key1 != $key2) {
548 $result['custom'][] = $key;
549 }
550 }
551 return $result;
552 }
553
554 /**
100fef9d 555 * Batch merge a set of contacts based on rule-group and group.
6a488035 556 *
77b97be7
EM
557 * @param int $rgid rule group id
558 * @param int $gid group id
559 * @param string $mode helps decide how to behave when there are conflicts.
6a488035
TO
560 * A 'safe' value skips the merge if there are any un-resolved conflicts.
561 * Does a force merge otherwise.
77b97be7 562 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
77b97be7 563 * @param bool $redirectForPerformance
6a488035 564 *
77b97be7 565 * @return array|bool
6a488035
TO
566 * @static
567 * @access public
568 */
569 static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $redirectForPerformance = FALSE) {
570 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
571 $cacheKeyString = "merge {$contactType}";
572 $cacheKeyString .= $rgid ? "_{$rgid}" : '_0';
573 $cacheKeyString .= $gid ? "_{$gid}" : '_0';
574 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
575 pn.entity_id2 = de.contact_id2 )";
576
577 $limit = $redirectForPerformance ? 75 : 1;
578 $where = "de.id IS NULL LIMIT {$limit}";
579
580 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
581 if (empty($dupePairs) && !$redirectForPerformance) {
582 // If we haven't found any dupes, probably cache is empty.
583 // Try filling cache and give another try.
584 CRM_Core_BAO_PrevNextCache::refillCache($rgid, $gid, $cacheKeyString);
585 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
586 }
587
588 $cacheParams = array(
589 'cache_key_string' => $cacheKeyString,
590 'join' => $join,
591 'where' => $where,
592 );
593 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
594 }
595
596 /**
100fef9d 597 * Merge given set of contacts. Performs core operation.
6a488035 598 *
77b97be7
EM
599 * @param array $dupePairs set of pair of contacts for whom merge is to be done.
600 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
6a488035 601 * Generally used with batch-merge.
77b97be7 602 * @param string $mode helps decide how to behave when there are conflicts.
6a488035
TO
603 * A 'safe' value skips the merge if there are any un-resolved conflicts.
604 * Does a force merge otherwise (aggressive mode).
77b97be7 605 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
6a488035
TO
606 *
607 *
77b97be7
EM
608 * @param bool $redirectForPerformance
609 *
610 * @return array|bool
6a488035
TO
611 * @static
612 * @access public
613 */
c490a46a 614 static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
6a488035
TO
615 $autoFlip = TRUE, $redirectForPerformance = FALSE
616 ) {
617 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
618 $resultStats = array('merged' => array(), 'skipped' => array());
619
620 // we don't want dupe caching to get reset after every-merge, and therefore set the
621 // doNotResetCache flag
622 $config = CRM_Core_Config::singleton();
623 $config->doNotResetCache = 1;
624
625 while (!empty($dupePairs)) {
626 foreach ($dupePairs as $dupes) {
1cf05c3e 627 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
6a488035
TO
628 $mainId = $dupes['dstID'];
629 $otherId = $dupes['srcID'];
602789b5
DS
630 $isAutoFlip = CRM_Utils_Array::value('auto_flip', $dupes, $autoFlip);
631 // if we can, make sure that $mainId is the one with lower id number
632 if ($isAutoFlip && ($mainId > $otherId)) {
6a488035
TO
633 $mainId = $dupes['srcID'];
634 $otherId = $dupes['dstID'];
635 }
636 if (!$mainId || !$otherId) {
637 // return error
638 return FALSE;
639 }
640
641 // Generate var $migrationInfo. The variable structure is exactly same as
642 // $formValues submitted during a UI merge for a pair of contacts.
643 $rowsElementsAndInfo = &CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId);
644
645 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
646
647 // add additional details that we might need to resolve conflicts
648 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
649 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
650 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
651 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
652
653 // go ahead with merge if there is no conflict
654 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode)) {
655 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo);
656 $resultStats['merged'][] = array('main_d' => $mainId, 'other_id' => $otherId);
657 }
658 else {
659 $resultStats['skipped'][] = array('main_d' => $mainId, 'other_id' => $otherId);
660 }
661
662 // delete entry from PrevNextCache table so we don't consider the pair next time
663 // pair may have been flipped, so make sure we delete using both orders
664 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString);
665 CRM_Core_BAO_PrevNextCache::deletePair($otherId, $mainId, $cacheKeyString);
666
667 CRM_Core_DAO::freeResult();
668 unset($rowsElementsAndInfo, $migrationInfo);
669 }
670
671 if ($cacheKeyString && !$redirectForPerformance) {
672 // retrieve next pair of dupes
673 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
674 $cacheParams['join'],
675 $cacheParams['where']
676 );
677 }
678 else {
679 // do not proceed. Terminate the loop
680 unset($dupePairs);
681 }
682 }
683 return $resultStats;
684 }
685
686 /**
687 * A function which uses various rules / algorithms for choosing which contact to bias to
688 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
689 *
77b97be7
EM
690 * @param int $mainId main contact with whom merge has to happen
691 * @param int $otherId duplicate contact which would be deleted after merge operation
692 * @param array $migrationInfo array of information about which elements to merge.
693 * @param string $mode helps decide how to behave when there are conflicts.
6a488035
TO
694 * A 'safe' value skips the merge if there are any un-resolved conflicts.
695 * Does a force merge otherwise (aggressive mode).
696 *
77b97be7 697 * @return bool
6a488035
TO
698 * @static
699 * @access public
700 */
701 static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe') {
702 $conflicts = array();
703 $migrationData = array(
704 'old_migration_info' => $migrationInfo,
705 'mode' => $mode,
706 );
b2b0530a 707 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
708
709 foreach ($migrationInfo as $key => $val) {
710 if ($val === "null") {
711 // Rule: no overwriting with empty values in any mode
712 unset($migrationInfo[$key]);
713 continue;
714 }
16254ae1 715 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
6a488035
TO
716 substr($key, 0, 12) == 'move_custom_'
717 ) and $val != NULL) {
718 // Rule: if both main-contact has other-contact, let $mode decide if to merge a
719 // particular field or not
720 if (!empty($migrationInfo['rows'][$key]['main'])) {
721 // if main also has a value its a conflict
722 if ($mode == 'safe') {
723 // note it down & lets wait for response from the hook.
724 // For no response skip this merge
725 $conflicts[$key] = NULL;
726 }
727 elseif ($mode == 'aggressive') {
728 // let the main-field be overwritten
729 continue;
730 }
731 }
732 }
733 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
734 $locField = explode('_', $key);
735 $fieldName = $locField[2];
736 $fieldCount = $locField[3];
737
738 // Rule: resolve address conflict if any -
739 if ($fieldName == 'address') {
740 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
a7488080 741 if (!empty($migrationInfo['main_loc_address']) &&
6a488035
TO
742 array_key_exists("main_{$mainNewLocTypeId}", $migrationInfo['main_loc_address'])) {
743 // main loc already has some address for the loc-type. Its a overwrite situation.
744
745 // look for next available loc-type
746 $newTypeId = NULL;
747 foreach ($allLocationTypes as $typeId => $typeLabel) {
748 if (!array_key_exists("main_{$typeId}", $migrationInfo['main_loc_address'])) {
749 $newTypeId = $typeId;
750 }
751 }
752 if ($newTypeId) {
753 // try insert address at new available loc-type
754 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
755 }
756 elseif ($mode == 'safe') {
757 // note it down & lets wait for response from the hook.
758 // For no response skip this merge
759 $conflicts[$key] = NULL;
760 }
761 elseif ($mode == 'aggressive') {
762 // let the loc-type-id be same as that of other-contact & go ahead
763 // with merge assuming aggressive mode
764 continue;
765 }
766 }
767 }
768 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
769 // for loc blocks other than address like email, phone .. if values are same no point in merging
770 // and adding redundant value
771 unset($migrationInfo[$key]);
772 }
773 }
774 }
775
776 // A hook to implement other algorithms for choosing which contact to bias to when
777 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
778 // merge happens with new values filled in here. For a particular field / row not to be merged
779 // field should be unset from fields_in_conflict.
780 $migrationData['fields_in_conflict'] = $conflicts;
781 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
782 $conflicts = $migrationData['fields_in_conflict'];
783
784 if (!empty($conflicts)) {
785 foreach ($conflicts as $key => $val) {
786 if ($val === NULL and $mode == 'safe') {
787 // un-resolved conflicts still present. Lets skip this merge.
788 return TRUE;
789 }
790 else {
791 // copy over the resolved values
792 $migrationInfo[$key] = $val;
793 }
794 }
795 }
796 return FALSE;
797 }
798
799 /**
800 * A function to build an array of information required by merge function and the merge UI.
801 *
77b97be7
EM
802 * @param int $mainId main contact with whom merge has to happen
803 * @param int $otherId duplicate contact which would be deleted after merge operation
6a488035 804 *
77b97be7 805 * @return array|bool|int
6a488035
TO
806 * @static
807 * @access public
808 */
809 static function getRowsElementsAndInfo($mainId, $otherId) {
810 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
811
812 // Fetch contacts
813 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
16254ae1 814 $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields()));
6a488035
TO
815 $result = civicrm_api('contact', 'get', $params);
816
817 if (empty($result['values'][$cid]['contact_type'])) {
818 return FALSE;
819 }
820 $$moniker = $result['values'][$cid];
821 }
822
823 static $fields = array();
824 if (empty($fields)) {
825 $fields = CRM_Contact_DAO_Contact::fields();
826 CRM_Core_DAO::freeResult();
827 }
828
829 // FIXME: there must be a better way
830 foreach (array('main', 'other') as $moniker) {
831 $contact = &$$moniker;
832 $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
833 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
834 $specialValues[$moniker] = array(
835 'preferred_communication_method' => $value,
0e357872 836 'communication_style_id' => $value,
6a488035
TO
837 );
838
a7488080 839 if (!empty($contact['preferred_communication_method'])){
6a488035 840 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
b3fdbf3d
DL
841 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
842 implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) :
6a488035
TO
843 $specialValues[$moniker]['preferred_communication_method'];
844 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
845 }
846 $names = array(
847 'preferred_communication_method' =>
848 array(
849 'newName' => 'preferred_communication_method_display',
850 'groupName' => 'preferred_communication_method',
851 ),
852 );
853 CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
a14df814 854
0e357872
C
855 if (!empty($contact['communication_style'])) {
856 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
857 }
6a488035
TO
858 }
859
860 static $optionValueFields = array();
861 if (empty($optionValueFields)) {
862 $optionValueFields = CRM_Core_OptionValue::getFields();
863 }
864 foreach ($optionValueFields as $field => $params) {
865 $fields[$field]['title'] = $params['title'];
866 }
867
868 $diffs = self::findDifferences($main, $other);
869
870 $rows = $elements = $relTableElements = $migrationInfo = array();
871
4f88c9cf
C
872 $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
873
6a488035 874 foreach ($diffs['contact'] as $field) {
4d5f18cc 875 if ($field == 'contact_sub_type') {
876 // CRM-15681 don't display sub-types in UI
877 continue;
878 }
6a488035
TO
879 foreach (array('main', 'other') as $moniker) {
880 $contact = &$$moniker;
881 $value = CRM_Utils_Array::value($field, $contact);
882 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
883 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
884 }
885 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
a7488080 886 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
6a488035
TO
887 if ($value) {
888 $value = str_replace('-', '', $value);
889 $label = CRM_Utils_Date::customFormat($label);
890 }
891 else {
892 $value = "null";
893 }
894 }
a7488080 895 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
6a488035
TO
896 if ($label === '0') {
897 $label = ts('[ ]');
898 }
899 if ($label === '1') {
900 $label = ts('[x]');
901 }
00f3da2e
BS
902 }
903 elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
904 $label = CRM_Utils_Array::value('individual_prefix', $contact);
6a488035
TO
905 $value = CRM_Utils_Array::value('prefix_id', $contact);
906 $field = 'prefix_id';
00f3da2e
BS
907 }
908 elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
909 $label = CRM_Utils_Array::value('individual_suffix', $contact);
6a488035
TO
910 $value = CRM_Utils_Array::value('suffix_id', $contact);
911 $field = 'suffix_id';
912 }
4f88c9cf
C
913 elseif ($field == 'gender_id' && !empty($value)) {
914 $label = $genders[$value];
915 }
916 elseif ($field == 'current_employer_id' && !empty($value)) {
917 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
918 }
6a488035
TO
919 $rows["move_$field"][$moniker] = $label;
920 if ($moniker == 'other') {
7154d2a4
BS
921 //CRM-14334
922 if ($value === NULL || $value == '') {
6a488035
TO
923 $value = 'null';
924 }
925 if ($value === 0 or $value === '0') {
926 $value = $qfZeroBug;
927 }
8cc574cf 928 if (is_array($value) && empty($value[1])) {
6a488035
TO
929 $value[1] = NULL;
930 }
931 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
932 $migrationInfo["move_$field"] = $value;
933 }
934 }
935 $rows["move_$field"]['title'] = $fields[$field]['title'];
936 }
937
938 // handle location blocks.
939 $locationBlocks = array('email', 'phone', 'address');
940 $locations = array();
941
942 foreach ($locationBlocks as $block) {
943 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
944 $cnt = 1;
945 $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
946 $count = $values['count'];
947 if ($count) {
948 if ($count > $cnt) {
949 foreach ($values['values'] as $value) {
950 if ($block == 'address') {
951 CRM_Core_BAO_Address::fixAddress($value);
952 $display = CRM_Utils_Address::format($value);
953 $locations[$moniker][$block][$cnt] = $value;
954 $locations[$moniker][$block][$cnt]['display'] = $display;
955 }
956 else {
957 $locations[$moniker][$block][$cnt] = $value;
958 }
959
960 $cnt++;
961 }
962 }
963 else {
964 $id = $values['id'];
965 if ($block == 'address') {
966 CRM_Core_BAO_Address::fixAddress($values['values'][$id]);
967 $display = CRM_Utils_Address::format($values['values'][$id]);
968 $locations[$moniker][$block][$cnt] = $values['values'][$id];
969 $locations[$moniker][$block][$cnt]['display'] = $display;
970 }
971 else {
972 $locations[$moniker][$block][$cnt] = $values['values'][$id];
973 }
974 }
975 }
976 }
977 }
978
b2b0530a 979 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
980
981 $mainLocBlock = $locBlockIds = array();
982 $locBlockIds['main'] = $locBlockIds['other'] = array();
983 foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
984 $name = strtolower($block);
985 foreach (array('main', 'other') as $moniker) {
986 $locIndex = CRM_Utils_Array::value($moniker, $locations);
987 $blockValue = CRM_Utils_Array::value($name, $locIndex, array());
988 if (empty($blockValue)) {
989 $locValue[$moniker][$name] = 0;
990 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
991 }
992 else {
993 $locValue[$moniker][$name] = TRUE;
994 foreach ($blockValue as $count => $blkValues) {
995 $fldName = $name;
996 $locTypeId = $blkValues['location_type_id'];
997 if ($name == 'im') {
998 $fldName = 'name';
999 }
1000 if ($name == 'address') {
1001 $fldName = 'display';
1002 }
1003 $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName,
1004 $blkValues
1005 );
1006 $locTypes[$moniker][$name][$count] = $locTypeId;
1007 if ($moniker == 'main' && in_array($name, $locationBlocks)) {
1008 $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array::value($fldName,
1009 $blkValues
1010 );
1011 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
1012 }
1013 else {
1014 $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
1015 }
1016 }
1017 }
1018 }
1019
1020 if ($locValue['other'][$name] != 0) {
1021 foreach ($locLabel['other'][$name] as $count => $value) {
1022 $locTypeId = $locTypes['other'][$name][$count];
1023 $rows["move_location_{$name}_$count"]['other'] = $value;
1024 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array::value($count,
1025 $locLabel['main'][$name]
1026 );
1027 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
1028 array(
1029 1 => $block,
1030 2 => $count,
1031 3 => $allLocationTypes[$locTypeId]
1032 )
1033 );
1034
1035 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
1036 $migrationInfo["move_location_{$name}_{$count}"] = 1;
1037
1038 // make sure default location type is always on top
1039 $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId);
1040 $locTypeValues = $allLocationTypes;
1041 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
1042 unset($locTypeValues[$mainLocTypeId]);
1043
1044 // keep 1-1 mapping for address - location type.
1045 $js = NULL;
1046 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
1047 $js = array('onChange' => "mergeBlock('$name', this, $count );");
1048 }
1049 $elements[] = array(
1050 'select', "location[{$name}][$count][locTypeId]", NULL,
1051 $defaultLocType + $locTypeValues, $js,
1052 );
1053 // keep location-type-id same as that of other-contact
1054 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
1055
1056 if ($name != 'address') {
1057 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
1058 // always use add operation
1059 $migrationInfo['location'][$name][$count]['operation'] = 1;
1060 }
1061 }
1062 }
1063 }
1064
1065 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1066 $config = CRM_Core_Config::singleton();
1067 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1068 $mainUser = NULL;
1069 if ($mainUfId) {
1070 // d6 compatible
1071 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1072 $mainUser = user_load($mainUfId);
1073 }
1074 elseif ($config->userFramework == 'Joomla') {
1075 $mainUser = JFactory::getUser($mainUfId);
1076 }
1077 }
1078 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1079 $otherUser = NULL;
1080 if ($otherUfId) {
1081 // d6 compatible
1082 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1083 $otherUser = user_load($otherUfId);
1084 }
1085 elseif ($config->userFramework == 'Joomla') {
1086 $otherUser = JFactory::getUser($otherUfId);
1087 }
1088 }
1089
1090 $relTables = CRM_Dedupe_Merger::relTables();
1091 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1092 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1093 foreach ($relTables as $name => $null) {
1094 if (!in_array($name, $activeRelTables) &&
1095 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1096 ) {
1097 unset($relTables[$name]);
1098 continue;
1099 }
1100
1101 $relTableElements[] = array('checkbox', "move_$name");
1102 $migrationInfo["move_$name"] = 1;
1103
1104 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1105 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1106 if ($name == 'rel_table_users') {
1107 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1108 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1109 $find = array('$ufid', '$ufname');
1110 if ($mainUser) {
1111 $replace = array($mainUfId, $mainUser->name);
1112 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1113 }
1114 if ($otherUser) {
1115 $replace = array($otherUfId, $otherUser->name);
1116 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1117 }
1118 }
1119 if ($name == 'rel_table_memberships') {
1120 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1121 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1122 }
1123 }
1124 foreach ($relTables as $name => $null) {
1125 $relTables["move_$name"] = $relTables[$name];
1126 unset($relTables[$name]);
1127 }
1128
1129 // handle custom fields
1130 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1,
1131 CRM_Utils_Array::value('contact_sub_type', $main)
1132 );
1133 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1,
1134 CRM_Utils_Array::value('contact_sub_type', $other)
1135 );
1136 CRM_Core_DAO::freeResult();
1137
1138 foreach ($otherTree as $gid => $group) {
1139 $foundField = FALSE;
1140 if (!isset($group['fields'])) {
1141 continue;
1142 }
1143
1144 foreach ($group['fields'] as $fid => $field) {
1145 if (in_array($fid, $diffs['custom'])) {
1146 if (!$foundField) {
1147 $rows["custom_group_$gid"]['title'] = $group['title'];
1148 $foundField = TRUE;
1149 }
a7488080 1150 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
6a488035
TO
1151 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1152 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1153 $field, TRUE
1154 );
1155 }
1156 }
1157 $value = "null";
a7488080 1158 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
6a488035
TO
1159 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1160 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1161 $field, TRUE
1162 );
1163 if ($values['data'] === 0 || $values['data'] === '0') {
1164 $values['data'] = $qfZeroBug;
1165 }
1166 $value = ($values['data']) ? $values['data'] : $value;
1167 }
1168 }
1169 $rows["move_custom_$fid"]['title'] = $field['label'];
1170
1171 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1172 $migrationInfo["move_custom_$fid"] = $value;
1173 }
1174 }
1175 }
1176 $result = array(
1177 'rows' => $rows,
1178 'elements' => $elements,
1179 'rel_table_elements' => $relTableElements,
1180 'main_loc_block' => $mainLocBlock,
1181 'rel_tables' => $relTables,
1182 'main_details' => $main,
1183 'other_details' => $other,
1184 'migration_info' => $migrationInfo,
1185 );
1186
1187 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1188 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1189
1190 return $result;
1191 }
1192
1193 /**
1194 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1195 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1196 * A superset of moveContactBelongings() function.
1197 *
77b97be7
EM
1198 * @param int $mainId main contact with whom merge has to happen
1199 * @param int $otherId duplicate contact which would be deleted after merge operation
1200 *
1201 * @param $migrationInfo
6a488035 1202 *
77b97be7 1203 * @return bool
6a488035
TO
1204 * @static
1205 * @access public
1206 */
1207 static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1208 if (empty($migrationInfo)) {
1209 return FALSE;
1210 }
1211
1212 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1213 $relTables = CRM_Dedupe_Merger::relTables();
1214 $moveTables = $locBlocks = $tableOperations = array();
1215 foreach ($migrationInfo as $key => $value) {
1216 if ($value == $qfZeroBug) {
1217 $value = '0';
1218 }
7154d2a4
BS
1219 if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) ||
1220 substr($key, 0, 12) == 'move_custom_') &&
1221 $value != NULL
1222 ) {
6a488035
TO
1223 $submitted[substr($key, 5)] = $value;
1224 }
1225 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1226 $locField = explode('_', $key);
1227 $fieldName = $locField[2];
1228 $fieldCount = $locField[3];
1229 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1230 // default operation is overwrite.
1231 if (!$operation) {
1232 $operation = 2;
1233 }
1234
1235 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1236 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1237 }
1238 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1239 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1240 if (array_key_exists('operation', $migrationInfo)) {
1241 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1242 if (array_key_exists($key, $migrationInfo['operation'])) {
1243 $tableOperations[$table] = $migrationInfo['operation'][$key];
1244 }
1245 }
1246 }
1247 }
1248 }
1249
1250
1251 // **** Do location related migration:
1252 if (!empty($locBlocks)) {
1253 $locComponent = array(
1254 'email' => 'Email',
1255 'phone' => 'Phone',
1256 'im' => 'IM',
1257 'openid' => 'OpenID',
1258 'address' => 'Address',
1259 );
1260
1261 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
1262 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
1263
1264 foreach ($locBlocks as $name => $block) {
1265 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1266 continue;
1267 }
1268 $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
1269 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1270 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1271
1272 foreach ($block as $blkCount => $values) {
1273 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
1274 $operation = CRM_Utils_Array::value('operation', $values, 2);
1275 $otherBlockId = CRM_Utils_Array::value($blkCount,
1276 $migrationInfo['other_details']['loc_block_ids'][$name]
1277 );
1278
1279 // keep 1-1 mapping for address - loc type.
1280 $idKey = $blkCount;
1281 if (array_key_exists($name, $locComponent)) {
1282 $idKey = $locTypeId;
1283 }
1284
1285 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1286 $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1287 }
1288
1289 if (!$otherBlockId) {
1290 continue;
1291 }
1292
1293 // for the block which belongs to other-contact, link the contact to main-contact
1294 $otherBlockDAO = new $daoName();
1295 $otherBlockDAO->id = $otherBlockId;
1296 $otherBlockDAO->contact_id = $mainId;
1297 $otherBlockDAO->location_type_id = $locTypeId;
1298
1299 // if main contact already has primary & billing, set the flags to 0.
1300 if ($primaryDAOId) {
1301 $otherBlockDAO->is_primary = 0;
1302 }
1303 if ($billingDAOId) {
1304 $otherBlockDAO->is_billing = 0;
1305 }
1306
1307 // overwrite - need to delete block which belongs to main-contact.
1308 if ($mainBlockId && ($operation == 2)) {
1309 $deleteDAO = new $daoName();
1310 $deleteDAO->id = $mainBlockId;
1311 $deleteDAO->find(TRUE);
1312
1313 // if we about to delete a primary / billing block, set the flags for new block
1314 // that we going to assign to main-contact
1315 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1316 $otherBlockDAO->is_primary = 1;
1317 }
1318 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1319 $otherBlockDAO->is_billing = 1;
1320 }
1321
1322 $deleteDAO->delete();
1323 $deleteDAO->free();
1324 }
1325
1326 $otherBlockDAO->update();
1327 $otherBlockDAO->free();
1328 }
1329 }
1330 }
1331
1332 // **** Do tables related migrations
1333 if (!empty($moveTables)) {
1334 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1335 unset($moveTables, $tableOperations);
1336 }
1337
1338 // **** Do contact related migrations
1339 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
1340
1341 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1342 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1343 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1344 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
aa62b355 1345 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
6a488035
TO
1346 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1347 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1348 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1349 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1350
1351 // fix custom fields so they're edible by createProfileContact()
1352 static $treeCache = array();
1353 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1354 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'],
1355 CRM_Core_DAO::$_nullObject, NULL, -1
1356 );
1357 }
1358 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1359
1360 $cFields = array();
1361 foreach ($cgTree as $key => $group) {
1362 if (!isset($group['fields'])) {
1363 continue;
1364 }
1365 foreach ($group['fields'] as $fid => $field) {
1366 $cFields[$fid]['attributes'] = $field;
1367 }
1368 }
1369
1370 if (!isset($submitted)) {
1371 $submitted = array();
1372 }
1373 foreach ($submitted as $key => $value) {
1374 if (substr($key, 0, 7) == 'custom_') {
1375 $fid = (int) substr($key, 7);
0e357872
C
1376 if (empty($cFields[$fid])) {
1377 continue;
1378 }
6a488035
TO
1379 $htmlType = $cFields[$fid]['attributes']['html_type'];
1380 switch ($htmlType) {
1381 case 'File':
1382 $customFiles[] = $fid;
1383 unset($submitted["custom_$fid"]);
1384 break;
1385
1386 case 'Select Country':
1387 case 'Select State/Province':
1388 $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
1389 break;
1390
1391 case 'CheckBox':
1392 case 'AdvMulti-Select':
1393 case 'Multi-Select':
1394 case 'Multi-Select Country':
1395 case 'Multi-Select State/Province':
1396 // Merge values from both contacts for multivalue fields, CRM-4385
1397 // get the existing custom values from db.
1398 $customParams = array('entityID' => $mainId, $key => TRUE);
1399 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
a7488080 1400 if (!empty($customfieldValues[$key])) {
6a488035
TO
1401 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1402 if (is_array($existingValue) && !empty($existingValue)) {
1403 $mergeValue = $submmtedCustomValue = array();
1404 if ($value) {
1405 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1406 }
1407
1408 //hack to remove null and duplicate values from array.
1409 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1410 if ($v != '' && !in_array($v, $mergeValue)) {
1411 $mergeValue[] = $v;
1412 }
1413 }
1414
1415 //keep state and country as array format.
1416 //for checkbox and m-select format w/ VALUE_SEPARATOR
1417 if (in_array($htmlType, array(
1418 'CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
1419 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1420 $mergeValue
1421 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1422 }
1423 else {
1424 $submitted[$key] = $mergeValue;
1425 }
1426 }
1427 }
1428 elseif (in_array($htmlType, array(
1429 'Multi-Select Country', 'Multi-Select State/Province'))) {
1430 //we require submitted values should be in array format
1431 if ($value) {
1432 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1433 //hack to remove null values from array.
1434 $mergeValue = array();
1435 foreach ($mergeValueArray as $k => $v) {
1436 if ($v != '') {
1437 $mergeValue[] = $v;
1438 }
1439 }
1440 $submitted[$key] = $mergeValue;
1441 }
1442 }
1443 break;
1444
1445 default:
1446 break;
1447 }
1448 }
1449 }
1450
1451 // **** Do file custom fields related migrations
1452 // FIXME: move this someplace else (one of the BAOs) after discussing
b3fdbf3d 1453 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
6a488035
TO
1454 // like, delete a file...
1455
1456 if (!isset($customFiles)) {
1457 $customFiles = array();
1458 }
1459 foreach ($customFiles as $customId) {
1460 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1461
1462 // get the contact_id -> file_id mapping
1463 $fileIds = array();
1464 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1465 $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1466 while ($dao->fetch()) {
1467 $fileIds[$dao->entity_id] = $dao->file_id;
1468 }
1469 $dao->free();
1470
1471 // delete the main contact's file
1472 if (!empty($fileIds[$mainId])) {
b3fdbf3d 1473 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
6a488035
TO
1474 }
1475
1476 // move the other contact's file to main contact
1477 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1478 if ( CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}") ) {
1479 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1480 }
1481 else {
1482 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1483 }
1484 CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1485
1486 if ( CRM_Core_DAO::singleValueQuery("
1487 SELECT id
1488 FROM civicrm_entity_file
1489 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}") ) {
1490 $sql = "
1491 UPDATE civicrm_entity_file
1492 SET entity_id = {$mainId}
1493 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1494 }
1495 else {
1496 $sql = "
1497 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1498 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1499 }
1500 CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1501 }
1502
1503 // move view only custom fields CRM-5362
1504 $viewOnlyCustomFields = array();
1505 foreach ($submitted as $key => $value) {
1506 $fid = (int) substr($key, 7);
8cc574cf 1507 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
6a488035
TO
1508 $viewOnlyCustomFields[$key] = $value;
1509 }
1510 }
1511
1512 // special case to set values for view only, CRM-5362
1513 if (!empty($viewOnlyCustomFields)) {
1514 $viewOnlyCustomFields['entityID'] = $mainId;
1515 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1516 }
1517
1518 // **** Delete other contact & update prev-next caching
1519 $otherParams = array(
1520 'contact_id' => $otherId,
1521 'id' => $otherId,
1522 'version' => 3,
1523 );
1524 if (CRM_Core_Permission::check('merge duplicate contacts') &&
1525 CRM_Core_Permission::check('delete contacts')
1526 ) {
1527 // if ext id is submitted then set it null for contact to be deleted
a7488080 1528 if (!empty($submitted['external_identifier'])) {
6a488035
TO
1529 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1530 CRM_Core_DAO::executeQuery($query);
1531 }
1532
1533 civicrm_api('contact', 'delete', $otherParams);
1534 CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
1535 }
1536 // FIXME: else part
1537 /* else { */
1538
1539 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1540
1541 /* } */
1542
1543
4d5f18cc 1544 // CRM-15681 merge sub_types
1545 if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
1546 if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
1547 $submitted['contact_sub_type'] = array_unique( array_merge($main_sub_types, $other_sub_types));
1548 } else {
1549 $submitted['contact_sub_type'] = $other_sub_types;
1550 }
1551 }
1552
6a488035
TO
1553 // **** Update contact related info for the main contact
1554 if (!empty($submitted)) {
1555 $submitted['contact_id'] = $mainId;
1556
1557 //update current employer field
1558 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1559 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1560 $submitted['current_employer'] = $submitted['current_employer_id'];
1561 } else {
1562 $submitted['current_employer'] = '';
1563 }
1564 unset($submitted['current_employer_id']);
1565 }
1566
00f3da2e
BS
1567 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1568 if ( !isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id']) ) {
1569 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1570 }
1571 if ( !isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id']) ) {
1572 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1573 }
1574
6a488035
TO
1575 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
1576 unset($submitted);
1577 }
1578
1579 return TRUE;
1580 }
16254ae1
ARW
1581
1582 /**
1583 * @return array of field names which will be compared, so everything except ID.
1584 */
1585 static function getContactFields() {
1586 $contactFields = CRM_Contact_DAO_Contact::fields();
77b97be7 1587 $invalidFields = array('api_key', 'contact_is_deleted', 'created_date', 'display_name', 'hash', 'id', 'modified_date',
b857bab2 1588 'primary_contact_id', 'sort_name', 'user_unique_id');
bdd7870e
RN
1589 foreach ($contactFields as $field => $value) {
1590 if (in_array($field, $invalidFields)) {
1591 unset($contactFields[$field]);
1592 }
1593 }
16254ae1
ARW
1594 return array_keys($contactFields);
1595 }
ada104d5
AW
1596
1597 /**
1598 * Added for CRM-12695
1599 * Based on the contactId provided
1600 * add/update membership(s) to related contacts
1601 *
1602 * @param contactId
1603 */
1604 static function addMembershipToRealtedContacts($contactID) {
1605 $dao = new CRM_Member_DAO_Membership();
1606 $dao->contact_id = $contactID;
1607 $dao->is_test = 0;
1608 $dao->find();
1609
1610 //checks membership of contact itself
1611 while ($dao->fetch()) {
1612 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1613 if ($relationshipTypeId) {
1614 $membershipParams = array(
1615 'id' => $dao->id,
1616 'contact_id' => $dao->contact_id,
1617 'membership_type_id' => $dao->membership_type_id,
1618 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1619 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1620 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1621 'source' => $dao->source,
1622 'status_id' => $dao->status_id
1623 );
1624 // create/update membership(s) for related contact(s)
1625 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1626 } // end of if relationshipTypeId
1627 }
1628 }
6a488035 1629}