Merge pull request #9242 from mollux/CRM-18549
[civicrm-core.git] / CRM / Dedupe / Merger.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
6a488035
TO
32 */
33class CRM_Dedupe_Merger {
6a488035 34
e0ef6999 35 /**
4f1f1f2a
CW
36 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
37 * FIXME: the sub-pages references by the URLs should
38 * be loaded dynamically on the merge form instead
e0ef6999
EM
39 * @return array
40 */
00be9182 41 public static function relTables() {
6a488035
TO
42 static $relTables;
43
12d73bba 44 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
45 // if the url can't be retrieved. A more standardised way to retrieve them is.
46 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
47 // we may need a different function when it is not known.
48 $title = $userRecordUrl = '';
49
6a488035
TO
50 $config = CRM_Core_Config::singleton();
51 if ($config->userSystem->is_drupal) {
52 $userRecordUrl = CRM_Utils_System::url('user/%ufid');
53 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
54 }
55 elseif ($config->userFramework == 'Joomla') {
b8feed6e 56 $userRecordUrl = $config->userSystem->getVersion() > 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';
6a488035
TO
57 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
58 }
59
60 if (!$relTables) {
61 $relTables = array(
62 'rel_table_contributions' => array(
63 'title' => ts('Contributions'),
64 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
65 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
66 ),
67 'rel_table_contribution_page' => array(
68 'title' => ts('Contribution Pages'),
69 'tables' => array('civicrm_contribution_page'),
70 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
71 ),
72 'rel_table_memberships' => array(
73 'title' => ts('Memberships'),
74 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
75 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
76 ),
77 'rel_table_participants' => array(
78 'title' => ts('Participants'),
79 'tables' => array('civicrm_participant'),
80 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
81 ),
82 'rel_table_events' => array(
83 'title' => ts('Events'),
84 'tables' => array('civicrm_event'),
85 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
86 ),
87 'rel_table_activities' => array(
88 'title' => ts('Activities'),
91da6cd5 89 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
6a488035
TO
90 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
91 ),
92 'rel_table_relationships' => array(
93 'title' => ts('Relationships'),
94 'tables' => array('civicrm_relationship'),
95 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
96 ),
97 'rel_table_custom_groups' => array(
98 'title' => ts('Custom Groups'),
99 'tables' => array('civicrm_custom_group'),
100 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
101 ),
102 'rel_table_uf_groups' => array(
103 'title' => ts('Profiles'),
104 'tables' => array('civicrm_uf_group'),
105 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
106 ),
107 'rel_table_groups' => array(
108 'title' => ts('Groups'),
109 'tables' => array('civicrm_group_contact'),
110 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
111 ),
112 'rel_table_notes' => array(
113 'title' => ts('Notes'),
114 'tables' => array('civicrm_note'),
115 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
116 ),
117 'rel_table_tags' => array(
118 'title' => ts('Tags'),
119 'tables' => array('civicrm_entity_tag'),
120 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
121 ),
122 'rel_table_mailings' => array(
123 'title' => ts('Mailings'),
124 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
f521f375 125 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
6a488035
TO
126 ),
127 'rel_table_cases' => array(
128 'title' => ts('Cases'),
129 'tables' => array('civicrm_case_contact'),
130 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
131 ),
132 'rel_table_grants' => array(
133 'title' => ts('Grants'),
134 'tables' => array('civicrm_grant'),
135 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
136 ),
137 'rel_table_pcp' => array(
138 'title' => ts('PCPs'),
139 'tables' => array('civicrm_pcp'),
140 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
141 ),
142 'rel_table_pledges' => array(
143 'title' => ts('Pledges'),
144 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
145 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
146 ),
147 'rel_table_users' => array(
148 'title' => $title,
149 'tables' => array('civicrm_uf_match'),
150 'url' => $userRecordUrl,
151 ),
152 );
153
76c53278
CW
154 $relTables += self::getMultiValueCustomSets('relTables');
155
6a488035
TO
156 // Allow hook_civicrm_merge() to adjust $relTables
157 CRM_Utils_Hook::merge('relTables', $relTables);
158 }
159 return $relTables;
160 }
161
162 /**
fe482240 163 * Returns the related tables groups for which a contact has any info entered.
ad37ac8e 164 *
165 * @param int $cid
166 *
167 * @return array
6a488035 168 */
00be9182 169 public static function getActiveRelTables($cid) {
6a488035
TO
170 $cid = (int) $cid;
171 $groups = array();
172
173 $relTables = self::relTables();
174 $cidRefs = self::cidRefs();
175 $eidRefs = self::eidRefs();
176 foreach ($relTables as $group => $params) {
177 $sqls = array();
178 foreach ($params['tables'] as $table) {
179 if (isset($cidRefs[$table])) {
180 foreach ($cidRefs[$table] as $field) {
181 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
182 }
183 }
184 if (isset($eidRefs[$table])) {
185 foreach ($eidRefs[$table] as $entityTable => $entityId) {
186 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
187 }
188 }
189 foreach ($sqls as $sql) {
190 if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
191 $groups[] = $group;
192 }
193 }
194 }
195 }
196 return array_unique($groups);
197 }
198
199 /**
3ae0ae3d 200 * Get array tables and fields that reference civicrm_contact.id.
201 *
202 * This includes core tables, custom group tables, tables added by the merge
203 * hook and (somewhat randomly) the entity_tag table.
204 *
205 * Refer to CRM-17454 for information on the danger of querying the information
206 * schema to derive this.
207 *
e31c3de1 208 * This function calls the merge hook but the entityTypes hook is the recommended
209 * way to add tables to this result.
6a488035 210 */
00be9182 211 public static function cidRefs() {
e31c3de1 212 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) {
213 return \Civi::$statics[__CLASS__]['contact_references'];
214 }
215 $contactReferences = array();
3ae0ae3d 216 $coreReferences = CRM_Core_DAO::getReferencesToTable('civicrm_contact');
217 foreach ($coreReferences as $coreReference) {
218 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
e31c3de1 219 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
6a488035 220 }
3ae0ae3d 221 }
e31c3de1 222 self::addCustomTablesExtendingContactsToCidRefs($contactReferences);
64b3569d 223
3ae0ae3d 224 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
e31c3de1 225 $contactReferences['civicrm_entity_tag'][] = 'entity_id';
6a488035 226
3ae0ae3d 227 // Allow hook_civicrm_merge() to adjust $cidRefs.
e31c3de1 228 // Note that if entities are registered using the entityTypes hook there
229 // is no need to use this hook.
230 CRM_Utils_Hook::merge('cidRefs', $contactReferences);
231 \Civi::$statics[__CLASS__]['contact_references'] = $contactReferences;
232 return \Civi::$statics[__CLASS__]['contact_references'];
6a488035
TO
233 }
234
235 /**
236 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
237 */
00be9182 238 public static function eidRefs() {
6a488035
TO
239 static $eidRefs;
240 if (!$eidRefs) {
241 // FIXME: this should be generated dynamically from the schema
242 // tables that reference contacts with entity_{id,table}
243 $eidRefs = array(
244 'civicrm_acl' => array('entity_table' => 'entity_id'),
245 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
246 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
247 'civicrm_log' => array('entity_table' => 'entity_id'),
248 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
249 'civicrm_note' => array('entity_table' => 'entity_id'),
6a488035
TO
250 );
251
252 // Allow hook_civicrm_merge() to adjust $eidRefs
253 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
254 }
255 return $eidRefs;
256 }
257
9da04f20 258 /**
fe482240 259 * Return tables using locations.
9da04f20 260 */
00be9182 261 public static function locTables() {
9da04f20
AS
262 static $locTables;
263 if (!$locTables) {
481a74f4 264 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
9da04f20
AS
265
266 // Allow hook_civicrm_merge() to adjust $locTables
267 CRM_Utils_Hook::merge('locTables', $locTables);
268 }
269 return $locTables;
270 }
271
76c53278
CW
272 /**
273 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
98997235
TO
274 * @param string $request
275 * 'relTables' or 'cidRefs'.
76c53278
CW
276 * @see CRM-13836
277 */
00be9182 278 public static function getMultiValueCustomSets($request) {
76c53278
CW
279 static $data = NULL;
280 if ($data === NULL) {
281 $data = array(
282 'relTables' => array(),
283 'cidRefs' => array(),
284 );
285 $result = civicrm_api3('custom_group', 'get', array(
286 'is_multiple' => 1,
287 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
288 'return' => array('id', 'title', 'table_name', 'style'),
289 ));
22e263ad 290 foreach ($result['values'] as $custom) {
76c53278
CW
291 $data['cidRefs'][$custom['table_name']] = array('entity_id');
292 $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
293 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
294 'title' => $custom['title'],
295 'tables' => array($custom['table_name']),
296 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
297 );
298 }
299 }
300 return $data[$request];
301 }
302
6a488035
TO
303 /**
304 * Tables which require custom processing should declare functions to call here.
305 * Doing so will override normal processing.
306 */
00be9182 307 public static function cpTables() {
6a488035
TO
308 static $tables;
309 if (!$tables) {
310 $tables = array(
311 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
312 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
313 // Empty array == do nothing - this table is handled by mergeGroupContact
314 'civicrm_subscription_history' => array(),
315 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
316 );
317 }
318 return $tables;
319 }
320
321 /**
100fef9d 322 * Return payment related table.
6a488035 323 */
00be9182 324 public static function paymentTables() {
6a488035
TO
325 static $tables;
326 if (!$tables) {
327 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
328 }
6a488035
TO
329 return $tables;
330 }
331
332 /**
100fef9d 333 * Return payment update Query.
54957108 334 *
335 * @param string $tableName
336 * @param int $mainContactId
337 * @param int $otherContactId
338 *
339 * @return array
6a488035 340 */
00be9182 341 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
6a488035
TO
342 $sqls = array();
343 if (!$tableName || !$mainContactId || !$otherContactId) {
344 return $sqls;
345 }
346
347 $paymentTables = self::paymentTables();
348 if (!in_array($tableName, $paymentTables)) {
349 return $sqls;
350 }
351
352 switch ($tableName) {
353 case 'civicrm_pledge':
354 $sqls[] = "
355 UPDATE IGNORE civicrm_contribution contribution
356INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
357INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
358 SET contribution.contact_id = $mainContactId
359 WHERE pledge.contact_id = $otherContactId";
360 break;
361
362 case 'civicrm_membership':
363 $sqls[] = "
364 UPDATE IGNORE civicrm_contribution contribution
365INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
366INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
367 SET contribution.contact_id = $mainContactId
368 WHERE membership.contact_id = $otherContactId";
369 break;
370
371 case 'civicrm_participant':
372 $sqls[] = "
373 UPDATE IGNORE civicrm_contribution contribution
374INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
375INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
376 SET contribution.contact_id = $mainContactId
377 WHERE participant.contact_id = $otherContactId";
378 break;
379 }
380
381 return $sqls;
382 }
383
e0ef6999 384 /**
100fef9d
CW
385 * @param int $mainId
386 * @param int $otherId
387 * @param string $tableName
e0ef6999
EM
388 * @param array $tableOperations
389 * @param string $mode
390 *
391 * @return array
392 */
00be9182 393 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
6a488035
TO
394 $sqls = array();
395 if (!$tableName || !$mainId || !$otherId) {
396 return $sqls;
397 }
398
6a488035
TO
399 switch ($tableName) {
400 case 'civicrm_membership':
d58a19a1
TO
401 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
402 break;
403 }
404 if ($mode == 'add') {
405 $sqls[] = "
6a488035
TO
406DELETE membership1.* FROM civicrm_membership membership1
407 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
408 AND membership1.contact_id = {$mainId}
409 AND membership2.contact_id = {$otherId} ";
d58a19a1
TO
410 }
411 if ($mode == 'payment') {
412 $sqls[] = "
6a488035
TO
413DELETE contribution.* FROM civicrm_contribution contribution
414INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
415INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
416 AND membership1.contact_id = {$mainId}
417INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
418 AND membership2.contact_id = {$otherId}";
d58a19a1
TO
419 }
420 break;
6a488035
TO
421
422 case 'civicrm_uf_match':
423 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
b44e3f84 424 // failing to meet intended result. Therefore we introduce this additional query:
6a488035
TO
425 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
426 break;
427 }
428
429 return $sqls;
430 }
431
432 /**
433 * Based on the provided two contact_ids and a set of tables, move the
434 * belongings of the other contact to the main one.
435 *
54957108 436 * @param int $mainId
437 * @param int $otherId
438 * @param bool $tables
439 * @param array $tableOperations
6a488035 440 */
00be9182 441 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
6a488035
TO
442 $cidRefs = self::cidRefs();
443 $eidRefs = self::eidRefs();
444 $cpTables = self::cpTables();
445 $paymentTables = self::paymentTables();
c5c263ca
AH
446 // CRM-12695:
447 $membershipMerge = FALSE;
6a488035
TO
448
449 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
450 if ($tables !== FALSE) {
451 // if there are specific tables, sanitize the list
452 $affected = array_unique(array_intersect($affected, $tables));
453 }
454 else {
455 // if there aren't any specific tables, don't affect the ones handled by relTables()
9da04f20 456 // also don't affect tables in locTables() CRM-15658
6a488035 457 $relTables = self::relTables();
9da04f20 458 $handled = self::locTables();
6a488035
TO
459 foreach ($relTables as $params) {
460 $handled = array_merge($handled, $params['tables']);
461 }
462 $affected = array_diff($affected, $handled);
ada104d5
AW
463 /**
464 * CRM-12695
465 * Set $membershipMerge flag only once
466 * while doing contact related migration
467 * to call addMembershipToRealtedContacts()
468 * function only once.
469 * Since the current function (moveContactBelongings) is called twice
470 * with & without parameters $tables & $tableOperations
471 */
472 // retrieve main contact's related table(s)
473 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
474 // check if membership table exists in main contact's related table(s)
c5c263ca 475 // set membership flag - CRM-12695
ada104d5 476 if (in_array('rel_table_memberships', $activeMainRelTables)) {
c5c263ca 477 $membershipMerge = TRUE;
ada104d5 478 }
6a488035
TO
479 }
480
481 $mainId = (int) $mainId;
482 $otherId = (int) $otherId;
483
484 $sqls = array();
485 foreach ($affected as $table) {
486 // Call custom processing function for objects that require it
487 if (isset($cpTables[$table])) {
488 foreach ($cpTables[$table] as $className => $fnName) {
489 $className::$fnName($mainId, $otherId, $sqls);
490 }
491 // Skip normal processing
492 continue;
493 }
b3fdbf3d 494
6a488035
TO
495 // use UPDATE IGNORE + DELETE query pair to skip on situations when
496 // there's a UNIQUE restriction on ($field, some_other_field) pair
497 if (isset($cidRefs[$table])) {
498 foreach ($cidRefs[$table] as $field) {
499 // carry related contributions CRM-5359
500 if (in_array($table, $paymentTables)) {
6a488035
TO
501 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
502 $sqls = array_merge($sqls, $paymentSqls);
71560cf3
C
503
504 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
505 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
506 $sqls = array_merge($sqls, $payOprSqls);
507 }
6a488035
TO
508 }
509
510 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
511 $sqls = array_merge($sqls, $preOperationSqls);
512
513 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
514 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
515 }
516 }
517 if (isset($eidRefs[$table])) {
518 foreach ($eidRefs[$table] as $entityTable => $entityId) {
519 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
520 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
521 }
522 }
523 }
524
525 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
526 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
527
528 // call the SQL queries in one transaction
529 $transaction = new CRM_Core_Transaction();
530 foreach ($sqls as $sql) {
531 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE);
532 }
ada104d5
AW
533 // CRM-12695
534 if ($membershipMerge) {
535 // call to function adding membership to related contacts
536 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
537 }
6a488035
TO
538 $transaction->commit();
539 }
540
541 /**
4eea8606 542 * Load all non-empty fields for the contacts
b3fdbf3d 543 *
98997235
TO
544 * @param array $main
545 * Contact details.
546 * @param array $other
547 * Contact details.
6a488035 548 *
77b97be7 549 * @return array
6a488035 550 */
4eea8606 551 public static function retrieveFields($main, $other) {
6a488035
TO
552 $result = array(
553 'contact' => array(),
554 'custom' => array(),
555 );
16254ae1 556 foreach (self::getContactFields() as $validField) {
eb61dc07
J
557 // CRM-17556 Get all non-empty fields, to make comparison easier
558 if (!empty($main[$validField]) || !empty($other[$validField])) {
6a488035
TO
559 $result['contact'][] = $validField;
560 }
561 }
562
563 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
564 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
565 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
566 foreach ($keys as $key) {
76c53278
CW
567 // Exclude multi-value fields CRM-13836
568 if (strpos($key, '_')) {
569 continue;
570 }
6a488035
TO
571 $key1 = CRM_Utils_Array::value($key, $mainEvs);
572 $key2 = CRM_Utils_Array::value($key, $otherEvs);
eb61dc07 573 // CRM-17556 Get all non-empty fields, to make comparison easier
08ef1f91 574 if (!empty($key1) || !empty($key2)) {
6a488035
TO
575 $result['custom'][] = $key;
576 }
577 }
578 return $result;
579 }
580
581 /**
100fef9d 582 * Batch merge a set of contacts based on rule-group and group.
6a488035 583 *
98997235
TO
584 * @param int $rgid
585 * Rule group id.
586 * @param int $gid
587 * Group id.
588 * @param string $mode
589 * Helps decide how to behave when there are conflicts.
15a793bb
EM
590 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
591 * mode does a force merge.
c301f76e 592 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
76ddbc8e 593 * Whether to let api decide which contact to retain and which to delete.
f931b74c 594 * @param int $batchLimit number of merges to carry out in one batch.
595 * @param int $isSelected if records with is_selected column needs to be processed.
6a488035 596 *
e23e26ec 597 * @param array $criteria
598 * Criteria to use in the filter.
599 *
3058f4d9 600 * @param bool $checkPermissions
601 * Respect logged in user permissions.
602 *
77b97be7 603 * @return array|bool
6a488035 604 */
3058f4d9 605 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $batchLimit = 1, $isSelected = 2, $criteria = array(), $checkPermissions = TRUE) {
63ef778e 606 $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
2988f5c7 607 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
3058f4d9 608 $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, '', ($mode == 'aggressive'), $criteria, $checkPermissions);
6a488035
TO
609
610 $cacheParams = array(
3058f4d9 611 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
2988f5c7 612 // @todo stop passing these parameters in & instead calculate them in the merge function based
613 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
614 'join' => self::getJoinOnDedupeTable(),
615 'where' => self::getWhereString($batchLimit, $isSelected),
6a488035 616 );
3058f4d9 617 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance, $checkPermissions);
6a488035
TO
618 }
619
2ae26001 620 /**
621 * Get the string to join the prevnext cache to the dedupe table.
622 *
623 * @return string
624 * The join string to join prevnext cache on the dedupe table.
625 */
626 public static function getJoinOnDedupeTable() {
627 return "
628 LEFT JOIN civicrm_dedupe_exception de
629 ON (
630 pn.entity_id1 = de.contact_id1
631 AND pn.entity_id2 = de.contact_id2 )
632 ";
633 }
634
2988f5c7 635 /**
636 * Get where string for dedupe join.
637 *
638 * @param int $batchLimit
639 * @param bool $isSelected
640 *
641 * @return string
642 */
643 protected static function getWhereString($batchLimit, $isSelected) {
644 $where = "de.id IS NULL";
645 if ($isSelected === 0 || $isSelected === 1) {
646 $where .= " AND pn.is_selected = {$isSelected}";
647 }
648 // else consider all dupe pairs
649 // @todo Adding limit to Where??!!
650 $where .= " LIMIT {$batchLimit}";
651 return $where;
652 }
653
f931b74c 654 public static function updateMergeStats($cacheKeyString, $result = array()) {
63ef778e 655 // gather latest stats
656 $merged = count($result['merged']);
657 $skipped = count($result['skipped']);
658
659 if ($merged <= 0 && $skipped <= 0) {
660 return;
661 }
662
663 // get previous stats
664 $previousStats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
665 if (!empty($previousStats)) {
666 if ($previousStats[0]['merged']) {
667 $merged = $merged + $previousStats[0]['merged'];
668 }
669 if ($previousStats[0]['skipped']) {
670 $skipped = $skipped + $previousStats[0]['skipped'];
671 }
672 }
673
674 // delete old stats
675 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
676
677 // store the updated stats
678 $data = array(
679 'merged' => $merged,
680 'skipped' => $skipped,
681 );
682 $data = CRM_Core_DAO::escapeString(serialize($data));
683
684 $values = array();
685 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
686 CRM_Core_BAO_PrevNextCache::setItem($values);
687 }
688
ae6455b2 689 /**
690 * Delete information about merges for the given string.
691 *
692 * @param $cacheKeyString
693 */
f931b74c 694 public static function resetMergeStats($cacheKeyString) {
ae6455b2 695 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
63ef778e 696 }
697
f931b74c 698 public static function getMergeStats($cacheKeyString) {
63ef778e 699 $stats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
700 if (!empty($stats)) {
701 $stats = $stats[0];
702 }
703 return $stats;
704 }
705
f931b74c 706 public static function getMergeStatsMsg($cacheKeyString) {
63ef778e 707 $msg = '';
708 $stats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
709 if (!empty($stats['merged'])) {
8dcd31bf 710 $msg = "{$stats['merged']} " . ts('Contact(s) were merged.');
63ef778e 711 }
712 if (!empty($stats['skipped'])) {
1fe557c2 713 $msg .= $stats['skipped'] . ts(' Contact(s) were skipped.');
63ef778e 714 }
715 return $msg;
716 }
717
6a488035 718 /**
100fef9d 719 * Merge given set of contacts. Performs core operation.
6a488035 720 *
98997235
TO
721 * @param array $dupePairs
722 * Set of pair of contacts for whom merge is to be done.
723 * @param array $cacheParams
724 * Prev-next-cache params based on which next pair of contacts are computed.
6a488035 725 * Generally used with batch-merge.
98997235
TO
726 * @param string $mode
727 * Helps decide how to behave when there are conflicts.
6a488035
TO
728 * A 'safe' value skips the merge if there are any un-resolved conflicts.
729 * Does a force merge otherwise (aggressive mode).
c301f76e 730 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
3058f4d9 731 * Whether to let api decide which contact to retain and which to delete.
6a488035 732 *
77b97be7 733 * @param bool $redirectForPerformance
3058f4d9 734 * Redirect to a url for batch processing.
735 *
736 * @param bool $checkPermissions
737 * Respect logged in user permissions.
77b97be7
EM
738 *
739 * @return array|bool
6a488035 740 */
00be9182 741 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
3058f4d9 742 $autoFlip = TRUE, $redirectForPerformance = FALSE, $checkPermissions = TRUE
6a488035
TO
743 ) {
744 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
745 $resultStats = array('merged' => array(), 'skipped' => array());
746
747 // we don't want dupe caching to get reset after every-merge, and therefore set the
748 // doNotResetCache flag
749 $config = CRM_Core_Config::singleton();
750 $config->doNotResetCache = 1;
78272750 751 $deletedContacts = array();
6a488035
TO
752
753 while (!empty($dupePairs)) {
78272750 754 foreach ($dupePairs as $index => $dupes) {
755 if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) {
756 unset($dupePairs[$index]);
757 continue;
758 }
1cf05c3e 759 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
6a488035
TO
760 $mainId = $dupes['dstID'];
761 $otherId = $dupes['srcID'];
e67dcaf8 762
6a488035
TO
763 if (!$mainId || !$otherId) {
764 // return error
765 return FALSE;
766 }
6a488035
TO
767 // Generate var $migrationInfo. The variable structure is exactly same as
768 // $formValues submitted during a UI merge for a pair of contacts.
201057c0 769 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions);
6a488035 770 // add additional details that we might need to resolve conflicts
e4e1db4b 771 $rowsElementsAndInfo['migration_info']['main_details'] = &$rowsElementsAndInfo['main_details'];
772 $rowsElementsAndInfo['migration_info']['other_details'] = &$rowsElementsAndInfo['other_details'];
773 $rowsElementsAndInfo['migration_info']['rows'] = &$rowsElementsAndInfo['rows'];
6a488035 774
e4e1db4b 775 self::dedupePair($rowsElementsAndInfo['migration_info'], $resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString);
6a488035
TO
776 }
777
778 if ($cacheKeyString && !$redirectForPerformance) {
779 // retrieve next pair of dupes
2988f5c7 780 // @todo call getDuplicatePairs.
6a488035
TO
781 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
782 $cacheParams['join'],
66eceb0b 783 $cacheParams['where'],
784 0,
785 0,
786 array(),
787 '',
788 FALSE
6a488035
TO
789 );
790 }
791 else {
792 // do not proceed. Terminate the loop
793 unset($dupePairs);
794 }
795 }
63ef778e 796
797 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
6a488035
TO
798 return $resultStats;
799 }
800
801 /**
802 * A function which uses various rules / algorithms for choosing which contact to bias to
803 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
804 *
98997235
TO
805 * @param int $mainId
806 * Main contact with whom merge has to happen.
807 * @param int $otherId
808 * Duplicate contact which would be deleted after merge operation.
809 * @param array $migrationInfo
810 * Array of information about which elements to merge.
811 * @param string $mode
812 * Helps decide how to behave when there are conflicts.
13919cf8
J
813 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
814 * - Does a force merge otherwise (aggressive mode).
6a488035 815 *
ad37ac8e 816 * @param array $conflicts
817 *
77b97be7 818 * @return bool
6a488035 819 */
63ef778e 820 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
0971143c 821
c08fae40 822 $originalMigrationInfo = $migrationInfo;
6a488035
TO
823 foreach ($migrationInfo as $key => $val) {
824 if ($val === "null") {
0971143c 825 // Rule: Never overwrite with an empty value (in any mode)
6a488035
TO
826 unset($migrationInfo[$key]);
827 continue;
828 }
16254ae1 829 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
6a488035 830 substr($key, 0, 12) == 'move_custom_'
353ffa53
TO
831 ) and $val != NULL
832 ) {
0971143c
J
833 // Rule: If both main-contact, and other-contact have a field with a
834 // different value, then let $mode decide if to merge it or not
4eea8606 835 if (
e2cecb9c 836 (!empty($migrationInfo['rows'][$key]['main'])
837 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
838 // is probably true for other fields too - e.g. 'do_not_email' but
839 // leaving that investigation as a @todo - until tests can be written.
840 // Note the handling of this has test coverage - although the data-typing
841 // of '0' feels flakey we have insurance.
842 || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
843 )
4eea8606
J
844 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
845 ) {
fd630ef9 846
847 // note it down & lets wait for response from the hook.
848 // For no response $mode will decide if to skip this merge
849 $conflicts[$key] = NULL;
6a488035
TO
850 }
851 }
852 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
853 $locField = explode('_', $key);
854 $fieldName = $locField[2];
855 $fieldCount = $locField[3];
856
4ece0d26 857 // Rule: Catch address conflicts (same address type on both contacts)
13cc4cac 858 if (
859 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
860 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
861 ) {
862
863 // Load the address we're inspecting from the 'other' contact
864 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
865 $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord);
b982316c 866
13cc4cac 867 // If it exists on the 'main' contact already, skip it. Otherwise
868 // if the location type exists already, log a conflict.
869 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
5d5b49ad 870 if (self::locationIsSame($addressRecord, $mainAddressRecord)) {
13cc4cac 871 unset($migrationInfo[$key]);
872 break;
873 }
874 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
875 $conflicts[$key] = NULL;
876 break;
877 }
6a488035
TO
878 }
879 }
13cc4cac 880
4ece0d26 881 // For other locations, don't merge/add if the values are the same
13cc4cac 882 elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
6a488035
TO
883 unset($migrationInfo[$key]);
884 }
885 }
886 }
887
888 // A hook to implement other algorithms for choosing which contact to bias to when
889 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
890 // merge happens with new values filled in here. For a particular field / row not to be merged
891 // field should be unset from fields_in_conflict.
c08fae40 892 $migrationData = array(
893 'old_migration_info' => $originalMigrationInfo,
894 'mode' => $mode,
895 'fields_in_conflict' => $conflicts,
896 'merge_mode' => $mode,
897 'migration_info' => $migrationInfo,
898 );
6a488035
TO
899 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
900 $conflicts = $migrationData['fields_in_conflict'];
63ef778e 901 // allow hook to override / manipulate migrationInfo as well
c08fae40 902 $migrationInfo = $migrationData['migration_info'];
6a488035
TO
903
904 if (!empty($conflicts)) {
905 foreach ($conflicts as $key => $val) {
906 if ($val === NULL and $mode == 'safe') {
63ef778e 907 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
6a488035
TO
908 return TRUE;
909 }
910 else {
911 // copy over the resolved values
912 $migrationInfo[$key] = $val;
913 }
914 }
fd630ef9 915 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
916 if (array_key_exists('skip_merge', $migrationData)) {
917 return (bool) $migrationData['skip_merge'];
918 }
6a488035
TO
919 }
920 return FALSE;
921 }
922
d48ad2c0 923 /**
924 * Compare 2 addresses to see if they are the same.
925 *
926 * @param array $mainAddress
927 * @param array $comparisonAddress
928 *
929 * @return bool
930 */
5d5b49ad 931 static public function locationIsSame($mainAddress, $comparisonAddress) {
d48ad2c0 932 $keysToIgnore = array('id', 'is_primary', 'is_billing', 'manual_geo_code', 'contact_id');
933 foreach ($comparisonAddress as $field => $value) {
934 if (in_array($field, $keysToIgnore)) {
935 continue;
936 }
dc7a41cb 937 if (!empty($value) && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
d48ad2c0 938 return FALSE;
939 }
940 }
941 return TRUE;
942 }
943
34917198
J
944 /**
945 * A function to build an array of information about location blocks that is
946 * required when merging location fields
947 *
948 * @return array
949 */
950 public static function getLocationBlockInfo() {
951 $locationBlocks = array(
952 'address' => array(
953 'label' => 'Address',
954 'displayField' => 'display',
955 'sortString' => 'location_type_id',
956 'hasLocation' => TRUE,
957 'hasType' => FALSE,
958 ),
959 'email' => array(
960 'label' => 'Email',
961 'displayField' => 'email',
962 'sortString' => 'location_type_id',
963 'hasLocation' => TRUE,
964 'hasType' => FALSE,
965 ),
966 'im' => array(
967 'label' => 'IM',
968 'displayField' => 'name',
969 'sortString' => 'location_type_id,provider_id',
970 'hasLocation' => TRUE,
971 'hasType' => 'provider_id',
972 ),
973 'phone' => array(
974 'label' => 'Phone',
975 'displayField' => 'phone',
976 'sortString' => 'location_type_id,phone_type_id',
977 'hasLocation' => TRUE,
978 'hasType' => 'phone_type_id',
979 ),
980 'website' => array(
981 'label' => 'Website',
982 'displayField' => 'url',
983 'sortString' => 'website_type_id',
984 'hasLocation' => FALSE,
985 'hasType' => 'website_type_id',
986 ),
987 );
988 return $locationBlocks;
989 }
990
6a488035
TO
991 /**
992 * A function to build an array of information required by merge function and the merge UI.
993 *
98997235
TO
994 * @param int $mainId
995 * Main contact with whom merge has to happen.
996 * @param int $otherId
997 * Duplicate contact which would be deleted after merge operation.
201057c0 998 * @param bool $checkPermissions
999 * Should the logged in user's permissions be ignore. Setting this to false is
1000 * highly risky as it could cause data to be lost due to conflicts not showing up.
1001 * OTOH there is a risk a merger might view custom data they do not have permission to.
1002 * Hence for now only making this really explicit and making it reflect perms in
1003 * an api call.
1004 *
1005 * @todo review permissions issue!
6a488035 1006 *
77b97be7 1007 * @return array|bool|int
1e3e0eed
J
1008 *
1009 * rows => An array of arrays, each is row of merge information for the table
1010 * Format: move_fieldname, eg: move_contact_type
1011 * main => Value associated with the main contact
1012 * other => Value associated with the other contact
1013 * title => The title of the field to display in the merge table
1014 *
1015 * elements => An array of form elements for the merge UI
1016 *
1017 * rel_table_elements => An array of form elements for the merge UI for
1018 * entities related to the contact (eg: checkbox to move 'mailings')
1019 *
1e3e0eed
J
1020 * rel_tables => Stores the tables that have related entities for the contact
1021 * for example mailings, groups
1022 *
1023 * main_details => An array of core contact field values, eg: first_name, etc.
1024 * location_blocks => An array of location block data for the main contact
1025 * stored as the 'result' of an API call.
1026 * eg: main_details['location_blocks']['address'][0]['id']
1027 * eg: main_details['location_blocks']['email'][1]['id']
1028 *
1029 * other_details => As above, but for the 'other' contact
1030 *
1031 * migration_info => Stores the 'default' merge actions for each field which
1032 * is used when programatically merging contacts. It contains instructions
1033 * to move all fields from the 'other' contact to the 'main' contact, as
1034 * though the form had been submitted with those options.
1035 *
3058f4d9 1036 * @throws \CRM_Core_Exception
1037 * @throws \CiviCRM_API3_Exception
1038 * @throws \Exception
6a488035 1039 */
201057c0 1040 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
6a488035 1041 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
74a6069d 1042 $fields = self::getMergeFieldsMetadata();
6a488035 1043
74a6069d 1044 $main = self::getMergeContactDetails($mainId, 'main');
1045 $other = self::getMergeContactDetails($otherId, 'main');
1046 $specialValues['main'] = self::getSpecialValues($main);
1047 $specialValues['other'] = self::getSpecialValues($other);
6a488035 1048
4eea8606 1049 $compareFields = self::retrieveFields($main, $other);
6a488035
TO
1050
1051 $rows = $elements = $relTableElements = $migrationInfo = array();
1052
4eea8606 1053 foreach ($compareFields['contact'] as $field) {
4d5f18cc 1054 if ($field == 'contact_sub_type') {
1055 // CRM-15681 don't display sub-types in UI
1056 continue;
1057 }
6a488035
TO
1058 foreach (array('main', 'other') as $moniker) {
1059 $contact = &$$moniker;
1060 $value = CRM_Utils_Array::value($field, $contact);
1061 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
1062 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
1063 }
1064 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
a7488080 1065 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
6a488035
TO
1066 if ($value) {
1067 $value = str_replace('-', '', $value);
1068 $label = CRM_Utils_Date::customFormat($label);
1069 }
1070 else {
1071 $value = "null";
1072 }
1073 }
a7488080 1074 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
6a488035
TO
1075 if ($label === '0') {
1076 $label = ts('[ ]');
1077 }
1078 if ($label === '1') {
1079 $label = ts('[x]');
1080 }
00f3da2e 1081 }
74a6069d 1082 elseif ($field == 'prefix_id') {
00f3da2e 1083 $label = CRM_Utils_Array::value('individual_prefix', $contact);
00f3da2e 1084 }
74a6069d 1085 elseif ($field == 'suffix_id') {
00f3da2e 1086 $label = CRM_Utils_Array::value('individual_suffix', $contact);
6a488035 1087 }
4f88c9cf 1088 elseif ($field == 'gender_id' && !empty($value)) {
5b28be84
J
1089 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
1090 $label = $genderOptions['values'][$value];
4f88c9cf
C
1091 }
1092 elseif ($field == 'current_employer_id' && !empty($value)) {
1093 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
1094 }
6a488035
TO
1095 $rows["move_$field"][$moniker] = $label;
1096 if ($moniker == 'other') {
7154d2a4
BS
1097 //CRM-14334
1098 if ($value === NULL || $value == '') {
6a488035
TO
1099 $value = 'null';
1100 }
1101 if ($value === 0 or $value === '0') {
1102 $value = $qfZeroBug;
1103 }
8cc574cf 1104 if (is_array($value) && empty($value[1])) {
6a488035
TO
1105 $value[1] = NULL;
1106 }
13919cf8
J
1107
1108 // Display a checkbox to migrate, only if the values are different
1109 if ($value != $main[$field]) {
1110 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1111 }
1112
6a488035
TO
1113 $migrationInfo["move_$field"] = $value;
1114 }
1115 }
1116 $rows["move_$field"]['title'] = $fields[$field]['title'];
1117 }
1118
eb61dc07
J
1119 // Handle location blocks.
1120 // @todo OpenID not in API yet, so is not supported here.
65a35632 1121
087f00ec 1122 // Set up useful information about the location blocks
34917198 1123 $locationBlocks = self::getLocationBlockInfo();
087f00ec
J
1124
1125 $locations = array(
1126 'main' => array(),
1127 'other' => array(),
13919cf8 1128 );
b814df56 1129
087f00ec
J
1130 // @todo This could probably be defined and used earlier
1131 $mergeTargets = array(
1132 'main' => $mainId,
1133 'other' => $otherId,
1134 );
6a488035 1135
087f00ec 1136 foreach ($locationBlocks as $blockName => $blockInfo) {
6a488035 1137
087f00ec
J
1138 // Collect existing fields from both 'main' and 'other' contacts first
1139 // This allows us to match up location/types when building the table rows
1140 foreach ($mergeTargets as $moniker => $cid) {
b932e89e 1141 $searchParams = array(
b932e89e 1142 'contact_id' => $cid,
087f00ec
J
1143 // CRM-17556 Order by field-specific criteria
1144 'options' => array(
1145 'sort' => $blockInfo['sortString'],
1146 ),
b932e89e 1147 );
0b50eca0 1148 $values = civicrm_api3($blockName, 'get', $searchParams);
087f00ec
J
1149 if ($values['count']) {
1150 $cnt = 0;
1151 foreach ($values['values'] as $index => $value) {
1152 $locations[$moniker][$blockName][$cnt] = $value;
1153 // Fix address display
eb61dc07 1154 if ($blockName == 'address') {
087f00ec 1155 CRM_Core_BAO_Address::fixAddress($value);
ae6455b2 1156 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address::format($value);
6a488035 1157 }
abb422f9 1158
087f00ec 1159 $cnt++;
6a488035
TO
1160 }
1161 }
1162 }
6a488035 1163
087f00ec
J
1164 // Now, build the table rows appropriately, based off the information on
1165 // the 'other' contact
34917198
J
1166 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1167 foreach ($locations['other'][$blockName] as $count => $value) {
6a488035 1168
087f00ec 1169 $displayValue = $value[$blockInfo['displayField']];
65a35632 1170
087f00ec
J
1171 // Add this value to the table rows
1172 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
65a35632 1173
087f00ec
J
1174 // CRM-17556 Only display 'main' contact value if it's the same location + type
1175 // Look it up from main values...
65a35632 1176
087f00ec
J
1177 $lookupLocation = FALSE;
1178 if ($blockInfo['hasLocation']) {
1179 $lookupLocation = $value['location_type_id'];
1180 }
65a35632 1181
087f00ec
J
1182 $lookupType = FALSE;
1183 if ($blockInfo['hasType']) {
13cc4cac 1184 $lookupType = CRM_Utils_Array::value($blockInfo['hasType'], $value);
087f00ec 1185 }
65a35632 1186
34917198
J
1187 // Hold ID of main contact's matching block
1188 $mainContactBlockId = 0;
1189
087f00ec
J
1190 if (!empty($locations['main'][$blockName])) {
1191 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1192 // No location/type, or matching location and type
1193 if (
1194 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
1195 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
1196 ) {
34917198 1197 // Set this value as the default against the 'other' contact value
087f00ec 1198 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
041d6d6b 1199 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
34917198 1200 $mainContactBlockId = $mainValueCheck['id'];
087f00ec
J
1201 break;
1202 }
6a488035 1203 }
087f00ec 1204 }
65a35632 1205
087f00ec
J
1206 // Add checkbox to migrate data from 'other' to 'main'
1207 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
65a35632 1208
abd0b852
J
1209 // Add checkbox to set the 'other' location as primary
1210 $elements[] = array('advcheckbox', "location_blocks[$blockName][$count][set_other_primary]", NULL, ts('Set as primary'));
1211
087f00ec
J
1212 // Flag up this field to skipMerge function (@todo: do we need to?)
1213 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
65a35632 1214
34917198 1215 // Add a hidden field to store the ID of the target main contact block
972947a7 1216 $elements[] = array('hidden', "location_blocks[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
34917198 1217
087f00ec
J
1218 // Setup variables
1219 $thisTypeId = FALSE;
1220 $thisLocId = FALSE;
65a35632 1221
087f00ec
J
1222 // Provide a select drop-down for the location's location type
1223 // eg: Home, Work...
65a35632 1224
087f00ec
J
1225 if ($blockInfo['hasLocation']) {
1226
5b28be84
J
1227 // Load the location options for this entity
1228 $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
1229
087f00ec
J
1230 $thisLocId = $value['location_type_id'];
1231
1232 // Put this field's location type at the top of the list
5b28be84 1233 $tmpIdList = $locationOptions['values'];
087f00ec
J
1234 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1235 unset($tmpIdList[$thisLocId]);
1236
1237 // Add the element
eb61dc07
J
1238 $elements[] = array(
1239 'select',
972947a7 1240 "location_blocks[$blockName][$count][locTypeId]",
eb61dc07 1241 NULL,
087f00ec 1242 $defaultLocId + $tmpIdList,
6a488035 1243 );
087f00ec
J
1244
1245 // Add the relevant information to the $migrationInfo
1246 // Keep location-type-id same as that of other-contact
1247 // @todo Check this logic out
1248 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
abb422f9 1249 if ($blockName != 'address') {
abd0b852 1250 $elements[] = array('advcheckbox', "location_blocks[{$blockName}][$count][operation]", NULL, ts('Add new'));
087f00ec 1251 // always use add operation
abb422f9 1252 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
6a488035 1253 }
087f00ec 1254
6a488035 1255 }
6a488035 1256
087f00ec
J
1257 // Provide a select drop-down for the location's type/provider
1258 // eg websites: Google+, Facebook...
1259
087f00ec
J
1260 if ($blockInfo['hasType']) {
1261
5b28be84
J
1262 // Load the type options for this entity
1263 $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
1264
13cc4cac 1265 $thisTypeId = CRM_Utils_Array::value($blockInfo['hasType'], $value);
087f00ec
J
1266
1267 // Put this field's location type at the top of the list
5b28be84 1268 $tmpIdList = $typeOptions['values'];
13cc4cac 1269 $defaultTypeId = array($thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList));
087f00ec
J
1270 unset($tmpIdList[$thisTypeId]);
1271
1272 // Add the element
65a35632
J
1273 $elements[] = array(
1274 'select',
972947a7 1275 "location_blocks[$blockName][$count][typeTypeId]",
65a35632 1276 NULL,
087f00ec 1277 $defaultTypeId + $tmpIdList,
65a35632 1278 );
65a35632 1279
1e3e0eed 1280 // Add the information to the migrationInfo
34917198 1281 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
65a35632 1282
6a488035 1283 }
087f00ec
J
1284
1285 // Set the label for this row
34917198
J
1286 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
1287 if (!empty($thisLocId)) {
5b28be84 1288 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
6a488035 1289 }
34917198 1290 if (!empty($thisTypeId)) {
5b28be84 1291 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
34917198
J
1292 }
1293 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
65a35632 1294
34917198 1295 } // End loop through 'other' locations of this type
087f00ec 1296
34917198 1297 } // End if 'other' location for this type exists
6a488035 1298
34917198 1299 } // End loop through each location block entity
6a488035
TO
1300
1301 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1302 $config = CRM_Core_Config::singleton();
1303 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1304 $mainUser = NULL;
1305 if ($mainUfId) {
1306 // d6 compatible
1307 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1308 $mainUser = user_load($mainUfId);
1309 }
1310 elseif ($config->userFramework == 'Joomla') {
1311 $mainUser = JFactory::getUser($mainUfId);
1312 }
1313 }
1314 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1315 $otherUser = NULL;
1316 if ($otherUfId) {
1317 // d6 compatible
1318 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1319 $otherUser = user_load($otherUfId);
1320 }
1321 elseif ($config->userFramework == 'Joomla') {
1322 $otherUser = JFactory::getUser($otherUfId);
1323 }
1324 }
1325
1326 $relTables = CRM_Dedupe_Merger::relTables();
1327 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1328 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1329 foreach ($relTables as $name => $null) {
1330 if (!in_array($name, $activeRelTables) &&
1331 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1332 ) {
1333 unset($relTables[$name]);
1334 continue;
1335 }
1336
1337 $relTableElements[] = array('checkbox', "move_$name");
1338 $migrationInfo["move_$name"] = 1;
1339
1340 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1341 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1342 if ($name == 'rel_table_users') {
1343 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1344 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1345 $find = array('$ufid', '$ufname');
1346 if ($mainUser) {
1347 $replace = array($mainUfId, $mainUser->name);
1348 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1349 }
1350 if ($otherUser) {
1351 $replace = array($otherUfId, $otherUser->name);
1352 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1353 }
1354 }
1355 if ($name == 'rel_table_memberships') {
1356 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1357 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1358 }
1359 }
1360 foreach ($relTables as $name => $null) {
1361 $relTables["move_$name"] = $relTables[$name];
1362 unset($relTables[$name]);
1363 }
1364
1365 // handle custom fields
201057c0 1366 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1,
1367 CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035
TO
1368 );
1369 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1,
201057c0 1370 CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035
TO
1371 );
1372 CRM_Core_DAO::freeResult();
1373
1374 foreach ($otherTree as $gid => $group) {
1375 $foundField = FALSE;
1376 if (!isset($group['fields'])) {
1377 continue;
1378 }
1379
1380 foreach ($group['fields'] as $fid => $field) {
4eea8606 1381 if (in_array($fid, $compareFields['custom'])) {
6a488035
TO
1382 if (!$foundField) {
1383 $rows["custom_group_$gid"]['title'] = $group['title'];
1384 $foundField = TRUE;
1385 }
a7488080 1386 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
6a488035 1387 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
51a3717f 1388 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1389 }
1390 }
1391 $value = "null";
a7488080 1392 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
6a488035 1393 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
51a3717f 1394 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1395 if ($values['data'] === 0 || $values['data'] === '0') {
1396 $values['data'] = $qfZeroBug;
d58a19a1 1397 }
6a488035 1398 $value = ($values['data']) ? $values['data'] : $value;
d58a19a1 1399 }
6a488035
TO
1400 }
1401 $rows["move_custom_$fid"]['title'] = $field['label'];
1402
1403 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1404 $migrationInfo["move_custom_$fid"] = $value;
1405 }
1406 }
1407 }
abb422f9 1408
6a488035
TO
1409 $result = array(
1410 'rows' => $rows,
1411 'elements' => $elements,
1412 'rel_table_elements' => $relTableElements,
6a488035
TO
1413 'rel_tables' => $relTables,
1414 'main_details' => $main,
1415 'other_details' => $other,
1416 'migration_info' => $migrationInfo,
1417 );
1418
34917198
J
1419 $result['main_details']['location_blocks'] = $locations['main'];
1420 $result['other_details']['location_blocks'] = $locations['other'];
6a488035
TO
1421
1422 return $result;
1423 }
1424
1425 /**
1426 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1427 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1428 * A superset of moveContactBelongings() function.
1429 *
98997235
TO
1430 * @param int $mainId
1431 * Main contact with whom merge has to happen.
1432 * @param int $otherId
1433 * Duplicate contact which would be deleted after merge operation.
77b97be7
EM
1434 *
1435 * @param $migrationInfo
6a488035 1436 *
3058f4d9 1437 * @param bool $checkPermissions
1438 * Respect logged in user permissions.
1439 *
77b97be7 1440 * @return bool
6a488035 1441 */
3058f4d9 1442 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
6a488035
TO
1443 if (empty($migrationInfo)) {
1444 return FALSE;
1445 }
1446
1447 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1448 $relTables = CRM_Dedupe_Merger::relTables();
92a77772 1449 $moveTables = $locationMigrationInfo = $tableOperations = array();
6a488035
TO
1450 foreach ($migrationInfo as $key => $value) {
1451 if ($value == $qfZeroBug) {
1452 $value = '0';
1453 }
7154d2a4 1454 if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) ||
353ffa53 1455 substr($key, 0, 12) == 'move_custom_') &&
7154d2a4
BS
1456 $value != NULL
1457 ) {
6a488035
TO
1458 $submitted[substr($key, 5)] = $value;
1459 }
34917198
J
1460
1461 // Set up initial information for handling migration of location blocks
6a488035 1462 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
92a77772 1463 $locationMigrationInfo[$key] = $value;
6a488035 1464 }
34917198 1465
6a488035
TO
1466 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1467 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1468 if (array_key_exists('operation', $migrationInfo)) {
1469 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1470 if (array_key_exists($key, $migrationInfo['operation'])) {
1471 $tableOperations[$table] = $migrationInfo['operation'][$key];
1472 }
1473 }
1474 }
1475 }
1476 }
92a77772 1477 self::mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo);
6a488035
TO
1478
1479 // **** Do tables related migrations
1480 if (!empty($moveTables)) {
1481 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1482 unset($moveTables, $tableOperations);
1483 }
1484
1485 // **** Do contact related migrations
1486 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
1487
1488 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1489 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1490 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1491 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
aa62b355 1492 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
6a488035
TO
1493 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1494 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1495 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1496 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1497
1498 // fix custom fields so they're edible by createProfileContact()
1499 static $treeCache = array();
1500 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1501 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'],
1502 CRM_Core_DAO::$_nullObject, NULL, -1
1503 );
1504 }
1505 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1506
1507 $cFields = array();
1508 foreach ($cgTree as $key => $group) {
1509 if (!isset($group['fields'])) {
1510 continue;
1511 }
1512 foreach ($group['fields'] as $fid => $field) {
1513 $cFields[$fid]['attributes'] = $field;
1514 }
1515 }
1516
1517 if (!isset($submitted)) {
1518 $submitted = array();
1519 }
1520 foreach ($submitted as $key => $value) {
1521 if (substr($key, 0, 7) == 'custom_') {
1522 $fid = (int) substr($key, 7);
0e357872
C
1523 if (empty($cFields[$fid])) {
1524 continue;
1525 }
6a488035
TO
1526 $htmlType = $cFields[$fid]['attributes']['html_type'];
1527 switch ($htmlType) {
1528 case 'File':
1529 $customFiles[] = $fid;
1530 unset($submitted["custom_$fid"]);
1531 break;
1532
1533 case 'Select Country':
1534 case 'Select State/Province':
8cee0c70 1535 $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
6a488035
TO
1536 break;
1537
69239109 1538 case 'Select Date':
1539 if ($cFields[$fid]['attributes']['is_view']) {
1540 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
1541 }
1542 break;
1543
6a488035
TO
1544 case 'CheckBox':
1545 case 'AdvMulti-Select':
1546 case 'Multi-Select':
1547 case 'Multi-Select Country':
1548 case 'Multi-Select State/Province':
1549 // Merge values from both contacts for multivalue fields, CRM-4385
1550 // get the existing custom values from db.
1551 $customParams = array('entityID' => $mainId, $key => TRUE);
1552 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
a7488080 1553 if (!empty($customfieldValues[$key])) {
6a488035
TO
1554 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1555 if (is_array($existingValue) && !empty($existingValue)) {
1556 $mergeValue = $submmtedCustomValue = array();
8a14f0f3 1557 if ($value == 'null') {
1558 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
1559 $submitted[$key] = $value;
6a488035 1560 }
8a14f0f3 1561 else {
1562 if ($value) {
1563 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1564 }
6a488035 1565
8a14f0f3 1566 //hack to remove null and duplicate values from array.
1567 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1568 if ($v != '' && !in_array($v, $mergeValue)) {
1569 $mergeValue[] = $v;
1570 }
6a488035 1571 }
6a488035 1572
8a14f0f3 1573 //keep state and country as array format.
1574 //for checkbox and m-select format w/ VALUE_SEPARATOR
1575 if (in_array($htmlType, array(
1576 'CheckBox',
1577 'Multi-Select',
1578 'AdvMulti-Select',
1579 ))) {
1580 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1581 $mergeValue
1582 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1583 }
1584 else {
1585 $submitted[$key] = $mergeValue;
1586 }
6a488035
TO
1587 }
1588 }
1589 }
1590 elseif (in_array($htmlType, array(
353ffa53 1591 'Multi-Select Country',
c301f76e 1592 'Multi-Select State/Province',
353ffa53 1593 ))) {
6a488035
TO
1594 //we require submitted values should be in array format
1595 if ($value) {
1596 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1597 //hack to remove null values from array.
1598 $mergeValue = array();
1599 foreach ($mergeValueArray as $k => $v) {
1600 if ($v != '') {
1601 $mergeValue[] = $v;
1602 }
1603 }
1604 $submitted[$key] = $mergeValue;
1605 }
1606 }
1607 break;
1608
1609 default:
1610 break;
1611 }
1612 }
1613 }
1614
1615 // **** Do file custom fields related migrations
1616 // FIXME: move this someplace else (one of the BAOs) after discussing
b3fdbf3d 1617 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
6a488035
TO
1618 // like, delete a file...
1619
1620 if (!isset($customFiles)) {
1621 $customFiles = array();
1622 }
1623 foreach ($customFiles as $customId) {
1624 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1625
1626 // get the contact_id -> file_id mapping
1627 $fileIds = array();
1628 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
9d2678f4 1629 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
1630 while ($dao->fetch()) {
1631 $fileIds[$dao->entity_id] = $dao->file_id;
1632 }
1633 $dao->free();
1634
1635 // delete the main contact's file
1636 if (!empty($fileIds[$mainId])) {
b3fdbf3d 1637 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
6a488035
TO
1638 }
1639
1640 // move the other contact's file to main contact
1641 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
481a74f4 1642 if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
d58a19a1 1643 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
6a488035
TO
1644 }
1645 else {
1646 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1647 }
9d2678f4 1648 CRM_Core_DAO::executeQuery($sql);
6a488035 1649
481a74f4 1650 if (CRM_Core_DAO::singleValueQuery("
6a488035
TO
1651 SELECT id
1652 FROM civicrm_entity_file
353ffa53
TO
1653 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1654 ) {
6a488035
TO
1655 $sql = "
1656 UPDATE civicrm_entity_file
1657 SET entity_id = {$mainId}
1658 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1659 }
1660 else {
1661 $sql = "
1662 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1663 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1664 }
9d2678f4 1665 CRM_Core_DAO::executeQuery($sql);
6a488035
TO
1666 }
1667
1668 // move view only custom fields CRM-5362
1669 $viewOnlyCustomFields = array();
1670 foreach ($submitted as $key => $value) {
1671 $fid = (int) substr($key, 7);
8cc574cf 1672 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
6a488035
TO
1673 $viewOnlyCustomFields[$key] = $value;
1674 }
1675 }
1676
1677 // special case to set values for view only, CRM-5362
1678 if (!empty($viewOnlyCustomFields)) {
1679 $viewOnlyCustomFields['entityID'] = $mainId;
1680 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1681 }
1682
3058f4d9 1683 if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') &&
1684 CRM_Core_Permission::check('delete contacts'))
6a488035
TO
1685 ) {
1686 // if ext id is submitted then set it null for contact to be deleted
a7488080 1687 if (!empty($submitted['external_identifier'])) {
6a488035
TO
1688 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1689 CRM_Core_DAO::executeQuery($query);
1690 }
5ea06a7b 1691 civicrm_api3('contact', 'delete', array('id' => $otherId));
6a488035 1692 }
6a488035 1693
4d5f18cc 1694 // CRM-15681 merge sub_types
35522279
J
1695 if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) {
1696 if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) {
481a74f4 1697 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
0db6c3e1
TO
1698 }
1699 else {
4d5f18cc 1700 $submitted['contact_sub_type'] = $other_sub_types;
1701 }
1702 }
1703
6a488035
TO
1704 // **** Update contact related info for the main contact
1705 if (!empty($submitted)) {
1706 $submitted['contact_id'] = $mainId;
1707
1708 //update current employer field
1709 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1710 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1711 $submitted['current_employer'] = $submitted['current_employer_id'];
0db6c3e1
TO
1712 }
1713 else {
6a488035
TO
1714 $submitted['current_employer'] = '';
1715 }
1716 unset($submitted['current_employer_id']);
1717 }
1718
00f3da2e 1719 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
481a74f4 1720 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
00f3da2e
BS
1721 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1722 }
481a74f4 1723 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
00f3da2e
BS
1724 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1725 }
1726
6a488035 1727 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
6a488035
TO
1728 }
1729
61bc2c0f 1730 CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
f00283b5 1731 self::createMergeActivities($mainId, $otherId);
5ea06a7b 1732
6a488035
TO
1733 return TRUE;
1734 }
16254ae1
ARW
1735
1736 /**
f00283b5 1737 * Get fields in the contact table suitable for merging.
1738 *
a6c01b45 1739 * @return array
f00283b5 1740 * Array of field names to be potentially merged.
16254ae1 1741 */
00be9182 1742 public static function getContactFields() {
16254ae1 1743 $contactFields = CRM_Contact_DAO_Contact::fields();
353ffa53
TO
1744 $invalidFields = array(
1745 'api_key',
353ffa53
TO
1746 'created_date',
1747 'display_name',
1748 'hash',
1749 'id',
1750 'modified_date',
1751 'primary_contact_id',
1752 'sort_name',
c301f76e 1753 'user_unique_id',
353ffa53 1754 );
bdd7870e
RN
1755 foreach ($contactFields as $field => $value) {
1756 if (in_array($field, $invalidFields)) {
1757 unset($contactFields[$field]);
1758 }
1759 }
16254ae1
ARW
1760 return array_keys($contactFields);
1761 }
ada104d5
AW
1762
1763 /**
1764 * Added for CRM-12695
c301f76e 1765 * Based on the contactID provided
ada104d5
AW
1766 * add/update membership(s) to related contacts
1767 *
c301f76e 1768 * @param int $contactID
ada104d5 1769 */
00be9182 1770 public static function addMembershipToRealtedContacts($contactID) {
ada104d5
AW
1771 $dao = new CRM_Member_DAO_Membership();
1772 $dao->contact_id = $contactID;
1773 $dao->is_test = 0;
1774 $dao->find();
1775
1776 //checks membership of contact itself
1777 while ($dao->fetch()) {
1778 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1779 if ($relationshipTypeId) {
1780 $membershipParams = array(
1781 'id' => $dao->id,
1782 'contact_id' => $dao->contact_id,
1783 'membership_type_id' => $dao->membership_type_id,
1784 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1785 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1786 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1787 'source' => $dao->source,
21dfd5f5 1788 'status_id' => $dao->status_id,
ada104d5
AW
1789 );
1790 // create/update membership(s) for related contact(s)
1791 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1792 } // end of if relationshipTypeId
1793 }
1794 }
96025800 1795
3ae0ae3d 1796 /**
1797 * Add custom tables that extend contacts to the list of contact references.
1798 *
1799 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
1800 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
1801 * - the down side is it is not cached.
1802 *
1803 * Further changes should be include tests in the CRM_Core_MergerTest class
1804 * to ensure that disabled, subtype, multiple etc groups are still captured.
1805 *
1806 * @param array $cidRefs
1807 */
1808 public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
1809 $customValueTables = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
1810 $customValueTables->find();
1811 while ($customValueTables->fetch()) {
1812 $cidRefs[$customValueTables->table_name] = array('entity_id');
1813 }
1814 }
1815
f00283b5 1816 /**
1817 * Create activities tracking the merge on affected contacts.
1818 *
1819 * @param int $mainId
1820 * @param int $otherId
1821 *
1822 * @throws \CiviCRM_API3_Exception
1823 */
1824 public static function createMergeActivities($mainId, $otherId) {
1825 $params = array(
1826 1 => $otherId,
1827 2 => $mainId,
1828 );
1829 $activity = civicrm_api3('activity', 'create', array(
dc33398e
J
1830 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1831 $mainId,
f00283b5 1832 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1833 'target_contact_id' => $mainId,
1834 'activity_type_id' => 'Contact Merged',
1835 'status_id' => 'Completed',
1836 ));
4d834a99 1837 if (civicrm_api3('Setting', 'getvalue', array('name' => 'contact_undelete', 'group' => 'CiviCRM Preferences'))) {
1838 civicrm_api3('activity', 'create', array(
dc33398e
J
1839 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1840 $otherId,
4d834a99 1841 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1842 'target_contact_id' => $otherId,
1843 'activity_type_id' => 'Contact Deleted by Merge',
1844 'parent_id' => $activity['id'],
1845 'status_id' => 'Completed',
1846 ));
1847 }
f00283b5 1848 }
1849
2988f5c7 1850 /**
1851 * Get Duplicate Pairs based on a rule for a group.
1852 *
1853 * @param int $rule_group_id
1854 * @param int $group_id
1855 * @param bool $reloadCacheIfEmpty
1856 * @param int $batchLimit
1857 * @param bool $isSelected
3058f4d9 1858 * @param array|string $orderByClause
66eceb0b 1859 * @param bool $includeConflicts
e23e26ec 1860 * @param array $criteria
1861 * Additional criteria to narrow down the merge group.
2988f5c7 1862 *
3058f4d9 1863 * @param bool $checkPermissions
1864 * Respect logged in user permissions.
1865 *
2988f5c7 1866 * @return array
3058f4d9 1867 * Array of matches meeting the criteria.
2988f5c7 1868 */
3058f4d9 1869 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $orderByClause = '', $includeConflicts = TRUE, $criteria = array(), $checkPermissions = TRUE) {
2988f5c7 1870 $where = self::getWhereString($batchLimit, $isSelected);
3058f4d9 1871 $cacheKeyString = self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions);
2988f5c7 1872 $join = self::getJoinOnDedupeTable();
66eceb0b 1873 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
2988f5c7 1874 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1875 // If we haven't found any dupes, probably cache is empty.
66eceb0b 1876 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1877 // until we have done some processing.
3058f4d9 1878 CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions);
66eceb0b 1879 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
2988f5c7 1880 return $dupePairs;
1881 }
1882 return $dupePairs;
1883 }
1884
2ae26001 1885 /**
1886 * Get the cache key string for the merge action.
1887 *
1888 * @param int $rule_group_id
1889 * @param int $group_id
e23e26ec 1890 * @param array $criteria
1891 * Additional criteria to narrow down the merge group.
1892 * Currently we are only supporting the key 'contact' within it.
2ae26001 1893 *
3058f4d9 1894 * @param bool $checkPermissions
1895 * Respect the users permissions.
1896 *
2ae26001 1897 * @return string
1898 */
3058f4d9 1899 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = array(), $checkPermissions = TRUE) {
2ae26001 1900 $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
1901 $cacheKeyString = "merge {$contactType}";
1902 $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
1903 $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
e23e26ec 1904 $cacheKeyString .= !empty($criteria) ? serialize($criteria) : '_0';
3058f4d9 1905 if ($checkPermissions) {
1906 $contactID = CRM_Core_Session::getLoggedInContactID();
1907 if (!$contactID) {
1908 // Distinguish between no permission check & no logged in user.
1909 $contactID = 'null';
1910 }
1911 $cacheKeyString .= '_' . $contactID;
1912 }
1913 else {
1914 $cacheKeyString .= '_0';
1915 }
2ae26001 1916 return $cacheKeyString;
1917 }
1918
1996e7d4 1919 /**
5d5b49ad 1920 * @param array $contact
1996e7d4 1921 * @return array
1922 * $specialValues
1923 */
1924 public static function getSpecialValues($contact) {
35522279 1925 $preferred_communication_method = CRM_Utils_Array::value('preferred_communication_method', $contact);
1996e7d4 1926 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
1927 $specialValues = array(
1928 'preferred_communication_method' => $value,
1929 'communication_style_id' => $value,
1930 );
1931
1932 if (!empty($contact['preferred_communication_method'])) {
1933 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
1934 $prefCommList = is_array($specialValues['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues['preferred_communication_method']) : $specialValues['preferred_communication_method'];
1935 $specialValues['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
1936 }
1937 $names = array(
1938 'preferred_communication_method' => array(
1939 'newName' => 'preferred_communication_method_display',
1940 'groupName' => 'preferred_communication_method',
1941 ),
1942 );
1943 CRM_Core_OptionGroup::lookupValues($specialValues, $names);
1944
1945 if (!empty($contact['communication_style'])) {
1946 $specialValues['communication_style_id_display'] = $contact['communication_style'];
1947 }
1948 return $specialValues;
1949 }
1950
74a6069d 1951 /**
1952 * Get the metadata for the merge fields.
1953 *
1954 * This is basically the contact metadata, augmented with fields to
1955 * represent email greeting, postal greeting & addressee.
1956 *
1957 * @return array
1958 */
1959 public static function getMergeFieldsMetadata() {
1960 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) {
1961 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1962 }
1963 $fields = CRM_Contact_DAO_Contact::fields();
1964 static $optionValueFields = array();
1965 if (empty($optionValueFields)) {
1966 $optionValueFields = CRM_Core_OptionValue::getFields();
1967 }
1968 foreach ($optionValueFields as $field => $params) {
1969 $fields[$field]['title'] = $params['title'];
1970 }
1971 \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields;
1972 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1973 }
1974
1975 /**
1976 * Get the details of the contact to be merged.
1977 *
1978 * @param int $contact_id
1979 * @param string $moniker
1980 *
1981 * @return array
1982 *
1983 * @throws CRM_Core_Exception
1984 */
1985 public static function getMergeContactDetails($contact_id, $moniker) {
1986 $params = array(
1987 'contact_id' => $contact_id,
1988 'version' => 3,
1989 'return' => array_merge(array('display_name'), self::getContactFields()),
1990 );
1991 $result = civicrm_api('contact', 'get', $params);
1992
1993 // CRM-18480: Cancel the process if the contact is already deleted
1994 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
1995 throw new CRM_Core_Exception(ts('Cannot merge because the \'%1\' contact (ID %2) has been deleted.', array(
1996 1 => $moniker,
1997 2 => $contact_id,
1998 )));
1999 }
2000
2001 return $result['values'][$contact_id];
2002 }
2003
92a77772 2004 /**
2005 * Merge location.
2006 *
2007 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
2008 *
2009 * The data is in the format received from the merge form (which is a fairly confusing format).
2010 *
2011 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
2012 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
2013 * been calculated and before saving because
2014 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
2015 * - passing to a hook right before save means calculations only have to be done once
2016 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
2017 * ugly.
2018 *
2019 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
16d4e0b7 2020 * is likely to be significant data in merge hooks.
92a77772 2021 *
2022 * @param int $mainId
2023 * @param int $otherId
2024 * @param array $locationMigrationInfo
2025 * Portion of the migration_info that holds location migration information.
2026 *
2027 * @param array $migrationInfo
2028 * Migration info for the merge. This is passed to the hook as informational only.
2029 */
2030 public static function mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo) {
2031 foreach ($locationMigrationInfo as $key => $value) {
2032 $locField = explode('_', $key);
2033 $fieldName = $locField[2];
2034 $fieldCount = $locField[3];
2035
2036 // Set up the operation type (add/overwrite)
2037 // Ignore operation for websites
2038 // @todo Tidy this up
2039 $operation = 0;
2040 if ($fieldName != 'website') {
2041 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
2042 }
2043 // default operation is overwrite.
2044 if (!$operation) {
2045 $operation = 2;
2046 }
2047 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
2048 }
2049 $blocksDAO = array();
2050
2051 // @todo Handle OpenID (not currently in API).
2052 if (!empty($locBlocks)) {
2053 $locationBlocks = self::getLocationBlockInfo();
2054
2055 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
2056 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
2057
2058 foreach ($locBlocks as $name => $block) {
2059 $blocksDAO[$name] = array('delete' => array(), 'update' => array());
2060 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
2061 continue;
2062 }
2063 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
abd0b852 2064 $changePrimary = FALSE;
92a77772 2065 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
2066 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
2067
2068 foreach ($block as $blkCount => $values) {
2069 $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
2070 $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
2071 if (!$otherBlockId) {
2072 continue;
2073 }
2074
2075 // For the block which belongs to other-contact, link the location block to main-contact
2076 $otherBlockDAO = new $daoName();
2077 $otherBlockDAO->contact_id = $mainId;
2078
2079 // Get the ID of this block on the 'other' contact, otherwise skip
2080 $otherBlockDAO->id = $otherBlockId;
2081
2082 // Add/update location and type information from the form, if applicable
2083 if ($locationBlocks[$name]['hasLocation']) {
2084 $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2085 $otherBlockDAO->location_type_id = $locTypeId;
2086 }
2087 if ($locationBlocks[$name]['hasType']) {
2088 $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2089 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
2090 }
2091
abd0b852
J
2092 // If we're deliberately setting this as primary then add the flag
2093 // and remove it from the current primary location (if there is one).
2094 // But only once for each entity.
2095 $set_primary = CRM_Utils_Array::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
9e848fc4 2096 if (!$changePrimary && $set_primary == "1") {
abd0b852
J
2097 $otherBlockDAO->is_primary = 1;
2098 if ($primaryDAOId) {
2099 $removePrimaryDAO = new $daoName();
2100 $removePrimaryDAO->id = $primaryDAOId;
2101 $removePrimaryDAO->is_primary = 0;
2102 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
2103 }
2104 $changePrimary = TRUE;
2105 }
2106 // Otherwise, if main contact already has primary, set it to 0.
2107 elseif ($primaryDAOId) {
92a77772 2108 $otherBlockDAO->is_primary = 0;
2109 }
abd0b852
J
2110
2111 // If the main contact already has a billing location, set this to 0.
92a77772 2112 if ($billingDAOId) {
2113 $otherBlockDAO->is_billing = 0;
2114 }
2115
2116 $operation = CRM_Utils_Array::value('operation', $values, 2);
2117 // overwrite - need to delete block which belongs to main-contact.
2118 if (!empty($mainBlockId) && ($operation == 2)) {
2119 $deleteDAO = new $daoName();
2120 $deleteDAO->id = $mainBlockId;
2121 $deleteDAO->find(TRUE);
2122
2123 // if we about to delete a primary / billing block, set the flags for new block
2124 // that we going to assign to main-contact
2125 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
2126 $otherBlockDAO->is_primary = 1;
2127 }
2128 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
2129 $otherBlockDAO->is_billing = 1;
2130 }
2131 $blocksDAO[$name]['delete'][$deleteDAO->id] = $deleteDAO;
2132 }
2133 $blocksDAO[$name]['update'][$otherBlockDAO->id] = $otherBlockDAO;
2134 }
2135 }
2136 }
2137
2138 CRM_Utils_Hook::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2139 foreach ($blocksDAO as $blockDAOs) {
2140 if (!empty($blockDAOs['update'])) {
2141 foreach ($blockDAOs['update'] as $blockDAO) {
2142 $blockDAO->save();
2143 }
2144 }
2145 if (!empty($blockDAOs['delete'])) {
2146 foreach ($blockDAOs['delete'] as $blockDAO) {
2147 $blockDAO->delete();
2148 }
2149 }
2150 }
2151 }
2152
e4e1db4b 2153 /**
2154 * Dedupe a pair of contacts.
2155 *
2156 * @param array $migrationInfo
2157 * @param array $resultStats
2158 * @param array $deletedContacts
2159 * @param string $mode
2160 * @param bool $checkPermissions
2161 * @param int $mainId
2162 * @param int $otherId
2163 * @param string $cacheKeyString
2164 */
2165 protected static function dedupePair(&$migrationInfo, &$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) {
2166
2167 // go ahead with merge if there is no conflict
2168 $conflicts = array();
2169 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2170 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2171 $resultStats['merged'][] = array(
2172 'main_id' => $mainId,
2173 'other_id' => $otherId,
2174 );
2175 $deletedContacts[] = $otherId;
2176 }
2177 else {
2178 $resultStats['skipped'][] = array(
2179 'main_id' => $mainId,
2180 'other_id' => $otherId,
2181 );
2182 }
2183
2184 // store any conflicts
2185 if (!empty($conflicts)) {
2186 foreach ($conflicts as $key => $dnc) {
2187 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
2188 }
2189 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
2190 }
2191 else {
2192 // delete entry from PrevNextCache table so we don't consider the pair next time
2193 // pair may have been flipped, so make sure we delete using both orders
2194 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
2195 }
2196
2197 CRM_Core_DAO::freeResult();
2198 }
2199
6a488035 2200}