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