Ian province abbreviation patch - issue 724
[civicrm-core.git] / CRM / Dedupe / Merger.php
... / ...
CommitLineData
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 * $Id$
33 *
34 */
35class CRM_Dedupe_Merger {
36
37 /**
38 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
39 * FIXME: the sub-pages references by the URLs should
40 * be loaded dynamically on the merge form instead
41 * @return array
42 */
43 public static function relTables() {
44 static $relTables;
45
46 $config = CRM_Core_Config::singleton();
47 if ($config->userSystem->is_drupal) {
48 $userRecordUrl = CRM_Utils_System::url('user/%ufid');
49 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
50 }
51 elseif ($config->userFramework == 'Joomla') {
52 $userRecordUrl = $config->userFrameworkVersion > 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';
53 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
54 }
55
56 if (!$relTables) {
57 $relTables = array(
58 'rel_table_contributions' => array(
59 'title' => ts('Contributions'),
60 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
61 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
62 ),
63 'rel_table_contribution_page' => array(
64 'title' => ts('Contribution Pages'),
65 'tables' => array('civicrm_contribution_page'),
66 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
67 ),
68 'rel_table_memberships' => array(
69 'title' => ts('Memberships'),
70 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
71 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
72 ),
73 'rel_table_participants' => array(
74 'title' => ts('Participants'),
75 'tables' => array('civicrm_participant'),
76 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
77 ),
78 'rel_table_events' => array(
79 'title' => ts('Events'),
80 'tables' => array('civicrm_event'),
81 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
82 ),
83 'rel_table_activities' => array(
84 'title' => ts('Activities'),
85 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
86 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
87 ),
88 'rel_table_relationships' => array(
89 'title' => ts('Relationships'),
90 'tables' => array('civicrm_relationship'),
91 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
92 ),
93 'rel_table_custom_groups' => array(
94 'title' => ts('Custom Groups'),
95 'tables' => array('civicrm_custom_group'),
96 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
97 ),
98 'rel_table_uf_groups' => array(
99 'title' => ts('Profiles'),
100 'tables' => array('civicrm_uf_group'),
101 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
102 ),
103 'rel_table_groups' => array(
104 'title' => ts('Groups'),
105 'tables' => array('civicrm_group_contact'),
106 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
107 ),
108 'rel_table_notes' => array(
109 'title' => ts('Notes'),
110 'tables' => array('civicrm_note'),
111 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
112 ),
113 'rel_table_tags' => array(
114 'title' => ts('Tags'),
115 'tables' => array('civicrm_entity_tag'),
116 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
117 ),
118 'rel_table_mailings' => array(
119 'title' => ts('Mailings'),
120 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
121 'url' => CRM_Utils_System::url('civicrm/mailing', 'reset=1&force=1&cid=$cid'),
122 ),
123 'rel_table_cases' => array(
124 'title' => ts('Cases'),
125 'tables' => array('civicrm_case_contact'),
126 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
127 ),
128 'rel_table_grants' => array(
129 'title' => ts('Grants'),
130 'tables' => array('civicrm_grant'),
131 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
132 ),
133 'rel_table_pcp' => array(
134 'title' => ts('PCPs'),
135 'tables' => array('civicrm_pcp'),
136 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
137 ),
138 'rel_table_pledges' => array(
139 'title' => ts('Pledges'),
140 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
141 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
142 ),
143 'rel_table_users' => array(
144 'title' => $title,
145 'tables' => array('civicrm_uf_match'),
146 'url' => $userRecordUrl,
147 ),
148 );
149
150 $relTables += self::getMultiValueCustomSets('relTables');
151
152 // Allow hook_civicrm_merge() to adjust $relTables
153 CRM_Utils_Hook::merge('relTables', $relTables);
154 }
155 return $relTables;
156 }
157
158 /**
159 * Returns the related tables groups for which a contact has any info entered.
160 */
161 public static function getActiveRelTables($cid) {
162 $cid = (int) $cid;
163 $groups = array();
164
165 $relTables = self::relTables();
166 $cidRefs = self::cidRefs();
167 $eidRefs = self::eidRefs();
168 foreach ($relTables as $group => $params) {
169 $sqls = array();
170 foreach ($params['tables'] as $table) {
171 if (isset($cidRefs[$table])) {
172 foreach ($cidRefs[$table] as $field) {
173 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
174 }
175 }
176 if (isset($eidRefs[$table])) {
177 foreach ($eidRefs[$table] as $entityTable => $entityId) {
178 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
179 }
180 }
181 foreach ($sqls as $sql) {
182 if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
183 $groups[] = $group;
184 }
185 }
186 }
187 }
188 return array_unique($groups);
189 }
190
191 /**
192 * Return tables and their fields referencing civicrm_contact.contact_id explicitly
193 */
194 public static function cidRefs() {
195 static $cidRefs;
196 if (!$cidRefs) {
197 $sql = "
198SELECT
199 table_name,
200 column_name
201FROM information_schema.key_column_usage
202WHERE
203 referenced_table_schema = database() AND
204 referenced_table_name = 'civicrm_contact' AND
205 referenced_column_name = 'id';
206 ";
207 $dao = CRM_Core_DAO::executeQuery($sql);
208 while ($dao->fetch()) {
209 $cidRefs[$dao->table_name][] = $dao->column_name;
210 }
211
212 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
213 $cidRefs['civicrm_entity_tag'][] = 'entity_id';
214 $dao->free();
215
216 // Allow hook_civicrm_merge() to adjust $cidRefs
217 CRM_Utils_Hook::merge('cidRefs', $cidRefs);
218 }
219 return $cidRefs;
220 }
221
222 /**
223 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
224 */
225 public static function eidRefs() {
226 static $eidRefs;
227 if (!$eidRefs) {
228 // FIXME: this should be generated dynamically from the schema
229 // tables that reference contacts with entity_{id,table}
230 $eidRefs = array(
231 'civicrm_acl' => array('entity_table' => 'entity_id'),
232 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
233 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
234 'civicrm_log' => array('entity_table' => 'entity_id'),
235 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
236 'civicrm_note' => array('entity_table' => 'entity_id'),
237 );
238
239 // Allow hook_civicrm_merge() to adjust $eidRefs
240 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
241 }
242 return $eidRefs;
243 }
244
245 /**
246 * Return tables using locations.
247 */
248 public static function locTables() {
249 static $locTables;
250 if (!$locTables) {
251 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
252
253 // Allow hook_civicrm_merge() to adjust $locTables
254 CRM_Utils_Hook::merge('locTables', $locTables);
255 }
256 return $locTables;
257 }
258
259 /**
260 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
261 * @param string $request
262 * 'relTables' or 'cidRefs'.
263 * @see CRM-13836
264 */
265 public static function getMultiValueCustomSets($request) {
266 static $data = NULL;
267 if ($data === NULL) {
268 $data = array(
269 'relTables' => array(),
270 'cidRefs' => array(),
271 );
272 $result = civicrm_api3('custom_group', 'get', array(
273 'is_multiple' => 1,
274 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
275 'return' => array('id', 'title', 'table_name', 'style'),
276 ));
277 foreach ($result['values'] as $custom) {
278 $data['cidRefs'][$custom['table_name']] = array('entity_id');
279 $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
280 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
281 'title' => $custom['title'],
282 'tables' => array($custom['table_name']),
283 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
284 );
285 }
286 }
287 return $data[$request];
288 }
289
290 /**
291 * Tables which require custom processing should declare functions to call here.
292 * Doing so will override normal processing.
293 */
294 public static function cpTables() {
295 static $tables;
296 if (!$tables) {
297 $tables = array(
298 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
299 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
300 // Empty array == do nothing - this table is handled by mergeGroupContact
301 'civicrm_subscription_history' => array(),
302 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
303 );
304 }
305 return $tables;
306 }
307
308 /**
309 * Return payment related table.
310 */
311 public static function paymentTables() {
312 static $tables;
313 if (!$tables) {
314 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
315 }
316
317 return $tables;
318 }
319
320 /**
321 * Return payment update Query.
322 */
323 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
324 $sqls = array();
325 if (!$tableName || !$mainContactId || !$otherContactId) {
326 return $sqls;
327 }
328
329 $paymentTables = self::paymentTables();
330 if (!in_array($tableName, $paymentTables)) {
331 return $sqls;
332 }
333
334 switch ($tableName) {
335 case 'civicrm_pledge':
336 $sqls[] = "
337 UPDATE IGNORE civicrm_contribution contribution
338INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
339INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
340 SET contribution.contact_id = $mainContactId
341 WHERE pledge.contact_id = $otherContactId";
342 break;
343
344 case 'civicrm_membership':
345 $sqls[] = "
346 UPDATE IGNORE civicrm_contribution contribution
347INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
348INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
349 SET contribution.contact_id = $mainContactId
350 WHERE membership.contact_id = $otherContactId";
351 break;
352
353 case 'civicrm_participant':
354 $sqls[] = "
355 UPDATE IGNORE civicrm_contribution contribution
356INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
357INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
358 SET contribution.contact_id = $mainContactId
359 WHERE participant.contact_id = $otherContactId";
360 break;
361 }
362
363 return $sqls;
364 }
365
366 /**
367 * @param int $mainId
368 * @param int $otherId
369 * @param string $tableName
370 * @param array $tableOperations
371 * @param string $mode
372 *
373 * @return array
374 */
375 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
376 $sqls = array();
377 if (!$tableName || !$mainId || !$otherId) {
378 return $sqls;
379 }
380
381 switch ($tableName) {
382 case 'civicrm_membership':
383 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
384 break;
385 }
386 if ($mode == 'add') {
387 $sqls[] = "
388DELETE membership1.* FROM civicrm_membership membership1
389 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
390 AND membership1.contact_id = {$mainId}
391 AND membership2.contact_id = {$otherId} ";
392 }
393 if ($mode == 'payment') {
394 $sqls[] = "
395DELETE contribution.* FROM civicrm_contribution contribution
396INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
397INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
398 AND membership1.contact_id = {$mainId}
399INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
400 AND membership2.contact_id = {$otherId}";
401 }
402 break;
403
404 case 'civicrm_uf_match':
405 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
406 // failing to meet intended result. Therefore we introduce this additional query:
407 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
408 break;
409 }
410
411 return $sqls;
412 }
413
414 /**
415 * Based on the provided two contact_ids and a set of tables, move the
416 * belongings of the other contact to the main one.
417 *
418 */
419 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
420 $cidRefs = self::cidRefs();
421 $eidRefs = self::eidRefs();
422 $cpTables = self::cpTables();
423 $paymentTables = self::paymentTables();
424 $membershipMerge = FALSE; // CRM-12695
425
426 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
427 if ($tables !== FALSE) {
428 // if there are specific tables, sanitize the list
429 $affected = array_unique(array_intersect($affected, $tables));
430 }
431 else {
432 // if there aren't any specific tables, don't affect the ones handled by relTables()
433 // also don't affect tables in locTables() CRM-15658
434 $relTables = self::relTables();
435 $handled = self::locTables();
436 foreach ($relTables as $params) {
437 $handled = array_merge($handled, $params['tables']);
438 }
439 $affected = array_diff($affected, $handled);
440 /**
441 * CRM-12695
442 * Set $membershipMerge flag only once
443 * while doing contact related migration
444 * to call addMembershipToRealtedContacts()
445 * function only once.
446 * Since the current function (moveContactBelongings) is called twice
447 * with & without parameters $tables & $tableOperations
448 */
449 // retrieve main contact's related table(s)
450 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
451 // check if membership table exists in main contact's related table(s)
452 if (in_array('rel_table_memberships', $activeMainRelTables)) {
453 $membershipMerge = TRUE; // set membership flag - CRM-12695
454 }
455 }
456
457 $mainId = (int) $mainId;
458 $otherId = (int) $otherId;
459
460 $sqls = array();
461 foreach ($affected as $table) {
462 // Call custom processing function for objects that require it
463 if (isset($cpTables[$table])) {
464 foreach ($cpTables[$table] as $className => $fnName) {
465 $className::$fnName($mainId, $otherId, $sqls);
466 }
467 // Skip normal processing
468 continue;
469 }
470
471 // use UPDATE IGNORE + DELETE query pair to skip on situations when
472 // there's a UNIQUE restriction on ($field, some_other_field) pair
473 if (isset($cidRefs[$table])) {
474 foreach ($cidRefs[$table] as $field) {
475 // carry related contributions CRM-5359
476 if (in_array($table, $paymentTables)) {
477 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
478 $sqls = array_merge($sqls, $paymentSqls);
479
480 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
481 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
482 $sqls = array_merge($sqls, $payOprSqls);
483 }
484 }
485
486 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
487 $sqls = array_merge($sqls, $preOperationSqls);
488
489 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
490 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
491 }
492 }
493 if (isset($eidRefs[$table])) {
494 foreach ($eidRefs[$table] as $entityTable => $entityId) {
495 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
496 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
497 }
498 }
499 }
500
501 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
502 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
503
504 // call the SQL queries in one transaction
505 $transaction = new CRM_Core_Transaction();
506 foreach ($sqls as $sql) {
507 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE);
508 }
509 // CRM-12695
510 if ($membershipMerge) {
511 // call to function adding membership to related contacts
512 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
513 }
514 $transaction->commit();
515 }
516
517 /**
518 * Find differences between contacts.
519 *
520 * @param array $main
521 * Contact details.
522 * @param array $other
523 * Contact details.
524 *
525 * @return array
526 */
527 public static function findDifferences($main, $other) {
528 $result = array(
529 'contact' => array(),
530 'custom' => array(),
531 );
532 foreach (self::getContactFields() as $validField) {
533 if (CRM_Utils_Array::value($validField, $main) != CRM_Utils_Array::value($validField, $other)) {
534 $result['contact'][] = $validField;
535 }
536 }
537
538 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
539 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
540 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
541 foreach ($keys as $key) {
542 // Exclude multi-value fields CRM-13836
543 if (strpos($key, '_')) {
544 continue;
545 }
546 $key1 = CRM_Utils_Array::value($key, $mainEvs);
547 $key2 = CRM_Utils_Array::value($key, $otherEvs);
548 if ($key1 != $key2) {
549 $result['custom'][] = $key;
550 }
551 }
552 return $result;
553 }
554
555 /**
556 * Batch merge a set of contacts based on rule-group and group.
557 *
558 * @param int $rgid
559 * Rule group id.
560 * @param int $gid
561 * Group id.
562 * @param string $mode
563 * Helps decide how to behave when there are conflicts.
564 * A 'safe' value skips the merge if there are any un-resolved conflicts.
565 * Does a force merge otherwise.
566 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
567 * Wether to let api decide which contact to retain and which to delete.
568 * @param int $batchLimit number of merges to carry out in one batch.
569 * @param int $isSelected if records with is_selected column needs to be processed.
570 *
571 * @return array|bool
572 */
573 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $batchLimit = 1, $isSelected = 2) {
574 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
575 $cacheKeyString = "merge {$contactType}";
576 $cacheKeyString .= $rgid ? "_{$rgid}" : '_0';
577 $cacheKeyString .= $gid ? "_{$gid}" : '_0';
578 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
579 pn.entity_id2 = de.contact_id2 )";
580
581 $where = "de.id IS NULL";
582 if ($isSelected === 0 || $isSelected === 1) {
583 $where .= " AND pn.is_selected = {$isSelected}";
584 }// else consider all dupe pairs
585 $where .= " LIMIT {$batchLimit}";
586
587 $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
588
589 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
590 if (empty($dupePairs) && !$redirectForPerformance && $isSelected == 2) {
591 // If we haven't found any dupes, probably cache is empty.
592 // Try filling cache and give another try.
593 CRM_Core_BAO_PrevNextCache::refillCache($rgid, $gid, $cacheKeyString);
594 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
595 }
596
597 $cacheParams = array(
598 'cache_key_string' => $cacheKeyString,
599 'join' => $join,
600 'where' => $where,
601 );
602 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
603 }
604
605 public static function updateMergeStats($cacheKeyString, $result = array()) {
606 // gather latest stats
607 $merged = count($result['merged']);
608 $skipped = count($result['skipped']);
609
610 if ($merged <= 0 && $skipped <= 0) {
611 return;
612 }
613
614 // get previous stats
615 $previousStats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
616 if (!empty($previousStats)) {
617 if ($previousStats[0]['merged']) {
618 $merged = $merged + $previousStats[0]['merged'];
619 }
620 if ($previousStats[0]['skipped']) {
621 $skipped = $skipped + $previousStats[0]['skipped'];
622 }
623 }
624
625 // delete old stats
626 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
627
628 // store the updated stats
629 $data = array(
630 'merged' => $merged,
631 'skipped' => $skipped,
632 );
633 $data = CRM_Core_DAO::escapeString(serialize($data));
634
635 $values = array();
636 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
637 CRM_Core_BAO_PrevNextCache::setItem($values);
638 }
639
640 public static function resetMergeStats($cacheKeyString) {
641 return CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
642 }
643
644 public static function getMergeStats($cacheKeyString) {
645 $stats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
646 if (!empty($stats)) {
647 $stats = $stats[0];
648 }
649 return $stats;
650 }
651
652 public static function getMergeStatsMsg($cacheKeyString) {
653 $msg = '';
654 $stats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
655 if (!empty($stats['merged'])) {
656 $msg = "{$stats['merged']} " . ts(' Contact(s) were merged. ');
657 }
658 if (!empty($stats['skipped'])) {
659 $msg .= $stats['skipped'] . ts(' Contact(s) were skipped.');
660 }
661 return $msg;
662 }
663
664 /**
665 * Merge given set of contacts. Performs core operation.
666 *
667 * @param array $dupePairs
668 * Set of pair of contacts for whom merge is to be done.
669 * @param array $cacheParams
670 * Prev-next-cache params based on which next pair of contacts are computed.
671 * Generally used with batch-merge.
672 * @param string $mode
673 * Helps decide how to behave when there are conflicts.
674 * A 'safe' value skips the merge if there are any un-resolved conflicts.
675 * Does a force merge otherwise (aggressive mode).
676 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
677 * Wether to let api decide which contact to retain and which to delete.
678 *
679 *
680 * @param bool $redirectForPerformance
681 *
682 * @return array|bool
683 */
684 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
685 $autoFlip = TRUE, $redirectForPerformance = FALSE
686 ) {
687 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
688 $resultStats = array('merged' => array(), 'skipped' => array());
689
690 // we don't want dupe caching to get reset after every-merge, and therefore set the
691 // doNotResetCache flag
692 $config = CRM_Core_Config::singleton();
693 $config->doNotResetCache = 1;
694
695 while (!empty($dupePairs)) {
696 foreach ($dupePairs as $dupes) {
697 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
698 $mainId = $dupes['dstID'];
699 $otherId = $dupes['srcID'];
700 $isAutoFlip = CRM_Utils_Array::value('auto_flip', $dupes, $autoFlip);
701 // if we can, make sure that $mainId is the one with lower id number
702 if ($isAutoFlip && ($mainId > $otherId)) {
703 $mainId = $dupes['srcID'];
704 $otherId = $dupes['dstID'];
705 }
706 if (!$mainId || !$otherId) {
707 // return error
708 return FALSE;
709 }
710
711 // Generate var $migrationInfo. The variable structure is exactly same as
712 // $formValues submitted during a UI merge for a pair of contacts.
713 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId);
714
715 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
716
717 // add additional details that we might need to resolve conflicts
718 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
719 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
720 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
721 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
722
723 // go ahead with merge if there is no conflict
724 $conflicts = array();
725 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
726 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo);
727 $resultStats['merged'][] = array('main_id' => $mainId, 'other_id' => $otherId);
728 }
729 else {
730 $resultStats['skipped'][] = array('main_id' => $mainId, 'other_id' => $otherId);
731 }
732
733 // store any conflicts
734 if (!empty($conflicts)) {
735 foreach ($conflicts as $key => $dnc) {
736 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
737 }
738 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
739 }
740 else {
741 // delete entry from PrevNextCache table so we don't consider the pair next time
742 // pair may have been flipped, so make sure we delete using both orders
743 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
744 }
745
746 CRM_Core_DAO::freeResult();
747 unset($rowsElementsAndInfo, $migrationInfo);
748 }
749
750 if ($cacheKeyString && !$redirectForPerformance) {
751 // retrieve next pair of dupes
752 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
753 $cacheParams['join'],
754 $cacheParams['where']
755 );
756 }
757 else {
758 // do not proceed. Terminate the loop
759 unset($dupePairs);
760 }
761 }
762
763 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
764 return $resultStats;
765 }
766
767 /**
768 * A function which uses various rules / algorithms for choosing which contact to bias to
769 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
770 *
771 * @param int $mainId
772 * Main contact with whom merge has to happen.
773 * @param int $otherId
774 * Duplicate contact which would be deleted after merge operation.
775 * @param array $migrationInfo
776 * Array of information about which elements to merge.
777 * @param string $mode
778 * Helps decide how to behave when there are conflicts.
779 * A 'safe' value skips the merge if there are any un-resolved conflicts.
780 * Does a force merge otherwise (aggressive mode).
781 *
782 * @return bool
783 */
784 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
785 //$conflicts = array();
786 $migrationData = array(
787 'old_migration_info' => $migrationInfo,
788 'mode' => $mode,
789 );
790 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
791
792 foreach ($migrationInfo as $key => $val) {
793 if ($val === "null") {
794 // Rule: no overwriting with empty values in any mode
795 unset($migrationInfo[$key]);
796 continue;
797 }
798 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
799 substr($key, 0, 12) == 'move_custom_'
800 ) and $val != NULL
801 ) {
802 // Rule: if both main-contact has other-contact, let $mode decide if to merge a
803 // particular field or not
804 if (!empty($migrationInfo['rows'][$key]['main'])) {
805 // if main also has a value its a conflict
806
807 // note it down & lets wait for response from the hook.
808 // For no response $mode will decide if to skip this merge
809 $conflicts[$key] = NULL;
810 }
811 }
812 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
813 $locField = explode('_', $key);
814 $fieldName = $locField[2];
815 $fieldCount = $locField[3];
816
817 // Rule: resolve address conflict if any -
818 if ($fieldName == 'address') {
819 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
820 if (!empty($migrationInfo['main_loc_block']) &&
821 array_key_exists("main_address{$mainNewLocTypeId}", $migrationInfo['main_loc_block'])) {
822 // main loc already has some address for the loc-type. Its a overwrite situation.
823 // look for next available loc-type
824 $newTypeId = NULL;
825 foreach ($allLocationTypes as $typeId => $typeLabel) {
826 if (!array_key_exists("main_address{$typeId}", $migrationInfo['main_loc_block'])) {
827 $newTypeId = $typeId;
828 }
829 }
830 if ($newTypeId) {
831 // try insert address at new available loc-type
832 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
833 }
834 else {
835 // note it down & lets wait for response from the hook.
836 // For no response $mode will decide if to skip this merge
837 $conflicts[$key] = NULL;
838 }
839 }
840 }
841 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
842 // for loc blocks other than address like email, phone .. if values are same no point in merging
843 // and adding redundant value
844 unset($migrationInfo[$key]);
845 }
846 }
847 }
848
849 // A hook to implement other algorithms for choosing which contact to bias to when
850 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
851 // merge happens with new values filled in here. For a particular field / row not to be merged
852 // field should be unset from fields_in_conflict.
853 $migrationData['fields_in_conflict'] = $conflicts;
854 $migrationData['merge_mode'] = $mode;
855 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
856 $conflicts = $migrationData['fields_in_conflict'];
857 // allow hook to override / manipulate migrationInfo as well
858 $migrationInfo = $migrationData['old_migration_info'];
859
860 if (!empty($conflicts)) {
861 foreach ($conflicts as $key => $val) {
862 if ($val === NULL and $mode == 'safe') {
863 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
864 return TRUE;
865 }
866 else {
867 // copy over the resolved values
868 $migrationInfo[$key] = $val;
869 }
870 }
871 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
872 if (array_key_exists('skip_merge', $migrationData)) {
873 return (bool) $migrationData['skip_merge'];
874 }
875 }
876 return FALSE;
877 }
878
879 /**
880 * A function to build an array of information required by merge function and the merge UI.
881 *
882 * @param int $mainId
883 * Main contact with whom merge has to happen.
884 * @param int $otherId
885 * Duplicate contact which would be deleted after merge operation.
886 *
887 * @return array|bool|int
888 */
889 public static function getRowsElementsAndInfo($mainId, $otherId) {
890 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
891
892 // Fetch contacts
893 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
894 $params = array(
895 'contact_id' => $cid,
896 'version' => 3,
897 'return' => array_merge(array('display_name'), self::getContactFields()),
898 );
899 $result = civicrm_api('contact', 'get', $params);
900
901 if (empty($result['values'][$cid]['contact_type'])) {
902 return FALSE;
903 }
904 $$moniker = $result['values'][$cid];
905 }
906
907 static $fields = array();
908 if (empty($fields)) {
909 $fields = CRM_Contact_DAO_Contact::fields();
910 CRM_Core_DAO::freeResult();
911 }
912
913 // FIXME: there must be a better way
914 foreach (array('main', 'other') as $moniker) {
915 $contact = &$$moniker;
916 $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
917 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
918 $specialValues[$moniker] = array(
919 'preferred_communication_method' => $value,
920 'communication_style_id' => $value,
921 );
922
923 if (!empty($contact['preferred_communication_method'])) {
924 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
925 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
926 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
927 }
928 $names = array(
929 'preferred_communication_method' => array(
930 'newName' => 'preferred_communication_method_display',
931 'groupName' => 'preferred_communication_method',
932 ),
933 );
934 CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
935
936 if (!empty($contact['communication_style'])) {
937 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
938 }
939 }
940
941 static $optionValueFields = array();
942 if (empty($optionValueFields)) {
943 $optionValueFields = CRM_Core_OptionValue::getFields();
944 }
945 foreach ($optionValueFields as $field => $params) {
946 $fields[$field]['title'] = $params['title'];
947 }
948
949 $diffs = self::findDifferences($main, $other);
950
951 $rows = $elements = $relTableElements = $migrationInfo = array();
952
953 $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
954
955 foreach ($diffs['contact'] as $field) {
956 if ($field == 'contact_sub_type') {
957 // CRM-15681 don't display sub-types in UI
958 continue;
959 }
960 foreach (array('main', 'other') as $moniker) {
961 $contact = &$$moniker;
962 $value = CRM_Utils_Array::value($field, $contact);
963 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
964 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
965 }
966 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
967 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
968 if ($value) {
969 $value = str_replace('-', '', $value);
970 $label = CRM_Utils_Date::customFormat($label);
971 }
972 else {
973 $value = "null";
974 }
975 }
976 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
977 if ($label === '0') {
978 $label = ts('[ ]');
979 }
980 if ($label === '1') {
981 $label = ts('[x]');
982 }
983 }
984 elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
985 $label = CRM_Utils_Array::value('individual_prefix', $contact);
986 $value = CRM_Utils_Array::value('prefix_id', $contact);
987 $field = 'prefix_id';
988 }
989 elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
990 $label = CRM_Utils_Array::value('individual_suffix', $contact);
991 $value = CRM_Utils_Array::value('suffix_id', $contact);
992 $field = 'suffix_id';
993 }
994 elseif ($field == 'gender_id' && !empty($value)) {
995 $label = $genders[$value];
996 }
997 elseif ($field == 'current_employer_id' && !empty($value)) {
998 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
999 }
1000 $rows["move_$field"][$moniker] = $label;
1001 if ($moniker == 'other') {
1002 //CRM-14334
1003 if ($value === NULL || $value == '') {
1004 $value = 'null';
1005 }
1006 if ($value === 0 or $value === '0') {
1007 $value = $qfZeroBug;
1008 }
1009 if (is_array($value) && empty($value[1])) {
1010 $value[1] = NULL;
1011 }
1012 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1013 $migrationInfo["move_$field"] = $value;
1014 }
1015 }
1016 $rows["move_$field"]['title'] = $fields[$field]['title'];
1017 }
1018
1019 // handle location blocks.
1020 $locationBlocks = array('email', 'phone', 'address');
1021 $locations = array();
1022
1023 foreach ($locationBlocks as $block) {
1024 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
1025 $cnt = 1;
1026 $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
1027 $count = $values['count'];
1028 if ($count) {
1029 if ($count > $cnt) {
1030 foreach ($values['values'] as $value) {
1031 if ($block == 'address') {
1032 CRM_Core_BAO_Address::fixAddress($value);
1033 $display = CRM_Utils_Address::format($value);
1034 $locations[$moniker][$block][$cnt] = $value;
1035 $locations[$moniker][$block][$cnt]['display'] = $display;
1036 }
1037 else {
1038 $locations[$moniker][$block][$cnt] = $value;
1039 }
1040
1041 $cnt++;
1042 }
1043 }
1044 else {
1045 $id = $values['id'];
1046 if ($block == 'address') {
1047 CRM_Core_BAO_Address::fixAddress($values['values'][$id]);
1048 $display = CRM_Utils_Address::format($values['values'][$id]);
1049 $locations[$moniker][$block][$cnt] = $values['values'][$id];
1050 $locations[$moniker][$block][$cnt]['display'] = $display;
1051 }
1052 else {
1053 $locations[$moniker][$block][$cnt] = $values['values'][$id];
1054 }
1055 }
1056 }
1057 }
1058 }
1059
1060 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
1061
1062 $mainLocBlock = $locBlockIds = array();
1063 $locBlockIds['main'] = $locBlockIds['other'] = array();
1064 foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
1065 $name = strtolower($block);
1066 foreach (array('main', 'other') as $moniker) {
1067 $locIndex = CRM_Utils_Array::value($moniker, $locations);
1068 $blockValue = CRM_Utils_Array::value($name, $locIndex, array());
1069 if (empty($blockValue)) {
1070 $locValue[$moniker][$name] = 0;
1071 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
1072 }
1073 else {
1074 $locValue[$moniker][$name] = TRUE;
1075 foreach ($blockValue as $count => $blkValues) {
1076 $fldName = $name;
1077 $locTypeId = $blkValues['location_type_id'];
1078 if ($name == 'im') {
1079 $fldName = 'name';
1080 }
1081 if ($name == 'address') {
1082 $fldName = 'display';
1083 }
1084 $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName,
1085 $blkValues
1086 );
1087 $locTypes[$moniker][$name][$count] = $locTypeId;
1088 if ($moniker == 'main' && in_array($name, $locationBlocks)) {
1089 $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array::value($fldName,
1090 $blkValues
1091 );
1092 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
1093 }
1094 else {
1095 $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
1096 }
1097 }
1098 }
1099 }
1100
1101 if ($locValue['other'][$name] != 0) {
1102 foreach ($locLabel['other'][$name] as $count => $value) {
1103 $locTypeId = $locTypes['other'][$name][$count];
1104 $rows["move_location_{$name}_$count"]['other'] = $value;
1105 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array::value($count,
1106 $locLabel['main'][$name]
1107 );
1108 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
1109 array(
1110 1 => $block,
1111 2 => $count,
1112 3 => $allLocationTypes[$locTypeId],
1113 )
1114 );
1115
1116 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
1117 $migrationInfo["move_location_{$name}_{$count}"] = 1;
1118
1119 // make sure default location type is always on top
1120 $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId);
1121 $locTypeValues = $allLocationTypes;
1122 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
1123 unset($locTypeValues[$mainLocTypeId]);
1124
1125 // keep 1-1 mapping for address - location type.
1126 $js = NULL;
1127 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
1128 $js = array('onChange' => "mergeBlock('$name', this, $count );");
1129 }
1130 $elements[] = array(
1131 'select',
1132 "location[{$name}][$count][locTypeId]",
1133 NULL,
1134 $defaultLocType + $locTypeValues,
1135 $js,
1136 );
1137 // keep location-type-id same as that of other-contact
1138 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
1139
1140 if ($name != 'address') {
1141 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
1142 // always use add operation
1143 $migrationInfo['location'][$name][$count]['operation'] = 1;
1144 }
1145 }
1146 }
1147 }
1148
1149 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1150 $config = CRM_Core_Config::singleton();
1151 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1152 $mainUser = NULL;
1153 if ($mainUfId) {
1154 // d6 compatible
1155 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1156 $mainUser = user_load($mainUfId);
1157 }
1158 elseif ($config->userFramework == 'Joomla') {
1159 $mainUser = JFactory::getUser($mainUfId);
1160 }
1161 }
1162 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1163 $otherUser = NULL;
1164 if ($otherUfId) {
1165 // d6 compatible
1166 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1167 $otherUser = user_load($otherUfId);
1168 }
1169 elseif ($config->userFramework == 'Joomla') {
1170 $otherUser = JFactory::getUser($otherUfId);
1171 }
1172 }
1173
1174 $relTables = CRM_Dedupe_Merger::relTables();
1175 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1176 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1177 foreach ($relTables as $name => $null) {
1178 if (!in_array($name, $activeRelTables) &&
1179 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1180 ) {
1181 unset($relTables[$name]);
1182 continue;
1183 }
1184
1185 $relTableElements[] = array('checkbox', "move_$name");
1186 $migrationInfo["move_$name"] = 1;
1187
1188 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1189 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1190 if ($name == 'rel_table_users') {
1191 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1192 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1193 $find = array('$ufid', '$ufname');
1194 if ($mainUser) {
1195 $replace = array($mainUfId, $mainUser->name);
1196 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1197 }
1198 if ($otherUser) {
1199 $replace = array($otherUfId, $otherUser->name);
1200 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1201 }
1202 }
1203 if ($name == 'rel_table_memberships') {
1204 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1205 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1206 }
1207 }
1208 foreach ($relTables as $name => $null) {
1209 $relTables["move_$name"] = $relTables[$name];
1210 unset($relTables[$name]);
1211 }
1212
1213 // handle custom fields
1214 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1,
1215 CRM_Utils_Array::value('contact_sub_type', $main)
1216 );
1217 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1,
1218 CRM_Utils_Array::value('contact_sub_type', $other)
1219 );
1220 CRM_Core_DAO::freeResult();
1221
1222 foreach ($otherTree as $gid => $group) {
1223 $foundField = FALSE;
1224 if (!isset($group['fields'])) {
1225 continue;
1226 }
1227
1228 foreach ($group['fields'] as $fid => $field) {
1229 if (in_array($fid, $diffs['custom'])) {
1230 if (!$foundField) {
1231 $rows["custom_group_$gid"]['title'] = $group['title'];
1232 $foundField = TRUE;
1233 }
1234 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1235 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1236 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1237 $field, TRUE
1238 );
1239 }
1240 }
1241 $value = "null";
1242 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1243 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1244 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1245 $field, TRUE
1246 );
1247 if ($values['data'] === 0 || $values['data'] === '0') {
1248 $values['data'] = $qfZeroBug;
1249 }
1250 $value = ($values['data']) ? $values['data'] : $value;
1251 }
1252 }
1253 $rows["move_custom_$fid"]['title'] = $field['label'];
1254
1255 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1256 $migrationInfo["move_custom_$fid"] = $value;
1257 }
1258 }
1259 }
1260 $result = array(
1261 'rows' => $rows,
1262 'elements' => $elements,
1263 'rel_table_elements' => $relTableElements,
1264 'main_loc_block' => $mainLocBlock,
1265 'rel_tables' => $relTables,
1266 'main_details' => $main,
1267 'other_details' => $other,
1268 'migration_info' => $migrationInfo,
1269 );
1270
1271 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1272 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1273
1274 return $result;
1275 }
1276
1277 /**
1278 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1279 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1280 * A superset of moveContactBelongings() function.
1281 *
1282 * @param int $mainId
1283 * Main contact with whom merge has to happen.
1284 * @param int $otherId
1285 * Duplicate contact which would be deleted after merge operation.
1286 *
1287 * @param $migrationInfo
1288 *
1289 * @return bool
1290 */
1291 public static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1292 if (empty($migrationInfo)) {
1293 return FALSE;
1294 }
1295
1296 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1297 $relTables = CRM_Dedupe_Merger::relTables();
1298 $moveTables = $locBlocks = $tableOperations = array();
1299 foreach ($migrationInfo as $key => $value) {
1300 if ($value == $qfZeroBug) {
1301 $value = '0';
1302 }
1303 if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) ||
1304 substr($key, 0, 12) == 'move_custom_') &&
1305 $value != NULL
1306 ) {
1307 $submitted[substr($key, 5)] = $value;
1308 }
1309 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1310 $locField = explode('_', $key);
1311 $fieldName = $locField[2];
1312 $fieldCount = $locField[3];
1313 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1314 // default operation is overwrite.
1315 if (!$operation) {
1316 $operation = 2;
1317 }
1318
1319 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1320 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1321 }
1322 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1323 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1324 if (array_key_exists('operation', $migrationInfo)) {
1325 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1326 if (array_key_exists($key, $migrationInfo['operation'])) {
1327 $tableOperations[$table] = $migrationInfo['operation'][$key];
1328 }
1329 }
1330 }
1331 }
1332 }
1333
1334 // **** Do location related migration:
1335 if (!empty($locBlocks)) {
1336 $locComponent = array(
1337 'email' => 'Email',
1338 'phone' => 'Phone',
1339 'im' => 'IM',
1340 'openid' => 'OpenID',
1341 'address' => 'Address',
1342 );
1343
1344 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
1345 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
1346
1347 foreach ($locBlocks as $name => $block) {
1348 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1349 continue;
1350 }
1351 $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
1352 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1353 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1354
1355 foreach ($block as $blkCount => $values) {
1356 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
1357 $operation = CRM_Utils_Array::value('operation', $values, 2);
1358 $otherBlockId = CRM_Utils_Array::value($blkCount,
1359 $migrationInfo['other_details']['loc_block_ids'][$name]
1360 );
1361
1362 // keep 1-1 mapping for address - loc type.
1363 $idKey = $blkCount;
1364 if (array_key_exists($name, $locComponent)) {
1365 $idKey = $locTypeId;
1366 }
1367
1368 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1369 $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1370 }
1371
1372 if (!$otherBlockId) {
1373 continue;
1374 }
1375
1376 // for the block which belongs to other-contact, link the contact to main-contact
1377 $otherBlockDAO = new $daoName();
1378 $otherBlockDAO->id = $otherBlockId;
1379 $otherBlockDAO->contact_id = $mainId;
1380 $otherBlockDAO->location_type_id = $locTypeId;
1381
1382 // if main contact already has primary & billing, set the flags to 0.
1383 if ($primaryDAOId) {
1384 $otherBlockDAO->is_primary = 0;
1385 }
1386 if ($billingDAOId) {
1387 $otherBlockDAO->is_billing = 0;
1388 }
1389
1390 // overwrite - need to delete block which belongs to main-contact.
1391 if (isset($mainBlockId) && $mainBlockId && ($operation == 2)) {
1392 $deleteDAO = new $daoName();
1393 $deleteDAO->id = $mainBlockId;
1394 $deleteDAO->find(TRUE);
1395
1396 // if we about to delete a primary / billing block, set the flags for new block
1397 // that we going to assign to main-contact
1398 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1399 $otherBlockDAO->is_primary = 1;
1400 }
1401 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1402 $otherBlockDAO->is_billing = 1;
1403 }
1404
1405 $deleteDAO->delete();
1406 $deleteDAO->free();
1407 }
1408
1409 $otherBlockDAO->update();
1410 $otherBlockDAO->free();
1411 }
1412 }
1413 }
1414
1415 // **** Do tables related migrations
1416 if (!empty($moveTables)) {
1417 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1418 unset($moveTables, $tableOperations);
1419 }
1420
1421 // **** Do contact related migrations
1422 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
1423
1424 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1425 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1426 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1427 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1428 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1429 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1430 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1431 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1432 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1433
1434 // fix custom fields so they're edible by createProfileContact()
1435 static $treeCache = array();
1436 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1437 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'],
1438 CRM_Core_DAO::$_nullObject, NULL, -1
1439 );
1440 }
1441 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1442
1443 $cFields = array();
1444 foreach ($cgTree as $key => $group) {
1445 if (!isset($group['fields'])) {
1446 continue;
1447 }
1448 foreach ($group['fields'] as $fid => $field) {
1449 $cFields[$fid]['attributes'] = $field;
1450 }
1451 }
1452
1453 if (!isset($submitted)) {
1454 $submitted = array();
1455 }
1456 foreach ($submitted as $key => $value) {
1457 if (substr($key, 0, 7) == 'custom_') {
1458 $fid = (int) substr($key, 7);
1459 if (empty($cFields[$fid])) {
1460 continue;
1461 }
1462 $htmlType = $cFields[$fid]['attributes']['html_type'];
1463 switch ($htmlType) {
1464 case 'File':
1465 $customFiles[] = $fid;
1466 unset($submitted["custom_$fid"]);
1467 break;
1468
1469 case 'Select Country':
1470 case 'Select State/Province':
1471 $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
1472 break;
1473
1474 case 'CheckBox':
1475 case 'AdvMulti-Select':
1476 case 'Multi-Select':
1477 case 'Multi-Select Country':
1478 case 'Multi-Select State/Province':
1479 // Merge values from both contacts for multivalue fields, CRM-4385
1480 // get the existing custom values from db.
1481 $customParams = array('entityID' => $mainId, $key => TRUE);
1482 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
1483 if (!empty($customfieldValues[$key])) {
1484 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1485 if (is_array($existingValue) && !empty($existingValue)) {
1486 $mergeValue = $submmtedCustomValue = array();
1487 if ($value) {
1488 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1489 }
1490
1491 //hack to remove null and duplicate values from array.
1492 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1493 if ($v != '' && !in_array($v, $mergeValue)) {
1494 $mergeValue[] = $v;
1495 }
1496 }
1497
1498 //keep state and country as array format.
1499 //for checkbox and m-select format w/ VALUE_SEPARATOR
1500 if (in_array($htmlType, array(
1501 'CheckBox',
1502 'Multi-Select',
1503 'AdvMulti-Select',
1504 ))) {
1505 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1506 $mergeValue
1507 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1508 }
1509 else {
1510 $submitted[$key] = $mergeValue;
1511 }
1512 }
1513 }
1514 elseif (in_array($htmlType, array(
1515 'Multi-Select Country',
1516 'Multi-Select State/Province',
1517 ))) {
1518 //we require submitted values should be in array format
1519 if ($value) {
1520 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1521 //hack to remove null values from array.
1522 $mergeValue = array();
1523 foreach ($mergeValueArray as $k => $v) {
1524 if ($v != '') {
1525 $mergeValue[] = $v;
1526 }
1527 }
1528 $submitted[$key] = $mergeValue;
1529 }
1530 }
1531 break;
1532
1533 default:
1534 break;
1535 }
1536 }
1537 }
1538
1539 // **** Do file custom fields related migrations
1540 // FIXME: move this someplace else (one of the BAOs) after discussing
1541 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1542 // like, delete a file...
1543
1544 if (!isset($customFiles)) {
1545 $customFiles = array();
1546 }
1547 foreach ($customFiles as $customId) {
1548 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1549
1550 // get the contact_id -> file_id mapping
1551 $fileIds = array();
1552 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1553 $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1554 while ($dao->fetch()) {
1555 $fileIds[$dao->entity_id] = $dao->file_id;
1556 }
1557 $dao->free();
1558
1559 // delete the main contact's file
1560 if (!empty($fileIds[$mainId])) {
1561 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1562 }
1563
1564 // move the other contact's file to main contact
1565 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1566 if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
1567 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1568 }
1569 else {
1570 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1571 }
1572 CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1573
1574 if (CRM_Core_DAO::singleValueQuery("
1575 SELECT id
1576 FROM civicrm_entity_file
1577 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1578 ) {
1579 $sql = "
1580 UPDATE civicrm_entity_file
1581 SET entity_id = {$mainId}
1582 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1583 }
1584 else {
1585 $sql = "
1586 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1587 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1588 }
1589 CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1590 }
1591
1592 // move view only custom fields CRM-5362
1593 $viewOnlyCustomFields = array();
1594 foreach ($submitted as $key => $value) {
1595 $fid = (int) substr($key, 7);
1596 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1597 $viewOnlyCustomFields[$key] = $value;
1598 }
1599 }
1600
1601 // special case to set values for view only, CRM-5362
1602 if (!empty($viewOnlyCustomFields)) {
1603 $viewOnlyCustomFields['entityID'] = $mainId;
1604 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1605 }
1606
1607 // **** Delete other contact & update prev-next caching
1608 $otherParams = array(
1609 'contact_id' => $otherId,
1610 'id' => $otherId,
1611 'version' => 3,
1612 );
1613 if (CRM_Core_Permission::check('merge duplicate contacts') &&
1614 CRM_Core_Permission::check('delete contacts')
1615 ) {
1616 // if ext id is submitted then set it null for contact to be deleted
1617 if (!empty($submitted['external_identifier'])) {
1618 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1619 CRM_Core_DAO::executeQuery($query);
1620 }
1621
1622 civicrm_api('contact', 'delete', $otherParams);
1623 CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
1624 }
1625 // FIXME: else part
1626 /* else { */
1627
1628 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1629
1630 /* } */
1631
1632 // CRM-15681 merge sub_types
1633 if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
1634 if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
1635 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1636 }
1637 else {
1638 $submitted['contact_sub_type'] = $other_sub_types;
1639 }
1640 }
1641
1642 // **** Update contact related info for the main contact
1643 if (!empty($submitted)) {
1644 $submitted['contact_id'] = $mainId;
1645
1646 //update current employer field
1647 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1648 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1649 $submitted['current_employer'] = $submitted['current_employer_id'];
1650 }
1651 else {
1652 $submitted['current_employer'] = '';
1653 }
1654 unset($submitted['current_employer_id']);
1655 }
1656
1657 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1658 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1659 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1660 }
1661 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1662 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1663 }
1664
1665 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
1666 unset($submitted);
1667 }
1668
1669 CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
1670
1671 return TRUE;
1672 }
1673
1674 /**
1675 * @return array
1676 * Array of field names which will be compared, so everything except ID.
1677 */
1678 public static function getContactFields() {
1679 $contactFields = CRM_Contact_DAO_Contact::fields();
1680 $invalidFields = array(
1681 'api_key',
1682 'contact_is_deleted',
1683 'created_date',
1684 'display_name',
1685 'hash',
1686 'id',
1687 'modified_date',
1688 'primary_contact_id',
1689 'sort_name',
1690 'user_unique_id',
1691 );
1692 foreach ($contactFields as $field => $value) {
1693 if (in_array($field, $invalidFields)) {
1694 unset($contactFields[$field]);
1695 }
1696 }
1697 return array_keys($contactFields);
1698 }
1699
1700 /**
1701 * Added for CRM-12695
1702 * Based on the contactID provided
1703 * add/update membership(s) to related contacts
1704 *
1705 * @param int $contactID
1706 */
1707 public static function addMembershipToRealtedContacts($contactID) {
1708 $dao = new CRM_Member_DAO_Membership();
1709 $dao->contact_id = $contactID;
1710 $dao->is_test = 0;
1711 $dao->find();
1712
1713 //checks membership of contact itself
1714 while ($dao->fetch()) {
1715 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1716 if ($relationshipTypeId) {
1717 $membershipParams = array(
1718 'id' => $dao->id,
1719 'contact_id' => $dao->contact_id,
1720 'membership_type_id' => $dao->membership_type_id,
1721 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1722 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1723 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1724 'source' => $dao->source,
1725 'status_id' => $dao->status_id,
1726 );
1727 // create/update membership(s) for related contact(s)
1728 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1729 } // end of if relationshipTypeId
1730 }
1731 }
1732
1733}