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