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