CRM-21349 - Improve batch merge status message
[civicrm-core.git] / CRM / Dedupe / Merger.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
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
b35800bd 440 * @param array $customTableToCopyFrom
6a488035 441 */
9af46cc4 442 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array(), $customTableToCopyFrom = NULL) {
6a488035
TO
443 $cidRefs = self::cidRefs();
444 $eidRefs = self::eidRefs();
445 $cpTables = self::cpTables();
446 $paymentTables = self::paymentTables();
447
b35800bd 448 // getting all custom tables
674920ca 449 $customTables = array();
ae2346d4 450 if ($customTableToCopyFrom !== NULL) {
674920ca
ES
451 self::addCustomTablesExtendingContactsToCidRefs($customTables);
452 $customTables = array_keys($customTables);
6a488035 453 }
674920ca
ES
454
455 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
0556db5d
CR
456
457 // if there aren't any specific tables, don't affect the ones handled by relTables()
458 // also don't affect tables in locTables() CRM-15658
459 $relTables = self::relTables();
460 $handled = self::locTables();
461
462 foreach ($relTables as $params) {
463 $handled = array_merge($handled, $params['tables']);
6a488035 464 }
0556db5d 465 $affected = array_diff($affected, $handled);
e3159b07 466 $affected = array_unique(array_merge($affected, $tables));
6a488035
TO
467
468 $mainId = (int) $mainId;
469 $otherId = (int) $otherId;
470
471 $sqls = array();
472 foreach ($affected as $table) {
674920ca 473 // skipping non selected custom table's value migration
ae2346d4 474 if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
b35800bd
ES
475 continue;
476 }
674920ca 477
6a488035
TO
478 // Call custom processing function for objects that require it
479 if (isset($cpTables[$table])) {
480 foreach ($cpTables[$table] as $className => $fnName) {
481 $className::$fnName($mainId, $otherId, $sqls);
482 }
483 // Skip normal processing
484 continue;
485 }
b3fdbf3d 486
6a488035
TO
487 // use UPDATE IGNORE + DELETE query pair to skip on situations when
488 // there's a UNIQUE restriction on ($field, some_other_field) pair
489 if (isset($cidRefs[$table])) {
490 foreach ($cidRefs[$table] as $field) {
491 // carry related contributions CRM-5359
492 if (in_array($table, $paymentTables)) {
6a488035
TO
493 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
494 $sqls = array_merge($sqls, $paymentSqls);
71560cf3
C
495
496 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
497 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
498 $sqls = array_merge($sqls, $payOprSqls);
499 }
6a488035
TO
500 }
501
502 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
503 $sqls = array_merge($sqls, $preOperationSqls);
504
ae2346d4
CR
505 if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self::customRecordExists($mainId, $table, $field)) {
506 $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
507 }
6a488035
TO
508 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
509 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
510 }
511 }
ae2346d4 512
6a488035
TO
513 if (isset($eidRefs[$table])) {
514 foreach ($eidRefs[$table] as $entityTable => $entityId) {
515 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
516 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
517 }
518 }
519 }
520
521 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
522 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
523
524 // call the SQL queries in one transaction
525 $transaction = new CRM_Core_Transaction();
526 foreach ($sqls as $sql) {
527 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE);
528 }
0556db5d 529 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
6a488035
TO
530 $transaction->commit();
531 }
532
4f751978
CR
533 /**
534 * Given a contact ID, will check if a record exists in given table.
535 *
536 * @param $contactID
537 * @param $table
538 * @param $idField
539 * Field where the contact's ID is stored in the table
540 *
541 * @return bool
542 * True if a record is found for the given contact ID, false otherwise
543 */
ae2346d4
CR
544 private static function customRecordExists($contactID, $table, $idField) {
545 $sql = "
546 SELECT COUNT(*) AS count
547 FROM $table
548 WHERE $idField = $contactID
549 ";
550 $dbResult = CRM_Core_DAO::executeQuery($sql);
551 $dbResult->fetch();
552
553 if ($dbResult->count > 0) {
ee3b1d86 554 return TRUE;
ae2346d4
CR
555 }
556
ee3b1d86 557 return FALSE;
ae2346d4
CR
558 }
559
6a488035 560 /**
4eea8606 561 * Load all non-empty fields for the contacts
b3fdbf3d 562 *
98997235
TO
563 * @param array $main
564 * Contact details.
565 * @param array $other
566 * Contact details.
6a488035 567 *
77b97be7 568 * @return array
6a488035 569 */
4eea8606 570 public static function retrieveFields($main, $other) {
6a488035
TO
571 $result = array(
572 'contact' => array(),
573 'custom' => array(),
574 );
16254ae1 575 foreach (self::getContactFields() as $validField) {
eb61dc07
J
576 // CRM-17556 Get all non-empty fields, to make comparison easier
577 if (!empty($main[$validField]) || !empty($other[$validField])) {
6a488035
TO
578 $result['contact'][] = $validField;
579 }
580 }
581
582 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
583 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
584 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
585 foreach ($keys as $key) {
76c53278
CW
586 // Exclude multi-value fields CRM-13836
587 if (strpos($key, '_')) {
588 continue;
589 }
6a488035
TO
590 $key1 = CRM_Utils_Array::value($key, $mainEvs);
591 $key2 = CRM_Utils_Array::value($key, $otherEvs);
eb61dc07 592 // CRM-17556 Get all non-empty fields, to make comparison easier
08ef1f91 593 if (!empty($key1) || !empty($key2)) {
6a488035
TO
594 $result['custom'][] = $key;
595 }
596 }
597 return $result;
598 }
599
600 /**
100fef9d 601 * Batch merge a set of contacts based on rule-group and group.
6a488035 602 *
98997235
TO
603 * @param int $rgid
604 * Rule group id.
605 * @param int $gid
606 * Group id.
607 * @param string $mode
608 * Helps decide how to behave when there are conflicts.
15a793bb
EM
609 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
610 * mode does a force merge.
f931b74c 611 * @param int $batchLimit number of merges to carry out in one batch.
612 * @param int $isSelected if records with is_selected column needs to be processed.
6a488035 613 *
e23e26ec 614 * @param array $criteria
615 * Criteria to use in the filter.
616 *
3058f4d9 617 * @param bool $checkPermissions
618 * Respect logged in user permissions.
619 *
77b97be7 620 * @return array|bool
6a488035 621 */
d13a105a 622 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = array(), $checkPermissions = TRUE) {
63ef778e 623 $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
2988f5c7 624 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
3058f4d9 625 $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, '', ($mode == 'aggressive'), $criteria, $checkPermissions);
6a488035
TO
626
627 $cacheParams = array(
3058f4d9 628 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
2988f5c7 629 // @todo stop passing these parameters in & instead calculate them in the merge function based
630 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
631 'join' => self::getJoinOnDedupeTable(),
632 'where' => self::getWhereString($batchLimit, $isSelected),
6a488035 633 );
d238756a 634 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
6a488035
TO
635 }
636
2ae26001 637 /**
638 * Get the string to join the prevnext cache to the dedupe table.
639 *
640 * @return string
641 * The join string to join prevnext cache on the dedupe table.
642 */
643 public static function getJoinOnDedupeTable() {
644 return "
645 LEFT JOIN civicrm_dedupe_exception de
646 ON (
647 pn.entity_id1 = de.contact_id1
648 AND pn.entity_id2 = de.contact_id2 )
649 ";
650 }
651
2988f5c7 652 /**
653 * Get where string for dedupe join.
654 *
655 * @param int $batchLimit
656 * @param bool $isSelected
657 *
658 * @return string
659 */
660 protected static function getWhereString($batchLimit, $isSelected) {
661 $where = "de.id IS NULL";
662 if ($isSelected === 0 || $isSelected === 1) {
663 $where .= " AND pn.is_selected = {$isSelected}";
664 }
665 // else consider all dupe pairs
666 // @todo Adding limit to Where??!!
5721d85e 667 if ($batchLimit) {
668 $where .= " LIMIT {$batchLimit}";
669 }
2988f5c7 670 return $where;
671 }
672
bc854509 673 /**
674 * Update the statistics for the merge set.
675 *
676 * @param string $cacheKeyString
677 * @param array $result
678 */
f931b74c 679 public static function updateMergeStats($cacheKeyString, $result = array()) {
63ef778e 680 // gather latest stats
681 $merged = count($result['merged']);
682 $skipped = count($result['skipped']);
683
684 if ($merged <= 0 && $skipped <= 0) {
685 return;
686 }
687
688 // get previous stats
689 $previousStats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
690 if (!empty($previousStats)) {
691 if ($previousStats[0]['merged']) {
692 $merged = $merged + $previousStats[0]['merged'];
693 }
694 if ($previousStats[0]['skipped']) {
695 $skipped = $skipped + $previousStats[0]['skipped'];
696 }
697 }
698
699 // delete old stats
700 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
701
702 // store the updated stats
703 $data = array(
704 'merged' => $merged,
705 'skipped' => $skipped,
706 );
707 $data = CRM_Core_DAO::escapeString(serialize($data));
708
709 $values = array();
710 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
711 CRM_Core_BAO_PrevNextCache::setItem($values);
712 }
713
ae6455b2 714 /**
715 * Delete information about merges for the given string.
716 *
717 * @param $cacheKeyString
718 */
f931b74c 719 public static function resetMergeStats($cacheKeyString) {
ae6455b2 720 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
63ef778e 721 }
722
bc854509 723 /**
724 * Get merge outcome statistics.
725 *
726 * @param string $cacheKeyString
727 *
728 * @return array
729 * Array of how many were merged and how many were skipped.
730 */
f931b74c 731 public static function getMergeStats($cacheKeyString) {
63ef778e 732 $stats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
733 if (!empty($stats)) {
734 $stats = $stats[0];
735 }
736 return $stats;
737 }
738
bc854509 739 /**
740 * Get merge statistics message.
741 *
3743fd3d 742 * @param array $stats
bc854509 743 *
744 * @return string
745 */
3743fd3d
CW
746 public static function getMergeStatsMsg($stats) {
747 $msg = '';
63ef778e 748 if (!empty($stats['merged'])) {
3743fd3d 749 $msg = '<p>' . ts('One contact merged.', array(1 => $stats['merged'], 'plural' => '%1 contacts merged.')) . '</p>';
63ef778e 750 }
751 if (!empty($stats['skipped'])) {
3743fd3d 752 $msg .= '<p>' . ts('One contact was skipped.', array(1 => $stats['skipped'], 'plural' => '%1 contacts were skipped.')) . '</p>';
63ef778e 753 }
754 return $msg;
755 }
756
6a488035 757 /**
100fef9d 758 * Merge given set of contacts. Performs core operation.
6a488035 759 *
98997235
TO
760 * @param array $dupePairs
761 * Set of pair of contacts for whom merge is to be done.
762 * @param array $cacheParams
763 * Prev-next-cache params based on which next pair of contacts are computed.
6a488035 764 * Generally used with batch-merge.
98997235
TO
765 * @param string $mode
766 * Helps decide how to behave when there are conflicts.
6a488035
TO
767 * A 'safe' value skips the merge if there are any un-resolved conflicts.
768 * Does a force merge otherwise (aggressive mode).
6a488035 769 *
77b97be7 770 * @param bool $redirectForPerformance
3058f4d9 771 * Redirect to a url for batch processing.
772 *
773 * @param bool $checkPermissions
774 * Respect logged in user permissions.
77b97be7
EM
775 *
776 * @return array|bool
6a488035 777 */
00be9182 778 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
d238756a 779 $redirectForPerformance = FALSE, $checkPermissions = TRUE
6a488035
TO
780 ) {
781 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
782 $resultStats = array('merged' => array(), 'skipped' => array());
783
784 // we don't want dupe caching to get reset after every-merge, and therefore set the
0626851e 785 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
78272750 786 $deletedContacts = array();
6a488035
TO
787
788 while (!empty($dupePairs)) {
78272750 789 foreach ($dupePairs as $index => $dupes) {
790 if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) {
791 unset($dupePairs[$index]);
792 continue;
793 }
1cf05c3e 794 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
6a488035
TO
795 $mainId = $dupes['dstID'];
796 $otherId = $dupes['srcID'];
e67dcaf8 797
6a488035
TO
798 if (!$mainId || !$otherId) {
799 // return error
800 return FALSE;
801 }
6a488035
TO
802 // Generate var $migrationInfo. The variable structure is exactly same as
803 // $formValues submitted during a UI merge for a pair of contacts.
201057c0 804 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions);
6a488035 805 // add additional details that we might need to resolve conflicts
e4e1db4b 806 $rowsElementsAndInfo['migration_info']['main_details'] = &$rowsElementsAndInfo['main_details'];
807 $rowsElementsAndInfo['migration_info']['other_details'] = &$rowsElementsAndInfo['other_details'];
808 $rowsElementsAndInfo['migration_info']['rows'] = &$rowsElementsAndInfo['rows'];
6a488035 809
e4e1db4b 810 self::dedupePair($rowsElementsAndInfo['migration_info'], $resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString);
6a488035
TO
811 }
812
813 if ($cacheKeyString && !$redirectForPerformance) {
814 // retrieve next pair of dupes
2988f5c7 815 // @todo call getDuplicatePairs.
6a488035
TO
816 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
817 $cacheParams['join'],
66eceb0b 818 $cacheParams['where'],
819 0,
820 0,
821 array(),
822 '',
823 FALSE
6a488035
TO
824 );
825 }
826 else {
827 // do not proceed. Terminate the loop
828 unset($dupePairs);
829 }
830 }
63ef778e 831
832 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
6a488035
TO
833 return $resultStats;
834 }
835
836 /**
837 * A function which uses various rules / algorithms for choosing which contact to bias to
838 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
839 *
98997235
TO
840 * @param int $mainId
841 * Main contact with whom merge has to happen.
842 * @param int $otherId
843 * Duplicate contact which would be deleted after merge operation.
844 * @param array $migrationInfo
845 * Array of information about which elements to merge.
846 * @param string $mode
847 * Helps decide how to behave when there are conflicts.
13919cf8
J
848 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
849 * - Does a force merge otherwise (aggressive mode).
6a488035 850 *
ad37ac8e 851 * @param array $conflicts
852 *
77b97be7 853 * @return bool
6a488035 854 */
63ef778e 855 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
0971143c 856
c08fae40 857 $originalMigrationInfo = $migrationInfo;
6a488035
TO
858 foreach ($migrationInfo as $key => $val) {
859 if ($val === "null") {
0971143c 860 // Rule: Never overwrite with an empty value (in any mode)
6a488035
TO
861 unset($migrationInfo[$key]);
862 continue;
863 }
16254ae1 864 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
6a488035 865 substr($key, 0, 12) == 'move_custom_'
353ffa53
TO
866 ) and $val != NULL
867 ) {
0971143c
J
868 // Rule: If both main-contact, and other-contact have a field with a
869 // different value, then let $mode decide if to merge it or not
4eea8606 870 if (
e2cecb9c 871 (!empty($migrationInfo['rows'][$key]['main'])
872 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
873 // is probably true for other fields too - e.g. 'do_not_email' but
874 // leaving that investigation as a @todo - until tests can be written.
875 // Note the handling of this has test coverage - although the data-typing
876 // of '0' feels flakey we have insurance.
877 || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
878 )
4eea8606
J
879 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
880 ) {
fd630ef9 881
882 // note it down & lets wait for response from the hook.
883 // For no response $mode will decide if to skip this merge
884 $conflicts[$key] = NULL;
6a488035
TO
885 }
886 }
887 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
888 $locField = explode('_', $key);
889 $fieldName = $locField[2];
890 $fieldCount = $locField[3];
891
4ece0d26 892 // Rule: Catch address conflicts (same address type on both contacts)
13cc4cac 893 if (
894 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
895 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
896 ) {
897
898 // Load the address we're inspecting from the 'other' contact
899 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
900 $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord);
b982316c 901
13cc4cac 902 // If it exists on the 'main' contact already, skip it. Otherwise
903 // if the location type exists already, log a conflict.
904 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
5d5b49ad 905 if (self::locationIsSame($addressRecord, $mainAddressRecord)) {
13cc4cac 906 unset($migrationInfo[$key]);
907 break;
908 }
909 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
910 $conflicts[$key] = NULL;
911 break;
912 }
6a488035
TO
913 }
914 }
13cc4cac 915
4ece0d26 916 // For other locations, don't merge/add if the values are the same
13cc4cac 917 elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
6a488035
TO
918 unset($migrationInfo[$key]);
919 }
920 }
921 }
922
923 // A hook to implement other algorithms for choosing which contact to bias to when
924 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
925 // merge happens with new values filled in here. For a particular field / row not to be merged
926 // field should be unset from fields_in_conflict.
c08fae40 927 $migrationData = array(
928 'old_migration_info' => $originalMigrationInfo,
929 'mode' => $mode,
930 'fields_in_conflict' => $conflicts,
931 'merge_mode' => $mode,
932 'migration_info' => $migrationInfo,
933 );
6a488035
TO
934 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
935 $conflicts = $migrationData['fields_in_conflict'];
63ef778e 936 // allow hook to override / manipulate migrationInfo as well
c08fae40 937 $migrationInfo = $migrationData['migration_info'];
6a488035
TO
938
939 if (!empty($conflicts)) {
940 foreach ($conflicts as $key => $val) {
941 if ($val === NULL and $mode == 'safe') {
63ef778e 942 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
6a488035
TO
943 return TRUE;
944 }
945 else {
946 // copy over the resolved values
947 $migrationInfo[$key] = $val;
948 }
949 }
fd630ef9 950 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
951 if (array_key_exists('skip_merge', $migrationData)) {
952 return (bool) $migrationData['skip_merge'];
953 }
6a488035
TO
954 }
955 return FALSE;
956 }
957
d48ad2c0 958 /**
959 * Compare 2 addresses to see if they are the same.
960 *
961 * @param array $mainAddress
962 * @param array $comparisonAddress
963 *
964 * @return bool
965 */
5d5b49ad 966 static public function locationIsSame($mainAddress, $comparisonAddress) {
00443529 967 $keysToIgnore = array('id', 'is_primary', 'is_billing', 'manual_geo_code', 'contact_id', 'reset_date', 'hold_date');
d48ad2c0 968 foreach ($comparisonAddress as $field => $value) {
969 if (in_array($field, $keysToIgnore)) {
970 continue;
971 }
00443529 972 if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
d48ad2c0 973 return FALSE;
974 }
975 }
976 return TRUE;
977 }
978
34917198
J
979 /**
980 * A function to build an array of information about location blocks that is
981 * required when merging location fields
982 *
983 * @return array
984 */
985 public static function getLocationBlockInfo() {
986 $locationBlocks = array(
987 'address' => array(
988 'label' => 'Address',
989 'displayField' => 'display',
990 'sortString' => 'location_type_id',
991 'hasLocation' => TRUE,
992 'hasType' => FALSE,
993 ),
994 'email' => array(
995 'label' => 'Email',
996 'displayField' => 'email',
997 'sortString' => 'location_type_id',
998 'hasLocation' => TRUE,
999 'hasType' => FALSE,
1000 ),
1001 'im' => array(
1002 'label' => 'IM',
1003 'displayField' => 'name',
1004 'sortString' => 'location_type_id,provider_id',
1005 'hasLocation' => TRUE,
1006 'hasType' => 'provider_id',
1007 ),
1008 'phone' => array(
1009 'label' => 'Phone',
1010 'displayField' => 'phone',
1011 'sortString' => 'location_type_id,phone_type_id',
1012 'hasLocation' => TRUE,
1013 'hasType' => 'phone_type_id',
1014 ),
1015 'website' => array(
1016 'label' => 'Website',
1017 'displayField' => 'url',
1018 'sortString' => 'website_type_id',
1019 'hasLocation' => FALSE,
1020 'hasType' => 'website_type_id',
1021 ),
1022 );
1023 return $locationBlocks;
1024 }
1025
6a488035
TO
1026 /**
1027 * A function to build an array of information required by merge function and the merge UI.
1028 *
98997235
TO
1029 * @param int $mainId
1030 * Main contact with whom merge has to happen.
1031 * @param int $otherId
1032 * Duplicate contact which would be deleted after merge operation.
201057c0 1033 * @param bool $checkPermissions
1034 * Should the logged in user's permissions be ignore. Setting this to false is
1035 * highly risky as it could cause data to be lost due to conflicts not showing up.
1036 * OTOH there is a risk a merger might view custom data they do not have permission to.
1037 * Hence for now only making this really explicit and making it reflect perms in
1038 * an api call.
1039 *
1040 * @todo review permissions issue!
6a488035 1041 *
77b97be7 1042 * @return array|bool|int
1e3e0eed
J
1043 *
1044 * rows => An array of arrays, each is row of merge information for the table
1045 * Format: move_fieldname, eg: move_contact_type
1046 * main => Value associated with the main contact
1047 * other => Value associated with the other contact
1048 * title => The title of the field to display in the merge table
1049 *
1050 * elements => An array of form elements for the merge UI
1051 *
1052 * rel_table_elements => An array of form elements for the merge UI for
1053 * entities related to the contact (eg: checkbox to move 'mailings')
1054 *
1e3e0eed
J
1055 * rel_tables => Stores the tables that have related entities for the contact
1056 * for example mailings, groups
1057 *
1058 * main_details => An array of core contact field values, eg: first_name, etc.
1059 * location_blocks => An array of location block data for the main contact
1060 * stored as the 'result' of an API call.
1061 * eg: main_details['location_blocks']['address'][0]['id']
1062 * eg: main_details['location_blocks']['email'][1]['id']
1063 *
1064 * other_details => As above, but for the 'other' contact
1065 *
1066 * migration_info => Stores the 'default' merge actions for each field which
1067 * is used when programatically merging contacts. It contains instructions
1068 * to move all fields from the 'other' contact to the 'main' contact, as
1069 * though the form had been submitted with those options.
1070 *
3058f4d9 1071 * @throws \CRM_Core_Exception
1072 * @throws \CiviCRM_API3_Exception
1073 * @throws \Exception
6a488035 1074 */
201057c0 1075 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
6a488035 1076 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
74a6069d 1077 $fields = self::getMergeFieldsMetadata();
6a488035 1078
fcc3d8ee 1079 $main = self::getMergeContactDetails($mainId);
1080 $other = self::getMergeContactDetails($otherId);
74a6069d 1081 $specialValues['main'] = self::getSpecialValues($main);
1082 $specialValues['other'] = self::getSpecialValues($other);
6a488035 1083
4eea8606 1084 $compareFields = self::retrieveFields($main, $other);
6a488035
TO
1085
1086 $rows = $elements = $relTableElements = $migrationInfo = array();
1087
4eea8606 1088 foreach ($compareFields['contact'] as $field) {
4d5f18cc 1089 if ($field == 'contact_sub_type') {
1090 // CRM-15681 don't display sub-types in UI
1091 continue;
1092 }
6a488035
TO
1093 foreach (array('main', 'other') as $moniker) {
1094 $contact = &$$moniker;
1095 $value = CRM_Utils_Array::value($field, $contact);
1096 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
1097 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
1098 }
1099 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
a7488080 1100 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
6a488035
TO
1101 if ($value) {
1102 $value = str_replace('-', '', $value);
1103 $label = CRM_Utils_Date::customFormat($label);
1104 }
1105 else {
1106 $value = "null";
1107 }
1108 }
a7488080 1109 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
6a488035
TO
1110 if ($label === '0') {
1111 $label = ts('[ ]');
1112 }
1113 if ($label === '1') {
1114 $label = ts('[x]');
1115 }
00f3da2e 1116 }
74a6069d 1117 elseif ($field == 'prefix_id') {
00f3da2e 1118 $label = CRM_Utils_Array::value('individual_prefix', $contact);
00f3da2e 1119 }
74a6069d 1120 elseif ($field == 'suffix_id') {
00f3da2e 1121 $label = CRM_Utils_Array::value('individual_suffix', $contact);
6a488035 1122 }
4f88c9cf 1123 elseif ($field == 'gender_id' && !empty($value)) {
5b28be84
J
1124 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
1125 $label = $genderOptions['values'][$value];
4f88c9cf
C
1126 }
1127 elseif ($field == 'current_employer_id' && !empty($value)) {
1128 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
1129 }
6a488035
TO
1130 $rows["move_$field"][$moniker] = $label;
1131 if ($moniker == 'other') {
7154d2a4
BS
1132 //CRM-14334
1133 if ($value === NULL || $value == '') {
6a488035
TO
1134 $value = 'null';
1135 }
1136 if ($value === 0 or $value === '0') {
1137 $value = $qfZeroBug;
1138 }
8cc574cf 1139 if (is_array($value) && empty($value[1])) {
6a488035
TO
1140 $value[1] = NULL;
1141 }
13919cf8
J
1142
1143 // Display a checkbox to migrate, only if the values are different
1144 if ($value != $main[$field]) {
1145 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1146 }
1147
6a488035
TO
1148 $migrationInfo["move_$field"] = $value;
1149 }
1150 }
1151 $rows["move_$field"]['title'] = $fields[$field]['title'];
1152 }
1153
eb61dc07
J
1154 // Handle location blocks.
1155 // @todo OpenID not in API yet, so is not supported here.
65a35632 1156
087f00ec 1157 // Set up useful information about the location blocks
34917198 1158 $locationBlocks = self::getLocationBlockInfo();
087f00ec
J
1159
1160 $locations = array(
1161 'main' => array(),
1162 'other' => array(),
13919cf8 1163 );
b814df56 1164
087f00ec
J
1165 // @todo This could probably be defined and used earlier
1166 $mergeTargets = array(
1167 'main' => $mainId,
1168 'other' => $otherId,
1169 );
6a488035 1170
087f00ec 1171 foreach ($locationBlocks as $blockName => $blockInfo) {
6a488035 1172
087f00ec
J
1173 // Collect existing fields from both 'main' and 'other' contacts first
1174 // This allows us to match up location/types when building the table rows
1175 foreach ($mergeTargets as $moniker => $cid) {
b932e89e 1176 $searchParams = array(
b932e89e 1177 'contact_id' => $cid,
087f00ec
J
1178 // CRM-17556 Order by field-specific criteria
1179 'options' => array(
1180 'sort' => $blockInfo['sortString'],
1181 ),
b932e89e 1182 );
0b50eca0 1183 $values = civicrm_api3($blockName, 'get', $searchParams);
087f00ec
J
1184 if ($values['count']) {
1185 $cnt = 0;
bf588234 1186 foreach ($values['values'] as $value) {
087f00ec
J
1187 $locations[$moniker][$blockName][$cnt] = $value;
1188 // Fix address display
eb61dc07 1189 if ($blockName == 'address') {
087f00ec 1190 CRM_Core_BAO_Address::fixAddress($value);
ae6455b2 1191 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address::format($value);
6a488035 1192 }
abb422f9 1193
087f00ec 1194 $cnt++;
6a488035
TO
1195 }
1196 }
1197 }
6a488035 1198
087f00ec
J
1199 // Now, build the table rows appropriately, based off the information on
1200 // the 'other' contact
34917198
J
1201 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1202 foreach ($locations['other'][$blockName] as $count => $value) {
6a488035 1203
087f00ec 1204 $displayValue = $value[$blockInfo['displayField']];
65a35632 1205
087f00ec
J
1206 // Add this value to the table rows
1207 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
65a35632 1208
087f00ec
J
1209 // CRM-17556 Only display 'main' contact value if it's the same location + type
1210 // Look it up from main values...
65a35632 1211
087f00ec
J
1212 $lookupLocation = FALSE;
1213 if ($blockInfo['hasLocation']) {
1214 $lookupLocation = $value['location_type_id'];
1215 }
65a35632 1216
087f00ec
J
1217 $lookupType = FALSE;
1218 if ($blockInfo['hasType']) {
13cc4cac 1219 $lookupType = CRM_Utils_Array::value($blockInfo['hasType'], $value);
087f00ec 1220 }
65a35632 1221
34917198
J
1222 // Hold ID of main contact's matching block
1223 $mainContactBlockId = 0;
1224
087f00ec
J
1225 if (!empty($locations['main'][$blockName])) {
1226 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1227 // No location/type, or matching location and type
1228 if (
1229 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
1230 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
1231 ) {
34917198 1232 // Set this value as the default against the 'other' contact value
087f00ec 1233 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
041d6d6b 1234 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
34917198 1235 $mainContactBlockId = $mainValueCheck['id'];
087f00ec
J
1236 break;
1237 }
6a488035 1238 }
087f00ec 1239 }
65a35632 1240
087f00ec
J
1241 // Add checkbox to migrate data from 'other' to 'main'
1242 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
65a35632 1243
abd0b852
J
1244 // Add checkbox to set the 'other' location as primary
1245 $elements[] = array('advcheckbox', "location_blocks[$blockName][$count][set_other_primary]", NULL, ts('Set as primary'));
1246
087f00ec
J
1247 // Flag up this field to skipMerge function (@todo: do we need to?)
1248 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
65a35632 1249
34917198 1250 // Add a hidden field to store the ID of the target main contact block
972947a7 1251 $elements[] = array('hidden', "location_blocks[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
34917198 1252
087f00ec
J
1253 // Setup variables
1254 $thisTypeId = FALSE;
1255 $thisLocId = FALSE;
65a35632 1256
087f00ec
J
1257 // Provide a select drop-down for the location's location type
1258 // eg: Home, Work...
65a35632 1259
087f00ec
J
1260 if ($blockInfo['hasLocation']) {
1261
5b28be84
J
1262 // Load the location options for this entity
1263 $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
1264
087f00ec
J
1265 $thisLocId = $value['location_type_id'];
1266
1267 // Put this field's location type at the top of the list
5b28be84 1268 $tmpIdList = $locationOptions['values'];
087f00ec
J
1269 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1270 unset($tmpIdList[$thisLocId]);
1271
1272 // Add the element
eb61dc07
J
1273 $elements[] = array(
1274 'select',
972947a7 1275 "location_blocks[$blockName][$count][locTypeId]",
eb61dc07 1276 NULL,
087f00ec 1277 $defaultLocId + $tmpIdList,
6a488035 1278 );
087f00ec
J
1279
1280 // Add the relevant information to the $migrationInfo
1281 // Keep location-type-id same as that of other-contact
1282 // @todo Check this logic out
1283 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
abb422f9 1284 if ($blockName != 'address') {
abd0b852 1285 $elements[] = array('advcheckbox', "location_blocks[{$blockName}][$count][operation]", NULL, ts('Add new'));
087f00ec 1286 // always use add operation
abb422f9 1287 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
6a488035 1288 }
087f00ec 1289
6a488035 1290 }
6a488035 1291
087f00ec
J
1292 // Provide a select drop-down for the location's type/provider
1293 // eg websites: Google+, Facebook...
1294
087f00ec
J
1295 if ($blockInfo['hasType']) {
1296
5b28be84
J
1297 // Load the type options for this entity
1298 $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
1299
13cc4cac 1300 $thisTypeId = CRM_Utils_Array::value($blockInfo['hasType'], $value);
087f00ec
J
1301
1302 // Put this field's location type at the top of the list
5b28be84 1303 $tmpIdList = $typeOptions['values'];
13cc4cac 1304 $defaultTypeId = array($thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList));
087f00ec
J
1305 unset($tmpIdList[$thisTypeId]);
1306
1307 // Add the element
65a35632
J
1308 $elements[] = array(
1309 'select',
972947a7 1310 "location_blocks[$blockName][$count][typeTypeId]",
65a35632 1311 NULL,
087f00ec 1312 $defaultTypeId + $tmpIdList,
65a35632 1313 );
65a35632 1314
1e3e0eed 1315 // Add the information to the migrationInfo
34917198 1316 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
65a35632 1317
6a488035 1318 }
087f00ec
J
1319
1320 // Set the label for this row
34917198
J
1321 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
1322 if (!empty($thisLocId)) {
5b28be84 1323 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
6a488035 1324 }
34917198 1325 if (!empty($thisTypeId)) {
5b28be84 1326 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
34917198
J
1327 }
1328 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
65a35632 1329
34917198 1330 } // End loop through 'other' locations of this type
087f00ec 1331
34917198 1332 } // End if 'other' location for this type exists
6a488035 1333
34917198 1334 } // End loop through each location block entity
6a488035
TO
1335
1336 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1337 $config = CRM_Core_Config::singleton();
1338 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1339 $mainUser = NULL;
1340 if ($mainUfId) {
1341 // d6 compatible
1342 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1343 $mainUser = user_load($mainUfId);
1344 }
1345 elseif ($config->userFramework == 'Joomla') {
1346 $mainUser = JFactory::getUser($mainUfId);
1347 }
1348 }
1349 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1350 $otherUser = NULL;
1351 if ($otherUfId) {
1352 // d6 compatible
1353 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1354 $otherUser = user_load($otherUfId);
1355 }
1356 elseif ($config->userFramework == 'Joomla') {
1357 $otherUser = JFactory::getUser($otherUfId);
1358 }
1359 }
1360
1361 $relTables = CRM_Dedupe_Merger::relTables();
1362 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1363 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1364 foreach ($relTables as $name => $null) {
1365 if (!in_array($name, $activeRelTables) &&
1366 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1367 ) {
1368 unset($relTables[$name]);
1369 continue;
1370 }
1371
1372 $relTableElements[] = array('checkbox', "move_$name");
1373 $migrationInfo["move_$name"] = 1;
1374
1375 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1376 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1377 if ($name == 'rel_table_users') {
1378 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1379 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1380 $find = array('$ufid', '$ufname');
1381 if ($mainUser) {
1382 $replace = array($mainUfId, $mainUser->name);
1383 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1384 }
1385 if ($otherUser) {
1386 $replace = array($otherUfId, $otherUser->name);
1387 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1388 }
1389 }
1390 if ($name == 'rel_table_memberships') {
1391 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1392 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1393 }
1394 }
1395 foreach ($relTables as $name => $null) {
1396 $relTables["move_$name"] = $relTables[$name];
1397 unset($relTables[$name]);
1398 }
1399
1400 // handle custom fields
201057c0 1401 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1,
1402 CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035 1403 );
0b330e6d 1404 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1,
201057c0 1405 CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035
TO
1406 );
1407 CRM_Core_DAO::freeResult();
1408
1409 foreach ($otherTree as $gid => $group) {
1410 $foundField = FALSE;
1411 if (!isset($group['fields'])) {
1412 continue;
1413 }
1414
1415 foreach ($group['fields'] as $fid => $field) {
4eea8606 1416 if (in_array($fid, $compareFields['custom'])) {
6a488035
TO
1417 if (!$foundField) {
1418 $rows["custom_group_$gid"]['title'] = $group['title'];
1419 $foundField = TRUE;
1420 }
a7488080 1421 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
6a488035 1422 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
51a3717f 1423 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1424 }
1425 }
1426 $value = "null";
a7488080 1427 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
6a488035 1428 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
51a3717f 1429 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1430 if ($values['data'] === 0 || $values['data'] === '0') {
1431 $values['data'] = $qfZeroBug;
d58a19a1 1432 }
6a488035 1433 $value = ($values['data']) ? $values['data'] : $value;
d58a19a1 1434 }
6a488035
TO
1435 }
1436 $rows["move_custom_$fid"]['title'] = $field['label'];
1437
1438 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1439 $migrationInfo["move_custom_$fid"] = $value;
1440 }
1441 }
1442 }
abb422f9 1443
6a488035
TO
1444 $result = array(
1445 'rows' => $rows,
1446 'elements' => $elements,
1447 'rel_table_elements' => $relTableElements,
6a488035
TO
1448 'rel_tables' => $relTables,
1449 'main_details' => $main,
1450 'other_details' => $other,
1451 'migration_info' => $migrationInfo,
1452 );
1453
34917198
J
1454 $result['main_details']['location_blocks'] = $locations['main'];
1455 $result['other_details']['location_blocks'] = $locations['other'];
6a488035
TO
1456
1457 return $result;
1458 }
1459
1460 /**
1461 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1462 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1463 * A superset of moveContactBelongings() function.
1464 *
98997235
TO
1465 * @param int $mainId
1466 * Main contact with whom merge has to happen.
1467 * @param int $otherId
1468 * Duplicate contact which would be deleted after merge operation.
77b97be7
EM
1469 *
1470 * @param $migrationInfo
6a488035 1471 *
3058f4d9 1472 * @param bool $checkPermissions
1473 * Respect logged in user permissions.
1474 *
77b97be7 1475 * @return bool
6a488035 1476 */
3058f4d9 1477 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
6a488035
TO
1478 if (empty($migrationInfo)) {
1479 return FALSE;
1480 }
1481
1482 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1483 $relTables = CRM_Dedupe_Merger::relTables();
ae2346d4
CR
1484 $submittedCustomFields = $moveTables = $locationMigrationInfo = $tableOperations = array();
1485
6a488035
TO
1486 foreach ($migrationInfo as $key => $value) {
1487 if ($value == $qfZeroBug) {
1488 $value = '0';
1489 }
08b00099
CR
1490
1491 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
6a488035 1492 $submitted[substr($key, 5)] = $value;
ae2346d4 1493 $submittedCustomFields[] = substr($key, 12);
6a488035 1494 }
08b00099 1495 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) {
6a488035
TO
1496 $submitted[substr($key, 5)] = $value;
1497 }
34917198 1498 // Set up initial information for handling migration of location blocks
6a488035 1499 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
92a77772 1500 $locationMigrationInfo[$key] = $value;
6a488035
TO
1501 }
1502 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1503 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1504 if (array_key_exists('operation', $migrationInfo)) {
1505 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1506 if (array_key_exists($key, $migrationInfo['operation'])) {
1507 $tableOperations[$table] = $migrationInfo['operation'][$key];
1508 }
1509 }
1510 }
1511 }
1512 }
92a77772 1513 self::mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo);
6a488035 1514
6a488035 1515 // **** Do contact related migrations
ae2346d4 1516 $customTablesToCopyValues = self::getAffectedCustomTables($submittedCustomFields);
0556db5d
CR
1517 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1518 unset($moveTables, $tableOperations);
6a488035
TO
1519
1520 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1521 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1522 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1523 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
aa62b355 1524 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
6a488035
TO
1525 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1526 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1527 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1528 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1529
1530 // fix custom fields so they're edible by createProfileContact()
1531 static $treeCache = array();
1532 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
0b330e6d 1533 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'], NULL, NULL, -1);
6a488035 1534 }
6a488035
TO
1535
1536 $cFields = array();
bf588234 1537 foreach ($treeCache[$migrationInfo['main_details']['contact_type']] as $key => $group) {
6a488035
TO
1538 if (!isset($group['fields'])) {
1539 continue;
1540 }
1541 foreach ($group['fields'] as $fid => $field) {
1542 $cFields[$fid]['attributes'] = $field;
1543 }
1544 }
1545
1546 if (!isset($submitted)) {
1547 $submitted = array();
1548 }
1549 foreach ($submitted as $key => $value) {
1550 if (substr($key, 0, 7) == 'custom_') {
1551 $fid = (int) substr($key, 7);
0e357872
C
1552 if (empty($cFields[$fid])) {
1553 continue;
1554 }
6a488035
TO
1555 $htmlType = $cFields[$fid]['attributes']['html_type'];
1556 switch ($htmlType) {
1557 case 'File':
1558 $customFiles[] = $fid;
1559 unset($submitted["custom_$fid"]);
1560 break;
1561
1562 case 'Select Country':
1563 case 'Select State/Province':
8cee0c70 1564 $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
6a488035
TO
1565 break;
1566
69239109 1567 case 'Select Date':
1568 if ($cFields[$fid]['attributes']['is_view']) {
1569 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
1570 }
1571 break;
1572
6a488035
TO
1573 case 'CheckBox':
1574 case 'AdvMulti-Select':
1575 case 'Multi-Select':
1576 case 'Multi-Select Country':
1577 case 'Multi-Select State/Province':
1578 // Merge values from both contacts for multivalue fields, CRM-4385
1579 // get the existing custom values from db.
1580 $customParams = array('entityID' => $mainId, $key => TRUE);
1581 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
a7488080 1582 if (!empty($customfieldValues[$key])) {
6a488035
TO
1583 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1584 if (is_array($existingValue) && !empty($existingValue)) {
ae2346d4 1585 $mergeValue = $submittedCustomFields = array();
8a14f0f3 1586 if ($value == 'null') {
1587 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
1588 $submitted[$key] = $value;
6a488035 1589 }
8a14f0f3 1590 else {
1591 if ($value) {
ae2346d4 1592 $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
8a14f0f3 1593 }
6a488035 1594
d606f5bc 1595 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
1596 // custom field value stored at $submittedCustomValue.
ae2346d4 1597 foreach ($submittedCustomFields as $k => $v) {
8a14f0f3 1598 if ($v != '' && !in_array($v, $mergeValue)) {
1599 $mergeValue[] = $v;
1600 }
6a488035 1601 }
6a488035 1602
8a14f0f3 1603 //keep state and country as array format.
1604 //for checkbox and m-select format w/ VALUE_SEPARATOR
1605 if (in_array($htmlType, array(
1606 'CheckBox',
1607 'Multi-Select',
1608 'AdvMulti-Select',
1609 ))) {
1610 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1611 $mergeValue
1612 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1613 }
1614 else {
1615 $submitted[$key] = $mergeValue;
1616 }
6a488035
TO
1617 }
1618 }
1619 }
1620 elseif (in_array($htmlType, array(
353ffa53 1621 'Multi-Select Country',
c301f76e 1622 'Multi-Select State/Province',
353ffa53 1623 ))) {
6a488035
TO
1624 //we require submitted values should be in array format
1625 if ($value) {
1626 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1627 //hack to remove null values from array.
1628 $mergeValue = array();
1629 foreach ($mergeValueArray as $k => $v) {
1630 if ($v != '') {
1631 $mergeValue[] = $v;
1632 }
1633 }
1634 $submitted[$key] = $mergeValue;
1635 }
1636 }
1637 break;
1638
1639 default:
1640 break;
1641 }
1642 }
1643 }
1644
1645 // **** Do file custom fields related migrations
1646 // FIXME: move this someplace else (one of the BAOs) after discussing
b3fdbf3d 1647 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
6a488035
TO
1648 // like, delete a file...
1649
1650 if (!isset($customFiles)) {
1651 $customFiles = array();
1652 }
1653 foreach ($customFiles as $customId) {
1654 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1655
1656 // get the contact_id -> file_id mapping
1657 $fileIds = array();
1658 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
9d2678f4 1659 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
1660 while ($dao->fetch()) {
1661 $fileIds[$dao->entity_id] = $dao->file_id;
ecdae719 1662 if ($dao->entity_id == $mainId) {
1663 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1664 }
6a488035
TO
1665 }
1666 $dao->free();
1667
6a488035
TO
1668 // move the other contact's file to main contact
1669 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
481a74f4 1670 if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
d58a19a1 1671 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
6a488035
TO
1672 }
1673 else {
1674 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1675 }
9d2678f4 1676 CRM_Core_DAO::executeQuery($sql);
6a488035 1677
481a74f4 1678 if (CRM_Core_DAO::singleValueQuery("
6a488035
TO
1679 SELECT id
1680 FROM civicrm_entity_file
353ffa53
TO
1681 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1682 ) {
6a488035
TO
1683 $sql = "
1684 UPDATE civicrm_entity_file
1685 SET entity_id = {$mainId}
1686 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1687 }
1688 else {
1689 $sql = "
1690 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1691 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1692 }
9d2678f4 1693 CRM_Core_DAO::executeQuery($sql);
6a488035
TO
1694 }
1695
1696 // move view only custom fields CRM-5362
1697 $viewOnlyCustomFields = array();
1698 foreach ($submitted as $key => $value) {
1699 $fid = (int) substr($key, 7);
8cc574cf 1700 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
6a488035
TO
1701 $viewOnlyCustomFields[$key] = $value;
1702 }
1703 }
1704
1705 // special case to set values for view only, CRM-5362
1706 if (!empty($viewOnlyCustomFields)) {
1707 $viewOnlyCustomFields['entityID'] = $mainId;
1708 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1709 }
1710
3058f4d9 1711 if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') &&
1712 CRM_Core_Permission::check('delete contacts'))
6a488035
TO
1713 ) {
1714 // if ext id is submitted then set it null for contact to be deleted
a7488080 1715 if (!empty($submitted['external_identifier'])) {
6a488035
TO
1716 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1717 CRM_Core_DAO::executeQuery($query);
1718 }
5ea06a7b 1719 civicrm_api3('contact', 'delete', array('id' => $otherId));
6a488035 1720 }
6a488035 1721
4d5f18cc 1722 // CRM-15681 merge sub_types
35522279
J
1723 if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) {
1724 if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) {
481a74f4 1725 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
0db6c3e1
TO
1726 }
1727 else {
4d5f18cc 1728 $submitted['contact_sub_type'] = $other_sub_types;
1729 }
1730 }
1731
6a488035
TO
1732 // **** Update contact related info for the main contact
1733 if (!empty($submitted)) {
1734 $submitted['contact_id'] = $mainId;
1735
1736 //update current employer field
1737 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1738 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1739 $submitted['current_employer'] = $submitted['current_employer_id'];
0db6c3e1
TO
1740 }
1741 else {
6a488035
TO
1742 $submitted['current_employer'] = '';
1743 }
1744 unset($submitted['current_employer_id']);
1745 }
1746
00f3da2e 1747 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
481a74f4 1748 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
00f3da2e
BS
1749 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1750 }
481a74f4 1751 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
00f3da2e
BS
1752 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1753 }
1754
6a488035 1755 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
6a488035
TO
1756 }
1757
1273d77c 1758 CRM_Utils_Hook::post('merge', 'Contact', $mainId);
f00283b5 1759 self::createMergeActivities($mainId, $otherId);
5ea06a7b 1760
6a488035
TO
1761 return TRUE;
1762 }
16254ae1 1763
ae2346d4
CR
1764 /**
1765 * Builds an Array of Custom tables for given custom field ID's.
1766 *
1767 * @param $customFieldIDs
1768 *
1769 * @return array
1770 * Array of custom table names
1771 */
1772 private static function getAffectedCustomTables($customFieldIDs) {
1773 $customTableToCopyValues = array();
1774
1775 foreach ($customFieldIDs as $fieldID) {
1776 if (!empty($fieldID)) {
08b00099
CR
1777 $customField = civicrm_api3('custom_field', 'getsingle', array(
1778 'id' => $fieldID,
1779 'is_active' => TRUE,
1780 ));
1781 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
1782 $customGroup = civicrm_api3('custom_group', 'getsingle', array(
1783 'id' => $customField['custom_group_id'],
ae2346d4
CR
1784 'is_active' => TRUE,
1785 ));
ae2346d4
CR
1786
1787 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1788 $customTableToCopyValues[] = $customGroup['table_name'];
1789 }
1790 }
1791 }
1792 }
1793
1794 return $customTableToCopyValues;
1795 }
1796
16254ae1 1797 /**
f00283b5 1798 * Get fields in the contact table suitable for merging.
1799 *
a6c01b45 1800 * @return array
f00283b5 1801 * Array of field names to be potentially merged.
16254ae1 1802 */
00be9182 1803 public static function getContactFields() {
16254ae1 1804 $contactFields = CRM_Contact_DAO_Contact::fields();
353ffa53
TO
1805 $invalidFields = array(
1806 'api_key',
353ffa53
TO
1807 'created_date',
1808 'display_name',
1809 'hash',
1810 'id',
1811 'modified_date',
1812 'primary_contact_id',
1813 'sort_name',
c301f76e 1814 'user_unique_id',
353ffa53 1815 );
bdd7870e
RN
1816 foreach ($contactFields as $field => $value) {
1817 if (in_array($field, $invalidFields)) {
1818 unset($contactFields[$field]);
1819 }
1820 }
16254ae1
ARW
1821 return array_keys($contactFields);
1822 }
ada104d5
AW
1823
1824 /**
1825 * Added for CRM-12695
c301f76e 1826 * Based on the contactID provided
ada104d5
AW
1827 * add/update membership(s) to related contacts
1828 *
c301f76e 1829 * @param int $contactID
ada104d5 1830 */
00be9182 1831 public static function addMembershipToRealtedContacts($contactID) {
ada104d5
AW
1832 $dao = new CRM_Member_DAO_Membership();
1833 $dao->contact_id = $contactID;
1834 $dao->is_test = 0;
1835 $dao->find();
1836
1837 //checks membership of contact itself
1838 while ($dao->fetch()) {
1839 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1840 if ($relationshipTypeId) {
1841 $membershipParams = array(
1842 'id' => $dao->id,
1843 'contact_id' => $dao->contact_id,
1844 'membership_type_id' => $dao->membership_type_id,
1845 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1846 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1847 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1848 'source' => $dao->source,
21dfd5f5 1849 'status_id' => $dao->status_id,
ada104d5
AW
1850 );
1851 // create/update membership(s) for related contact(s)
1852 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1853 } // end of if relationshipTypeId
1854 }
1855 }
96025800 1856
3ae0ae3d 1857 /**
1858 * Add custom tables that extend contacts to the list of contact references.
1859 *
1860 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
1861 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
1862 * - the down side is it is not cached.
1863 *
1864 * Further changes should be include tests in the CRM_Core_MergerTest class
1865 * to ensure that disabled, subtype, multiple etc groups are still captured.
1866 *
1867 * @param array $cidRefs
1868 */
1869 public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
1870 $customValueTables = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
1871 $customValueTables->find();
1872 while ($customValueTables->fetch()) {
1873 $cidRefs[$customValueTables->table_name] = array('entity_id');
1874 }
1875 }
1876
f00283b5 1877 /**
1878 * Create activities tracking the merge on affected contacts.
1879 *
1880 * @param int $mainId
1881 * @param int $otherId
1882 *
1883 * @throws \CiviCRM_API3_Exception
1884 */
1885 public static function createMergeActivities($mainId, $otherId) {
1886 $params = array(
1887 1 => $otherId,
1888 2 => $mainId,
1889 );
1890 $activity = civicrm_api3('activity', 'create', array(
dc33398e
J
1891 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1892 $mainId,
f00283b5 1893 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1894 'target_contact_id' => $mainId,
1895 'activity_type_id' => 'Contact Merged',
1896 'status_id' => 'Completed',
1897 ));
4d834a99 1898 if (civicrm_api3('Setting', 'getvalue', array('name' => 'contact_undelete', 'group' => 'CiviCRM Preferences'))) {
1899 civicrm_api3('activity', 'create', array(
dc33398e
J
1900 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1901 $otherId,
4d834a99 1902 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1903 'target_contact_id' => $otherId,
1904 'activity_type_id' => 'Contact Deleted by Merge',
1905 'parent_id' => $activity['id'],
1906 'status_id' => 'Completed',
1907 ));
1908 }
f00283b5 1909 }
1910
2988f5c7 1911 /**
1912 * Get Duplicate Pairs based on a rule for a group.
1913 *
1914 * @param int $rule_group_id
1915 * @param int $group_id
1916 * @param bool $reloadCacheIfEmpty
1917 * @param int $batchLimit
1918 * @param bool $isSelected
5721d85e 1919 * Limit to selected pairs.
3058f4d9 1920 * @param array|string $orderByClause
66eceb0b 1921 * @param bool $includeConflicts
e23e26ec 1922 * @param array $criteria
1923 * Additional criteria to narrow down the merge group.
2988f5c7 1924 *
3058f4d9 1925 * @param bool $checkPermissions
1926 * Respect logged in user permissions.
1927 *
21a95d83 1928 * @param int $searchLimit
1929 * Limit to searching for matches against this many contacts.
1930 *
2988f5c7 1931 * @return array
3058f4d9 1932 * Array of matches meeting the criteria.
2988f5c7 1933 */
21a95d83 1934 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $orderByClause = '', $includeConflicts = TRUE, $criteria = array(), $checkPermissions = TRUE, $searchLimit = 0) {
2988f5c7 1935 $where = self::getWhereString($batchLimit, $isSelected);
3058f4d9 1936 $cacheKeyString = self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions);
2988f5c7 1937 $join = self::getJoinOnDedupeTable();
66eceb0b 1938 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
2988f5c7 1939 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1940 // If we haven't found any dupes, probably cache is empty.
66eceb0b 1941 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1942 // until we have done some processing.
21a95d83 1943 CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions, $searchLimit);
66eceb0b 1944 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
2988f5c7 1945 return $dupePairs;
1946 }
1947 return $dupePairs;
1948 }
1949
2ae26001 1950 /**
1951 * Get the cache key string for the merge action.
1952 *
1953 * @param int $rule_group_id
1954 * @param int $group_id
e23e26ec 1955 * @param array $criteria
1956 * Additional criteria to narrow down the merge group.
1957 * Currently we are only supporting the key 'contact' within it.
2ae26001 1958 *
3058f4d9 1959 * @param bool $checkPermissions
1960 * Respect the users permissions.
1961 *
2ae26001 1962 * @return string
1963 */
3058f4d9 1964 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = array(), $checkPermissions = TRUE) {
2ae26001 1965 $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
1966 $cacheKeyString = "merge {$contactType}";
1967 $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
1968 $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
629dd4f3 1969 $cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0';
3058f4d9 1970 if ($checkPermissions) {
1971 $contactID = CRM_Core_Session::getLoggedInContactID();
1972 if (!$contactID) {
1973 // Distinguish between no permission check & no logged in user.
1974 $contactID = 'null';
1975 }
1976 $cacheKeyString .= '_' . $contactID;
1977 }
1978 else {
1979 $cacheKeyString .= '_0';
1980 }
2ae26001 1981 return $cacheKeyString;
1982 }
1983
1996e7d4 1984 /**
5d5b49ad 1985 * @param array $contact
1996e7d4 1986 * @return array
1987 * $specialValues
1988 */
1989 public static function getSpecialValues($contact) {
35522279 1990 $preferred_communication_method = CRM_Utils_Array::value('preferred_communication_method', $contact);
1996e7d4 1991 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
1992 $specialValues = array(
1993 'preferred_communication_method' => $value,
1994 'communication_style_id' => $value,
1995 );
1996
1997 if (!empty($contact['preferred_communication_method'])) {
1998 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
1999 $prefCommList = is_array($specialValues['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues['preferred_communication_method']) : $specialValues['preferred_communication_method'];
2000 $specialValues['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
2001 }
2002 $names = array(
2003 'preferred_communication_method' => array(
2004 'newName' => 'preferred_communication_method_display',
2005 'groupName' => 'preferred_communication_method',
2006 ),
2007 );
2008 CRM_Core_OptionGroup::lookupValues($specialValues, $names);
2009
2010 if (!empty($contact['communication_style'])) {
2011 $specialValues['communication_style_id_display'] = $contact['communication_style'];
2012 }
2013 return $specialValues;
2014 }
2015
74a6069d 2016 /**
2017 * Get the metadata for the merge fields.
2018 *
2019 * This is basically the contact metadata, augmented with fields to
2020 * represent email greeting, postal greeting & addressee.
2021 *
2022 * @return array
2023 */
2024 public static function getMergeFieldsMetadata() {
2025 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) {
2026 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
2027 }
2028 $fields = CRM_Contact_DAO_Contact::fields();
2029 static $optionValueFields = array();
2030 if (empty($optionValueFields)) {
2031 $optionValueFields = CRM_Core_OptionValue::getFields();
2032 }
2033 foreach ($optionValueFields as $field => $params) {
2034 $fields[$field]['title'] = $params['title'];
2035 }
2036 \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields;
2037 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
2038 }
2039
2040 /**
2041 * Get the details of the contact to be merged.
2042 *
2043 * @param int $contact_id
74a6069d 2044 *
2045 * @return array
2046 *
2047 * @throws CRM_Core_Exception
2048 */
fcc3d8ee 2049 public static function getMergeContactDetails($contact_id) {
74a6069d 2050 $params = array(
2051 'contact_id' => $contact_id,
2052 'version' => 3,
2053 'return' => array_merge(array('display_name'), self::getContactFields()),
2054 );
2055 $result = civicrm_api('contact', 'get', $params);
2056
2057 // CRM-18480: Cancel the process if the contact is already deleted
2058 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
fcc3d8ee 2059 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', array(
2060 1 => $contact_id,
74a6069d 2061 )));
2062 }
2063
2064 return $result['values'][$contact_id];
2065 }
2066
92a77772 2067 /**
2068 * Merge location.
2069 *
2070 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
2071 *
2072 * The data is in the format received from the merge form (which is a fairly confusing format).
2073 *
2074 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
2075 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
2076 * been calculated and before saving because
2077 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
2078 * - passing to a hook right before save means calculations only have to be done once
2079 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
2080 * ugly.
2081 *
2082 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
16d4e0b7 2083 * is likely to be significant data in merge hooks.
92a77772 2084 *
2085 * @param int $mainId
2086 * @param int $otherId
2087 * @param array $locationMigrationInfo
2088 * Portion of the migration_info that holds location migration information.
2089 *
2090 * @param array $migrationInfo
2091 * Migration info for the merge. This is passed to the hook as informational only.
2092 */
2093 public static function mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo) {
2094 foreach ($locationMigrationInfo as $key => $value) {
2095 $locField = explode('_', $key);
2096 $fieldName = $locField[2];
2097 $fieldCount = $locField[3];
2098
2099 // Set up the operation type (add/overwrite)
2100 // Ignore operation for websites
2101 // @todo Tidy this up
2102 $operation = 0;
2103 if ($fieldName != 'website') {
2104 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
2105 }
2106 // default operation is overwrite.
2107 if (!$operation) {
2108 $operation = 2;
2109 }
2110 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
2111 }
2112 $blocksDAO = array();
2113
2114 // @todo Handle OpenID (not currently in API).
2115 if (!empty($locBlocks)) {
2116 $locationBlocks = self::getLocationBlockInfo();
2117
2118 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
2119 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
2120
2121 foreach ($locBlocks as $name => $block) {
2122 $blocksDAO[$name] = array('delete' => array(), 'update' => array());
2123 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
2124 continue;
2125 }
2126 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
abd0b852 2127 $changePrimary = FALSE;
92a77772 2128 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
2129 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
2130
2131 foreach ($block as $blkCount => $values) {
2132 $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
2133 $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
2134 if (!$otherBlockId) {
2135 continue;
2136 }
2137
2138 // For the block which belongs to other-contact, link the location block to main-contact
2139 $otherBlockDAO = new $daoName();
2140 $otherBlockDAO->contact_id = $mainId;
2141
2142 // Get the ID of this block on the 'other' contact, otherwise skip
2143 $otherBlockDAO->id = $otherBlockId;
2144
2145 // Add/update location and type information from the form, if applicable
2146 if ($locationBlocks[$name]['hasLocation']) {
2147 $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2148 $otherBlockDAO->location_type_id = $locTypeId;
2149 }
2150 if ($locationBlocks[$name]['hasType']) {
2151 $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2152 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
2153 }
2154
abd0b852
J
2155 // If we're deliberately setting this as primary then add the flag
2156 // and remove it from the current primary location (if there is one).
2157 // But only once for each entity.
2158 $set_primary = CRM_Utils_Array::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
9e848fc4 2159 if (!$changePrimary && $set_primary == "1") {
abd0b852
J
2160 $otherBlockDAO->is_primary = 1;
2161 if ($primaryDAOId) {
2162 $removePrimaryDAO = new $daoName();
2163 $removePrimaryDAO->id = $primaryDAOId;
2164 $removePrimaryDAO->is_primary = 0;
2165 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
2166 }
2167 $changePrimary = TRUE;
2168 }
2169 // Otherwise, if main contact already has primary, set it to 0.
2170 elseif ($primaryDAOId) {
92a77772 2171 $otherBlockDAO->is_primary = 0;
2172 }
abd0b852
J
2173
2174 // If the main contact already has a billing location, set this to 0.
92a77772 2175 if ($billingDAOId) {
2176 $otherBlockDAO->is_billing = 0;
2177 }
2178
2179 $operation = CRM_Utils_Array::value('operation', $values, 2);
2180 // overwrite - need to delete block which belongs to main-contact.
2181 if (!empty($mainBlockId) && ($operation == 2)) {
2182 $deleteDAO = new $daoName();
2183 $deleteDAO->id = $mainBlockId;
2184 $deleteDAO->find(TRUE);
2185
2186 // if we about to delete a primary / billing block, set the flags for new block
2187 // that we going to assign to main-contact
2188 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
2189 $otherBlockDAO->is_primary = 1;
2190 }
2191 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
2192 $otherBlockDAO->is_billing = 1;
2193 }
2194 $blocksDAO[$name]['delete'][$deleteDAO->id] = $deleteDAO;
2195 }
2196 $blocksDAO[$name]['update'][$otherBlockDAO->id] = $otherBlockDAO;
2197 }
2198 }
2199 }
2200
2201 CRM_Utils_Hook::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2202 foreach ($blocksDAO as $blockDAOs) {
2203 if (!empty($blockDAOs['update'])) {
2204 foreach ($blockDAOs['update'] as $blockDAO) {
2205 $blockDAO->save();
2206 }
2207 }
2208 if (!empty($blockDAOs['delete'])) {
2209 foreach ($blockDAOs['delete'] as $blockDAO) {
2210 $blockDAO->delete();
2211 }
2212 }
2213 }
2214 }
2215
e4e1db4b 2216 /**
2217 * Dedupe a pair of contacts.
2218 *
2219 * @param array $migrationInfo
2220 * @param array $resultStats
2221 * @param array $deletedContacts
2222 * @param string $mode
2223 * @param bool $checkPermissions
2224 * @param int $mainId
2225 * @param int $otherId
2226 * @param string $cacheKeyString
2227 */
2228 protected static function dedupePair(&$migrationInfo, &$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) {
2229
2230 // go ahead with merge if there is no conflict
2231 $conflicts = array();
2232 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2233 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2234 $resultStats['merged'][] = array(
2235 'main_id' => $mainId,
2236 'other_id' => $otherId,
2237 );
2238 $deletedContacts[] = $otherId;
2239 }
2240 else {
2241 $resultStats['skipped'][] = array(
2242 'main_id' => $mainId,
2243 'other_id' => $otherId,
2244 );
2245 }
2246
2247 // store any conflicts
2248 if (!empty($conflicts)) {
2249 foreach ($conflicts as $key => $dnc) {
2250 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
2251 }
2252 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
2253 }
2254 else {
2255 // delete entry from PrevNextCache table so we don't consider the pair next time
2256 // pair may have been flipped, so make sure we delete using both orders
2257 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
2258 }
2259
2260 CRM_Core_DAO::freeResult();
2261 }
2262
6a488035 2263}