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