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