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