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