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