Merge pull request #5057 from cividesk/CRM-15901-4.5
[civicrm-core.git] / CRM / Dedupe / Merger.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35 class CRM_Dedupe_Merger {
36
37 // FIXME: consider creating a common structure with cidRefs() and eidRefs()
38 // FIXME: the sub-pages references by the URLs should
39 // be loaded dynamically on the merge form instead
40 /**
41 * @return array
42 */
43 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 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 static function cidRefs() {
195 static $cidRefs;
196 if (!$cidRefs) {
197 $sql = "
198 SELECT
199 table_name,
200 column_name
201 FROM information_schema.key_column_usage
202 WHERE
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 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 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 'relTables' or 'cidRefs'
262 * @see CRM-13836
263 */
264 static function getMultiValueCustomSets($request) {
265 static $data = NULL;
266 if ($data === NULL) {
267 $data = array(
268 'relTables' => array(),
269 'cidRefs' => array(),
270 );
271 $result = civicrm_api3('custom_group', 'get', array(
272 'is_multiple' => 1,
273 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
274 'return' => array('id', 'title', 'table_name', 'style'),
275 ));
276 foreach($result['values'] as $custom) {
277 $data['cidRefs'][$custom['table_name']] = array('entity_id');
278 $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
279 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
280 'title' => $custom['title'],
281 'tables' => array($custom['table_name']),
282 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
283 );
284 }
285 }
286 return $data[$request];
287 }
288
289 /**
290 * Tables which require custom processing should declare functions to call here.
291 * Doing so will override normal processing.
292 */
293 static function cpTables() {
294 static $tables;
295 if (!$tables) {
296 $tables = array(
297 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
298 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
299 // Empty array == do nothing - this table is handled by mergeGroupContact
300 'civicrm_subscription_history' => array(),
301 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
302 );
303 }
304 return $tables;
305 }
306
307 /**
308 * return payment related table.
309 */
310 static function paymentTables() {
311 static $tables;
312 if (!$tables) {
313 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
314 }
315
316 return $tables;
317 }
318
319 /**
320 * return payment update Query.
321 */
322 static function paymentSql($tableName, $mainContactId, $otherContactId) {
323 $sqls = array();
324 if (!$tableName || !$mainContactId || !$otherContactId) {
325 return $sqls;
326 }
327
328 $paymentTables = self::paymentTables();
329 if (!in_array($tableName, $paymentTables)) {
330 return $sqls;
331 }
332
333 switch ($tableName) {
334 case 'civicrm_pledge':
335 $sqls[] = "
336 UPDATE IGNORE civicrm_contribution contribution
337 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
338 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
339 SET contribution.contact_id = $mainContactId
340 WHERE pledge.contact_id = $otherContactId";
341 break;
342
343 case 'civicrm_membership':
344 $sqls[] = "
345 UPDATE IGNORE civicrm_contribution contribution
346 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
347 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
348 SET contribution.contact_id = $mainContactId
349 WHERE membership.contact_id = $otherContactId";
350 break;
351
352 case 'civicrm_participant':
353 $sqls[] = "
354 UPDATE IGNORE civicrm_contribution contribution
355 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
356 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
357 SET contribution.contact_id = $mainContactId
358 WHERE participant.contact_id = $otherContactId";
359 break;
360 }
361
362 return $sqls;
363 }
364
365 /**
366 * @param $mainId
367 * @param $otherId
368 * @param $tableName
369 * @param array $tableOperations
370 * @param string $mode
371 *
372 * @return array
373 */
374 static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
375 $sqls = array();
376 if (!$tableName || !$mainId || !$otherId) {
377 return $sqls;
378 }
379
380
381 switch ($tableName) {
382 case 'civicrm_membership':
383 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add'])
384 break;
385 if ($mode == 'add') {
386 $sqls[] = "
387 DELETE membership1.* FROM civicrm_membership membership1
388 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
389 AND membership1.contact_id = {$mainId}
390 AND membership2.contact_id = {$otherId} ";
391 }
392 if ($mode == 'payment') {
393 $sqls[] = "
394 DELETE contribution.* FROM civicrm_contribution contribution
395 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
396 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
397 AND membership1.contact_id = {$mainId}
398 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
399 AND membership2.contact_id = {$otherId}";
400 }
401 break;
402
403 case 'civicrm_uf_match':
404 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
405 // failing to meet intended result. Therefore we introduce this additonal query:
406 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
407 break;
408 }
409
410 return $sqls;
411 }
412
413 /**
414 * Based on the provided two contact_ids and a set of tables, move the
415 * belongings of the other contact to the main one.
416 *
417 * @static
418 */
419 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 contact details
521 * @param array $other contact details
522 *
523 * @return array
524 * @static
525 */
526 static function findDifferences($main, $other) {
527 $result = array(
528 'contact' => array(),
529 'custom' => array(),
530 );
531 foreach (self::getContactFields() as $validField) {
532 if (CRM_Utils_Array::value($validField, $main) != CRM_Utils_Array::value($validField, $other)) {
533 $result['contact'][] = $validField;
534 }
535 }
536
537 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
538 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
539 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
540 foreach ($keys as $key) {
541 // Exclude multi-value fields CRM-13836
542 if (strpos($key, '_')) {
543 continue;
544 }
545 $key1 = CRM_Utils_Array::value($key, $mainEvs);
546 $key2 = CRM_Utils_Array::value($key, $otherEvs);
547 if ($key1 != $key2) {
548 $result['custom'][] = $key;
549 }
550 }
551 return $result;
552 }
553
554 /**
555 * Function to batch merge a set of contacts based on rule-group and group.
556 *
557 * @param int $rgid rule group id
558 * @param int $gid group id
559 * @param string $mode helps decide how to behave when there are conflicts.
560 * A 'safe' value skips the merge if there are any un-resolved conflicts.
561 * Does a force merge otherwise.
562 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
563 *
564 *
565 * @param bool $redirectForPerformance
566 *
567 * @return array|bool
568 * @internal param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
569 * Generally used with batch-merge.
570 * @static
571 * @access public
572 */
573 static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $redirectForPerformance = FALSE) {
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 $limit = $redirectForPerformance ? 75 : 1;
582 $where = "de.id IS NULL LIMIT {$limit}";
583
584 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
585 if (empty($dupePairs) && !$redirectForPerformance) {
586 // If we haven't found any dupes, probably cache is empty.
587 // Try filling cache and give another try.
588 CRM_Core_BAO_PrevNextCache::refillCache($rgid, $gid, $cacheKeyString);
589 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
590 }
591
592 $cacheParams = array(
593 'cache_key_string' => $cacheKeyString,
594 'join' => $join,
595 'where' => $where,
596 );
597 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
598 }
599
600 /**
601 * Function to merge given set of contacts. Performs core operation.
602 *
603 * @param array $dupePairs set of pair of contacts for whom merge is to be done.
604 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
605 * Generally used with batch-merge.
606 * @param string $mode helps decide how to behave when there are conflicts.
607 * A 'safe' value skips the merge if there are any un-resolved conflicts.
608 * Does a force merge otherwise (aggressive mode).
609 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
610 *
611 *
612 * @param bool $redirectForPerformance
613 *
614 * @return array|bool
615 * @static
616 * @access public
617 */
618 static function merge($dupePairs = array(
619 ), $cacheParams = array(), $mode = 'safe',
620 $autoFlip = TRUE, $redirectForPerformance = FALSE
621 ) {
622 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
623 $resultStats = array('merged' => array(), 'skipped' => array());
624
625 // we don't want dupe caching to get reset after every-merge, and therefore set the
626 // doNotResetCache flag
627 $config = CRM_Core_Config::singleton();
628 $config->doNotResetCache = 1;
629
630 while (!empty($dupePairs)) {
631 foreach ($dupePairs as $dupes) {
632 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
633 $mainId = $dupes['dstID'];
634 $otherId = $dupes['srcID'];
635 $isAutoFlip = CRM_Utils_Array::value('auto_flip', $dupes, $autoFlip);
636 // if we can, make sure that $mainId is the one with lower id number
637 if ($isAutoFlip && ($mainId > $otherId)) {
638 $mainId = $dupes['srcID'];
639 $otherId = $dupes['dstID'];
640 }
641 if (!$mainId || !$otherId) {
642 // return error
643 return FALSE;
644 }
645
646 // Generate var $migrationInfo. The variable structure is exactly same as
647 // $formValues submitted during a UI merge for a pair of contacts.
648 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId);
649
650 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
651
652 // add additional details that we might need to resolve conflicts
653 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
654 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
655 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
656 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
657
658 // go ahead with merge if there is no conflict
659 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode)) {
660 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo);
661 $resultStats['merged'][] = array('main_id' => $mainId, 'other_id' => $otherId);
662 }
663 else {
664 $resultStats['skipped'][] = array('main_id' => $mainId, 'other_id' => $otherId);
665 }
666
667 // delete entry from PrevNextCache table so we don't consider the pair next time
668 // pair may have been flipped, so make sure we delete using both orders
669 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString);
670 CRM_Core_BAO_PrevNextCache::deletePair($otherId, $mainId, $cacheKeyString);
671
672 CRM_Core_DAO::freeResult();
673 unset($rowsElementsAndInfo, $migrationInfo);
674 }
675
676 if ($cacheKeyString && !$redirectForPerformance) {
677 // retrieve next pair of dupes
678 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
679 $cacheParams['join'],
680 $cacheParams['where']
681 );
682 }
683 else {
684 // do not proceed. Terminate the loop
685 unset($dupePairs);
686 }
687 }
688 return $resultStats;
689 }
690
691 /**
692 * A function which uses various rules / algorithms for choosing which contact to bias to
693 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
694 *
695 * @param int $mainId main contact with whom merge has to happen
696 * @param int $otherId duplicate contact which would be deleted after merge operation
697 * @param array $migrationInfo array of information about which elements to merge.
698 * @param string $mode helps decide how to behave when there are conflicts.
699 * A 'safe' value skips the merge if there are any un-resolved conflicts.
700 * Does a force merge otherwise (aggressive mode).
701 *
702 * @return bool
703 * @static
704 * @access public
705 */
706 static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe') {
707 $conflicts = array();
708 $migrationData = array(
709 'old_migration_info' => $migrationInfo,
710 'mode' => $mode,
711 );
712 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
713
714 foreach ($migrationInfo as $key => $val) {
715 if ($val === "null") {
716 // Rule: no overwriting with empty values in any mode
717 unset($migrationInfo[$key]);
718 continue;
719 }
720 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
721 substr($key, 0, 12) == 'move_custom_'
722 ) and $val != NULL) {
723 // Rule: if both main-contact has other-contact, let $mode decide if to merge a
724 // particular field or not
725 if (!empty($migrationInfo['rows'][$key]['main'])) {
726 // if main also has a value its a conflict
727 if ($mode == 'safe') {
728 // note it down & lets wait for response from the hook.
729 // For no response skip this merge
730 $conflicts[$key] = NULL;
731 }
732 elseif ($mode == 'aggressive') {
733 // let the main-field be overwritten
734 continue;
735 }
736 }
737 }
738 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
739 $locField = explode('_', $key);
740 $fieldName = $locField[2];
741 $fieldCount = $locField[3];
742
743 // Rule: resolve address conflict if any -
744 if ($fieldName == 'address') {
745 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
746 if (!empty($migrationInfo['main_loc_block']) &&
747 array_key_exists("main_address{$mainNewLocTypeId}", $migrationInfo['main_loc_block'])) {
748 // main loc already has some address for the loc-type. Its a overwrite situation.
749
750 // look for next available loc-type
751 $newTypeId = NULL;
752 foreach ($allLocationTypes as $typeId => $typeLabel) {
753 if (!array_key_exists("main_address{$typeId}", $migrationInfo['main_loc_block'])) {
754 $newTypeId = $typeId;
755 }
756 }
757 if ($newTypeId) {
758 // try insert address at new available loc-type
759 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
760 }
761 elseif ($mode == 'safe') {
762 // note it down & lets wait for response from the hook.
763 // For no response skip this merge
764 $conflicts[$key] = NULL;
765 }
766 elseif ($mode == 'aggressive') {
767 // let the loc-type-id be same as that of other-contact & go ahead
768 // with merge assuming aggressive mode
769 continue;
770 }
771 }
772 }
773 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
774 // for loc blocks other than address like email, phone .. if values are same no point in merging
775 // and adding redundant value
776 unset($migrationInfo[$key]);
777 }
778 }
779 }
780
781 // A hook to implement other algorithms for choosing which contact to bias to when
782 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
783 // merge happens with new values filled in here. For a particular field / row not to be merged
784 // field should be unset from fields_in_conflict.
785 $migrationData['fields_in_conflict'] = $conflicts;
786 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
787 $conflicts = $migrationData['fields_in_conflict'];
788
789 if (!empty($conflicts)) {
790 foreach ($conflicts as $key => $val) {
791 if ($val === NULL and $mode == 'safe') {
792 // un-resolved conflicts still present. Lets skip this merge.
793 return TRUE;
794 }
795 else {
796 // copy over the resolved values
797 $migrationInfo[$key] = $val;
798 }
799 }
800 }
801 return FALSE;
802 }
803
804 /**
805 * A function to build an array of information required by merge function and the merge UI.
806 *
807 * @param int $mainId main contact with whom merge has to happen
808 * @param int $otherId duplicate contact which would be deleted after merge operation
809 *
810 * @return array|bool|int
811 * @static
812 * @access public
813 */
814 static function getRowsElementsAndInfo($mainId, $otherId) {
815 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
816
817 // Fetch contacts
818 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
819 $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields()));
820 $result = civicrm_api('contact', 'get', $params);
821
822 if (empty($result['values'][$cid]['contact_type'])) {
823 return FALSE;
824 }
825 $$moniker = $result['values'][$cid];
826 }
827
828 static $fields = array();
829 if (empty($fields)) {
830 $fields = CRM_Contact_DAO_Contact::fields();
831 CRM_Core_DAO::freeResult();
832 }
833
834 // get all contact subtypes
835 $contactSubTypes = CRM_Contact_BAO_ContactType::subTypePairs(NULL, TRUE, '');
836
837 // FIXME: there must be a better way
838 foreach (array('main', 'other') as $moniker) {
839 $contact = &$$moniker;
840 $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
841 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
842 $specialValues[$moniker] = array(
843 'preferred_communication_method' => $value,
844 'contact_sub_type' => $value,
845 'communication_style_id' => $value,
846 );
847
848 if (!empty($contact['preferred_communication_method'])){
849 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
850 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
851 implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) :
852 $specialValues[$moniker]['preferred_communication_method'];
853 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
854 }
855 $names = array(
856 'preferred_communication_method' =>
857 array(
858 'newName' => 'preferred_communication_method_display',
859 'groupName' => 'preferred_communication_method',
860 ),
861 );
862 CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
863
864 if (!empty($contact['contact_sub_type'])) {
865 $specialValues[$moniker]['contact_sub_type'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $contact['contact_sub_type']);
866
867 // fix contact sub type label for contact with sub type
868 $subtypes = array();
869 foreach ($contact['contact_sub_type'] as $key => $value) {
870 $subtypes[] = CRM_Utils_Array::retrieveValueRecursive($contactSubTypes, $value);
871 }
872 $contact['contact_sub_type_display'] = $specialValues[$moniker]['contact_sub_type_display'] = implode(', ', $subtypes);
873 }
874
875 if (!empty($contact['communication_style'])) {
876 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
877 }
878 }
879
880 static $optionValueFields = array();
881 if (empty($optionValueFields)) {
882 $optionValueFields = CRM_Core_OptionValue::getFields();
883 }
884 foreach ($optionValueFields as $field => $params) {
885 $fields[$field]['title'] = $params['title'];
886 }
887
888 $diffs = self::findDifferences($main, $other);
889
890 $rows = $elements = $relTableElements = $migrationInfo = array();
891
892 foreach ($diffs['contact'] as $field) {
893 foreach (array('main', 'other') as $moniker) {
894 $contact = &$$moniker;
895 $value = CRM_Utils_Array::value($field, $contact);
896 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
897 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
898 }
899 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
900 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
901 if ($value) {
902 $value = str_replace('-', '', $value);
903 $label = CRM_Utils_Date::customFormat($label);
904 }
905 else {
906 $value = "null";
907 }
908 }
909 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
910 if ($label === '0') {
911 $label = ts('[ ]');
912 }
913 if ($label === '1') {
914 $label = ts('[x]');
915 }
916 }
917 elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
918 $label = CRM_Utils_Array::value('individual_prefix', $contact);
919 $value = CRM_Utils_Array::value('prefix_id', $contact);
920 $field = 'prefix_id';
921 }
922 elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
923 $label = CRM_Utils_Array::value('individual_suffix', $contact);
924 $value = CRM_Utils_Array::value('suffix_id', $contact);
925 $field = 'suffix_id';
926 }
927 $rows["move_$field"][$moniker] = $label;
928 if ($moniker == 'other') {
929 //CRM-14334
930 if ($value === NULL || $value == '') {
931 $value = 'null';
932 }
933 if ($value === 0 or $value === '0') {
934 $value = $qfZeroBug;
935 }
936 if (is_array($value) && empty($value[1])) {
937 $value[1] = NULL;
938 }
939 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
940 $migrationInfo["move_$field"] = $value;
941 }
942 }
943 $rows["move_$field"]['title'] = $fields[$field]['title'];
944 }
945
946 // handle location blocks.
947 $locationBlocks = array('email', 'phone', 'address');
948 $locations = array();
949
950 foreach ($locationBlocks as $block) {
951 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
952 $cnt = 1;
953 $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
954 $count = $values['count'];
955 if ($count) {
956 if ($count > $cnt) {
957 foreach ($values['values'] as $value) {
958 if ($block == 'address') {
959 CRM_Core_BAO_Address::fixAddress($value);
960 $display = CRM_Utils_Address::format($value);
961 $locations[$moniker][$block][$cnt] = $value;
962 $locations[$moniker][$block][$cnt]['display'] = $display;
963 }
964 else {
965 $locations[$moniker][$block][$cnt] = $value;
966 }
967
968 $cnt++;
969 }
970 }
971 else {
972 $id = $values['id'];
973 if ($block == 'address') {
974 CRM_Core_BAO_Address::fixAddress($values['values'][$id]);
975 $display = CRM_Utils_Address::format($values['values'][$id]);
976 $locations[$moniker][$block][$cnt] = $values['values'][$id];
977 $locations[$moniker][$block][$cnt]['display'] = $display;
978 }
979 else {
980 $locations[$moniker][$block][$cnt] = $values['values'][$id];
981 }
982 }
983 }
984 }
985 }
986
987 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
988
989 $mainLocBlock = $locBlockIds = array();
990 $locBlockIds['main'] = $locBlockIds['other'] = array();
991 foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
992 $name = strtolower($block);
993 foreach (array('main', 'other') as $moniker) {
994 $locIndex = CRM_Utils_Array::value($moniker, $locations);
995 $blockValue = CRM_Utils_Array::value($name, $locIndex, array());
996 if (empty($blockValue)) {
997 $locValue[$moniker][$name] = 0;
998 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
999 }
1000 else {
1001 $locValue[$moniker][$name] = TRUE;
1002 foreach ($blockValue as $count => $blkValues) {
1003 $fldName = $name;
1004 $locTypeId = $blkValues['location_type_id'];
1005 if ($name == 'im') {
1006 $fldName = 'name';
1007 }
1008 if ($name == 'address') {
1009 $fldName = 'display';
1010 }
1011 $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName,
1012 $blkValues
1013 );
1014 $locTypes[$moniker][$name][$count] = $locTypeId;
1015 if ($moniker == 'main' && in_array($name, $locationBlocks)) {
1016 $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array::value($fldName,
1017 $blkValues
1018 );
1019 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
1020 }
1021 else {
1022 $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
1023 }
1024 }
1025 }
1026 }
1027
1028 if ($locValue['other'][$name] != 0) {
1029 foreach ($locLabel['other'][$name] as $count => $value) {
1030 $locTypeId = $locTypes['other'][$name][$count];
1031 $rows["move_location_{$name}_$count"]['other'] = $value;
1032 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array::value($count,
1033 $locLabel['main'][$name]
1034 );
1035 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
1036 array(
1037 1 => $block,
1038 2 => $count,
1039 3 => $allLocationTypes[$locTypeId]
1040 )
1041 );
1042
1043 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
1044 $migrationInfo["move_location_{$name}_{$count}"] = 1;
1045
1046 // make sure default location type is always on top
1047 $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId);
1048 $locTypeValues = $allLocationTypes;
1049 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
1050 unset($locTypeValues[$mainLocTypeId]);
1051
1052 // keep 1-1 mapping for address - location type.
1053 $js = NULL;
1054 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
1055 $js = array('onChange' => "mergeBlock('$name', this, $count );");
1056 }
1057 $elements[] = array(
1058 'select', "location[{$name}][$count][locTypeId]", NULL,
1059 $defaultLocType + $locTypeValues, $js,
1060 );
1061 // keep location-type-id same as that of other-contact
1062 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
1063
1064 if ($name != 'address') {
1065 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
1066 // always use add operation
1067 $migrationInfo['location'][$name][$count]['operation'] = 1;
1068 }
1069 }
1070 }
1071 }
1072
1073 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1074 $config = CRM_Core_Config::singleton();
1075 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1076 $mainUser = NULL;
1077 if ($mainUfId) {
1078 // d6 compatible
1079 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1080 $mainUser = user_load($mainUfId);
1081 }
1082 elseif ($config->userFramework == 'Joomla') {
1083 $mainUser = JFactory::getUser($mainUfId);
1084 }
1085 }
1086 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1087 $otherUser = NULL;
1088 if ($otherUfId) {
1089 // d6 compatible
1090 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1091 $otherUser = user_load($otherUfId);
1092 }
1093 elseif ($config->userFramework == 'Joomla') {
1094 $otherUser = JFactory::getUser($otherUfId);
1095 }
1096 }
1097
1098 $relTables = CRM_Dedupe_Merger::relTables();
1099 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1100 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1101 foreach ($relTables as $name => $null) {
1102 if (!in_array($name, $activeRelTables) &&
1103 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1104 ) {
1105 unset($relTables[$name]);
1106 continue;
1107 }
1108
1109 $relTableElements[] = array('checkbox', "move_$name");
1110 $migrationInfo["move_$name"] = 1;
1111
1112 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1113 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1114 if ($name == 'rel_table_users') {
1115 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1116 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1117 $find = array('$ufid', '$ufname');
1118 if ($mainUser) {
1119 $replace = array($mainUfId, $mainUser->name);
1120 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1121 }
1122 if ($otherUser) {
1123 $replace = array($otherUfId, $otherUser->name);
1124 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1125 }
1126 }
1127 if ($name == 'rel_table_memberships') {
1128 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1129 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1130 }
1131 }
1132 foreach ($relTables as $name => $null) {
1133 $relTables["move_$name"] = $relTables[$name];
1134 unset($relTables[$name]);
1135 }
1136
1137 // handle custom fields
1138 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1,
1139 CRM_Utils_Array::value('contact_sub_type', $main)
1140 );
1141 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1,
1142 CRM_Utils_Array::value('contact_sub_type', $other)
1143 );
1144 CRM_Core_DAO::freeResult();
1145
1146 foreach ($otherTree as $gid => $group) {
1147 $foundField = FALSE;
1148 if (!isset($group['fields'])) {
1149 continue;
1150 }
1151
1152 foreach ($group['fields'] as $fid => $field) {
1153 if (in_array($fid, $diffs['custom'])) {
1154 if (!$foundField) {
1155 $rows["custom_group_$gid"]['title'] = $group['title'];
1156 $foundField = TRUE;
1157 }
1158 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1159 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1160 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1161 $field, TRUE
1162 );
1163 }
1164 }
1165 $value = "null";
1166 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1167 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1168 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1169 $field, TRUE
1170 );
1171 if ($values['data'] === 0 || $values['data'] === '0') {
1172 $values['data'] = $qfZeroBug;
1173 }
1174 $value = ($values['data']) ? $values['data'] : $value;
1175 }
1176 }
1177 $rows["move_custom_$fid"]['title'] = $field['label'];
1178
1179 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1180 $migrationInfo["move_custom_$fid"] = $value;
1181 }
1182 }
1183 }
1184 $result = array(
1185 'rows' => $rows,
1186 'elements' => $elements,
1187 'rel_table_elements' => $relTableElements,
1188 'main_loc_block' => $mainLocBlock,
1189 'rel_tables' => $relTables,
1190 'main_details' => $main,
1191 'other_details' => $other,
1192 'migration_info' => $migrationInfo,
1193 );
1194
1195 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1196 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1197
1198 return $result;
1199 }
1200
1201 /**
1202 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1203 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1204 * A superset of moveContactBelongings() function.
1205 *
1206 * @param int $mainId main contact with whom merge has to happen
1207 * @param int $otherId duplicate contact which would be deleted after merge operation
1208 *
1209 * @param $migrationInfo
1210 *
1211 * @return bool
1212 * @static
1213 * @access public
1214 */
1215 static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1216 if (empty($migrationInfo)) {
1217 return FALSE;
1218 }
1219
1220 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1221 $relTables = CRM_Dedupe_Merger::relTables();
1222 $moveTables = $locBlocks = $tableOperations = array();
1223 foreach ($migrationInfo as $key => $value) {
1224 if ($value == $qfZeroBug) {
1225 $value = '0';
1226 }
1227 if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) ||
1228 substr($key, 0, 12) == 'move_custom_') &&
1229 $value != NULL
1230 ) {
1231 $submitted[substr($key, 5)] = $value;
1232 }
1233 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1234 $locField = explode('_', $key);
1235 $fieldName = $locField[2];
1236 $fieldCount = $locField[3];
1237 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1238 // default operation is overwrite.
1239 if (!$operation) {
1240 $operation = 2;
1241 }
1242
1243 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1244 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1245 }
1246 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1247 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1248 if (array_key_exists('operation', $migrationInfo)) {
1249 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1250 if (array_key_exists($key, $migrationInfo['operation'])) {
1251 $tableOperations[$table] = $migrationInfo['operation'][$key];
1252 }
1253 }
1254 }
1255 }
1256 }
1257
1258
1259 // **** Do location related migration:
1260 if (!empty($locBlocks)) {
1261 $locComponent = array(
1262 'email' => 'Email',
1263 'phone' => 'Phone',
1264 'im' => 'IM',
1265 'openid' => 'OpenID',
1266 'address' => 'Address',
1267 );
1268
1269 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
1270 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
1271
1272 foreach ($locBlocks as $name => $block) {
1273 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1274 continue;
1275 }
1276 $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
1277 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1278 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1279
1280 foreach ($block as $blkCount => $values) {
1281 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
1282 $operation = CRM_Utils_Array::value('operation', $values, 2);
1283 $otherBlockId = CRM_Utils_Array::value($blkCount,
1284 $migrationInfo['other_details']['loc_block_ids'][$name]
1285 );
1286
1287 // keep 1-1 mapping for address - loc type.
1288 $idKey = $blkCount;
1289 if (array_key_exists($name, $locComponent)) {
1290 $idKey = $locTypeId;
1291 }
1292
1293 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1294 $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1295 }
1296
1297 if (!$otherBlockId) {
1298 continue;
1299 }
1300
1301 // for the block which belongs to other-contact, link the contact to main-contact
1302 $otherBlockDAO = new $daoName();
1303 $otherBlockDAO->id = $otherBlockId;
1304 $otherBlockDAO->contact_id = $mainId;
1305 $otherBlockDAO->location_type_id = $locTypeId;
1306
1307 // if main contact already has primary & billing, set the flags to 0.
1308 if ($primaryDAOId) {
1309 $otherBlockDAO->is_primary = 0;
1310 }
1311 if ($billingDAOId) {
1312 $otherBlockDAO->is_billing = 0;
1313 }
1314
1315 // overwrite - need to delete block which belongs to main-contact.
1316 if ($mainBlockId && ($operation == 2)) {
1317 $deleteDAO = new $daoName();
1318 $deleteDAO->id = $mainBlockId;
1319 $deleteDAO->find(TRUE);
1320
1321 // if we about to delete a primary / billing block, set the flags for new block
1322 // that we going to assign to main-contact
1323 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1324 $otherBlockDAO->is_primary = 1;
1325 }
1326 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1327 $otherBlockDAO->is_billing = 1;
1328 }
1329
1330 $deleteDAO->delete();
1331 $deleteDAO->free();
1332 }
1333
1334 $otherBlockDAO->update();
1335 $otherBlockDAO->free();
1336 }
1337 }
1338 }
1339
1340 // **** Do tables related migrations
1341 if (!empty($moveTables)) {
1342 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1343 unset($moveTables, $tableOperations);
1344 }
1345
1346 // **** Do contact related migrations
1347 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
1348
1349 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1350 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1351 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1352 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1353 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1354 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1355 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1356 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1357 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1358
1359 // fix custom fields so they're edible by createProfileContact()
1360 static $treeCache = array();
1361 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1362 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'],
1363 CRM_Core_DAO::$_nullObject, NULL, -1
1364 );
1365 }
1366 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1367
1368 $cFields = array();
1369 foreach ($cgTree as $key => $group) {
1370 if (!isset($group['fields'])) {
1371 continue;
1372 }
1373 foreach ($group['fields'] as $fid => $field) {
1374 $cFields[$fid]['attributes'] = $field;
1375 }
1376 }
1377
1378 if (!isset($submitted)) {
1379 $submitted = array();
1380 }
1381 foreach ($submitted as $key => $value) {
1382 if (substr($key, 0, 7) == 'custom_') {
1383 $fid = (int) substr($key, 7);
1384 if (empty($cFields[$fid])) {
1385 continue;
1386 }
1387 $htmlType = $cFields[$fid]['attributes']['html_type'];
1388 switch ($htmlType) {
1389 case 'File':
1390 $customFiles[] = $fid;
1391 unset($submitted["custom_$fid"]);
1392 break;
1393
1394 case 'Select Country':
1395 case 'Select State/Province':
1396 $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
1397 break;
1398
1399 case 'CheckBox':
1400 case 'AdvMulti-Select':
1401 case 'Multi-Select':
1402 case 'Multi-Select Country':
1403 case 'Multi-Select State/Province':
1404 // Merge values from both contacts for multivalue fields, CRM-4385
1405 // get the existing custom values from db.
1406 $customParams = array('entityID' => $mainId, $key => TRUE);
1407 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
1408 if (!empty($customfieldValues[$key])) {
1409 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1410 if (is_array($existingValue) && !empty($existingValue)) {
1411 $mergeValue = $submmtedCustomValue = array();
1412 if ($value) {
1413 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1414 }
1415
1416 //hack to remove null and duplicate values from array.
1417 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1418 if ($v != '' && !in_array($v, $mergeValue)) {
1419 $mergeValue[] = $v;
1420 }
1421 }
1422
1423 //keep state and country as array format.
1424 //for checkbox and m-select format w/ VALUE_SEPARATOR
1425 if (in_array($htmlType, array(
1426 'CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
1427 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1428 $mergeValue
1429 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1430 }
1431 else {
1432 $submitted[$key] = $mergeValue;
1433 }
1434 }
1435 }
1436 elseif (in_array($htmlType, array(
1437 'Multi-Select Country', 'Multi-Select State/Province'))) {
1438 //we require submitted values should be in array format
1439 if ($value) {
1440 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1441 //hack to remove null values from array.
1442 $mergeValue = array();
1443 foreach ($mergeValueArray as $k => $v) {
1444 if ($v != '') {
1445 $mergeValue[] = $v;
1446 }
1447 }
1448 $submitted[$key] = $mergeValue;
1449 }
1450 }
1451 break;
1452
1453 default:
1454 break;
1455 }
1456 }
1457 }
1458
1459 // **** Do file custom fields related migrations
1460 // FIXME: move this someplace else (one of the BAOs) after discussing
1461 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1462 // like, delete a file...
1463
1464 if (!isset($customFiles)) {
1465 $customFiles = array();
1466 }
1467 foreach ($customFiles as $customId) {
1468 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1469
1470 // get the contact_id -> file_id mapping
1471 $fileIds = array();
1472 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1473 $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1474 while ($dao->fetch()) {
1475 $fileIds[$dao->entity_id] = $dao->file_id;
1476 }
1477 $dao->free();
1478
1479 // delete the main contact's file
1480 if (!empty($fileIds[$mainId])) {
1481 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1482 }
1483
1484 // move the other contact's file to main contact
1485 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1486 if ( CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}") ) {
1487 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1488 }
1489 else {
1490 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1491 }
1492 CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1493
1494 if ( CRM_Core_DAO::singleValueQuery("
1495 SELECT id
1496 FROM civicrm_entity_file
1497 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}") ) {
1498 $sql = "
1499 UPDATE civicrm_entity_file
1500 SET entity_id = {$mainId}
1501 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1502 }
1503 else {
1504 $sql = "
1505 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1506 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1507 }
1508 CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1509 }
1510
1511 // move view only custom fields CRM-5362
1512 $viewOnlyCustomFields = array();
1513 foreach ($submitted as $key => $value) {
1514 $fid = (int) substr($key, 7);
1515 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1516 $viewOnlyCustomFields[$key] = $value;
1517 }
1518 }
1519
1520 // special case to set values for view only, CRM-5362
1521 if (!empty($viewOnlyCustomFields)) {
1522 $viewOnlyCustomFields['entityID'] = $mainId;
1523 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1524 }
1525
1526 // **** Delete other contact & update prev-next caching
1527 $otherParams = array(
1528 'contact_id' => $otherId,
1529 'id' => $otherId,
1530 'version' => 3,
1531 );
1532 if (CRM_Core_Permission::check('merge duplicate contacts') &&
1533 CRM_Core_Permission::check('delete contacts')
1534 ) {
1535 // if ext id is submitted then set it null for contact to be deleted
1536 if (!empty($submitted['external_identifier'])) {
1537 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1538 CRM_Core_DAO::executeQuery($query);
1539 }
1540
1541 civicrm_api('contact', 'delete', $otherParams);
1542 CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
1543 }
1544 // FIXME: else part
1545 /* else { */
1546
1547 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1548
1549 /* } */
1550
1551
1552 // **** Update contact related info for the main contact
1553 if (!empty($submitted)) {
1554 $submitted['contact_id'] = $mainId;
1555
1556 //update current employer field
1557 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1558 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1559 $submitted['current_employer'] = $submitted['current_employer_id'];
1560 } else {
1561 $submitted['current_employer'] = '';
1562 }
1563 unset($submitted['current_employer_id']);
1564 }
1565
1566 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1567 if ( !isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id']) ) {
1568 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1569 }
1570 if ( !isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id']) ) {
1571 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1572 }
1573
1574 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
1575 unset($submitted);
1576 }
1577
1578 return TRUE;
1579 }
1580
1581 /**
1582 * @return array of field names which will be compared, so everything except ID.
1583 */
1584 static function getContactFields() {
1585 $contactFields = CRM_Contact_DAO_Contact::fields();
1586 $invalidFields = array('api_key', 'contact_is_deleted', 'created_date', 'display_name', 'hash', 'id', 'modified_date',
1587 'primary_contact_id', 'sort_name', 'user_unique_id');
1588 foreach ($contactFields as $field => $value) {
1589 if (in_array($field, $invalidFields)) {
1590 unset($contactFields[$field]);
1591 }
1592 }
1593 return array_keys($contactFields);
1594 }
1595
1596 /**
1597 * Added for CRM-12695
1598 * Based on the contactId provided
1599 * add/update membership(s) to related contacts
1600 *
1601 * @param contactId
1602 */
1603 static function addMembershipToRealtedContacts($contactID) {
1604 $dao = new CRM_Member_DAO_Membership();
1605 $dao->contact_id = $contactID;
1606 $dao->is_test = 0;
1607 $dao->find();
1608
1609 //checks membership of contact itself
1610 while ($dao->fetch()) {
1611 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1612 if ($relationshipTypeId) {
1613 $membershipParams = array(
1614 'id' => $dao->id,
1615 'contact_id' => $dao->contact_id,
1616 'membership_type_id' => $dao->membership_type_id,
1617 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1618 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1619 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1620 'source' => $dao->source,
1621 'status_id' => $dao->status_id
1622 );
1623 // create/update membership(s) for related contact(s)
1624 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1625 } // end of if relationshipTypeId
1626 }
1627 }
1628 }