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