CRM-18497 add first very basic test to job.merge
[civicrm-core.git] / CRM / Dedupe / Merger.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
32 */
33 class CRM_Dedupe_Merger {
34
35 /**
36 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
37 * FIXME: the sub-pages references by the URLs should
38 * be loaded dynamically on the merge form instead
39 * @return array
40 */
41 public static function relTables() {
42 static $relTables;
43
44 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
45 // if the url can't be retrieved. A more standardised way to retrieve them is.
46 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
47 // we may need a different function when it is not known.
48 $title = $userRecordUrl = '';
49
50 $config = CRM_Core_Config::singleton();
51 if ($config->userSystem->is_drupal) {
52 $userRecordUrl = CRM_Utils_System::url('user/%ufid');
53 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
54 }
55 elseif ($config->userFramework == 'Joomla') {
56 $userRecordUrl = $config->userSystem->getVersion() > 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';
57 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
58 }
59
60 if (!$relTables) {
61 $relTables = array(
62 'rel_table_contributions' => array(
63 'title' => ts('Contributions'),
64 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
65 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
66 ),
67 'rel_table_contribution_page' => array(
68 'title' => ts('Contribution Pages'),
69 'tables' => array('civicrm_contribution_page'),
70 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
71 ),
72 'rel_table_memberships' => array(
73 'title' => ts('Memberships'),
74 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
75 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
76 ),
77 'rel_table_participants' => array(
78 'title' => ts('Participants'),
79 'tables' => array('civicrm_participant'),
80 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
81 ),
82 'rel_table_events' => array(
83 'title' => ts('Events'),
84 'tables' => array('civicrm_event'),
85 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
86 ),
87 'rel_table_activities' => array(
88 'title' => ts('Activities'),
89 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
90 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
91 ),
92 'rel_table_relationships' => array(
93 'title' => ts('Relationships'),
94 'tables' => array('civicrm_relationship'),
95 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
96 ),
97 'rel_table_custom_groups' => array(
98 'title' => ts('Custom Groups'),
99 'tables' => array('civicrm_custom_group'),
100 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
101 ),
102 'rel_table_uf_groups' => array(
103 'title' => ts('Profiles'),
104 'tables' => array('civicrm_uf_group'),
105 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
106 ),
107 'rel_table_groups' => array(
108 'title' => ts('Groups'),
109 'tables' => array('civicrm_group_contact'),
110 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
111 ),
112 'rel_table_notes' => array(
113 'title' => ts('Notes'),
114 'tables' => array('civicrm_note'),
115 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
116 ),
117 'rel_table_tags' => array(
118 'title' => ts('Tags'),
119 'tables' => array('civicrm_entity_tag'),
120 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
121 ),
122 'rel_table_mailings' => array(
123 'title' => ts('Mailings'),
124 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
125 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
126 ),
127 'rel_table_cases' => array(
128 'title' => ts('Cases'),
129 'tables' => array('civicrm_case_contact'),
130 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
131 ),
132 'rel_table_grants' => array(
133 'title' => ts('Grants'),
134 'tables' => array('civicrm_grant'),
135 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
136 ),
137 'rel_table_pcp' => array(
138 'title' => ts('PCPs'),
139 'tables' => array('civicrm_pcp'),
140 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
141 ),
142 'rel_table_pledges' => array(
143 'title' => ts('Pledges'),
144 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
145 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
146 ),
147 'rel_table_users' => array(
148 'title' => $title,
149 'tables' => array('civicrm_uf_match'),
150 'url' => $userRecordUrl,
151 ),
152 );
153
154 $relTables += self::getMultiValueCustomSets('relTables');
155
156 // Allow hook_civicrm_merge() to adjust $relTables
157 CRM_Utils_Hook::merge('relTables', $relTables);
158 }
159 return $relTables;
160 }
161
162 /**
163 * Returns the related tables groups for which a contact has any info entered.
164 *
165 * @param int $cid
166 *
167 * @return array
168 */
169 public static function getActiveRelTables($cid) {
170 $cid = (int) $cid;
171 $groups = array();
172
173 $relTables = self::relTables();
174 $cidRefs = self::cidRefs();
175 $eidRefs = self::eidRefs();
176 foreach ($relTables as $group => $params) {
177 $sqls = array();
178 foreach ($params['tables'] as $table) {
179 if (isset($cidRefs[$table])) {
180 foreach ($cidRefs[$table] as $field) {
181 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
182 }
183 }
184 if (isset($eidRefs[$table])) {
185 foreach ($eidRefs[$table] as $entityTable => $entityId) {
186 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
187 }
188 }
189 foreach ($sqls as $sql) {
190 if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
191 $groups[] = $group;
192 }
193 }
194 }
195 }
196 return array_unique($groups);
197 }
198
199 /**
200 * Get array tables and fields that reference civicrm_contact.id.
201 *
202 * This includes core tables, custom group tables, tables added by the merge
203 * hook and (somewhat randomly) the entity_tag table.
204 *
205 * Refer to CRM-17454 for information on the danger of querying the information
206 * schema to derive this.
207 *
208 * @todo create an 'entity hook' to allow entities to be registered to CiviCRM
209 * including all info that is normally in the DAO.
210 */
211 public static function cidRefs() {
212 $cidRefs = array();
213 $coreReferences = CRM_Core_DAO::getReferencesToTable('civicrm_contact');
214 foreach ($coreReferences as $coreReference) {
215 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
216 $cidRefs[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
217 }
218 }
219 self::addCustomTablesExtendingContactsToCidRefs($cidRefs);
220
221 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
222 $cidRefs['civicrm_entity_tag'][] = 'entity_id';
223
224 // Allow hook_civicrm_merge() to adjust $cidRefs.
225 // @todo consider adding a way to register entities and have them
226 // automatically added to this list.
227 CRM_Utils_Hook::merge('cidRefs', $cidRefs);
228 return $cidRefs;
229 }
230
231 /**
232 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
233 */
234 public static function eidRefs() {
235 static $eidRefs;
236 if (!$eidRefs) {
237 // FIXME: this should be generated dynamically from the schema
238 // tables that reference contacts with entity_{id,table}
239 $eidRefs = array(
240 'civicrm_acl' => array('entity_table' => 'entity_id'),
241 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
242 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
243 'civicrm_log' => array('entity_table' => 'entity_id'),
244 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
245 'civicrm_note' => array('entity_table' => 'entity_id'),
246 );
247
248 // Allow hook_civicrm_merge() to adjust $eidRefs
249 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
250 }
251 return $eidRefs;
252 }
253
254 /**
255 * Return tables using locations.
256 */
257 public static function locTables() {
258 static $locTables;
259 if (!$locTables) {
260 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
261
262 // Allow hook_civicrm_merge() to adjust $locTables
263 CRM_Utils_Hook::merge('locTables', $locTables);
264 }
265 return $locTables;
266 }
267
268 /**
269 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
270 * @param string $request
271 * 'relTables' or 'cidRefs'.
272 * @see CRM-13836
273 */
274 public static function getMultiValueCustomSets($request) {
275 static $data = NULL;
276 if ($data === NULL) {
277 $data = array(
278 'relTables' => array(),
279 'cidRefs' => array(),
280 );
281 $result = civicrm_api3('custom_group', 'get', array(
282 'is_multiple' => 1,
283 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
284 'return' => array('id', 'title', 'table_name', 'style'),
285 ));
286 foreach ($result['values'] as $custom) {
287 $data['cidRefs'][$custom['table_name']] = array('entity_id');
288 $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
289 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
290 'title' => $custom['title'],
291 'tables' => array($custom['table_name']),
292 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
293 );
294 }
295 }
296 return $data[$request];
297 }
298
299 /**
300 * Tables which require custom processing should declare functions to call here.
301 * Doing so will override normal processing.
302 */
303 public static function cpTables() {
304 static $tables;
305 if (!$tables) {
306 $tables = array(
307 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
308 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
309 // Empty array == do nothing - this table is handled by mergeGroupContact
310 'civicrm_subscription_history' => array(),
311 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
312 );
313 }
314 return $tables;
315 }
316
317 /**
318 * Return payment related table.
319 */
320 public static function paymentTables() {
321 static $tables;
322 if (!$tables) {
323 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
324 }
325 return $tables;
326 }
327
328 /**
329 * Return payment update Query.
330 *
331 * @param string $tableName
332 * @param int $mainContactId
333 * @param int $otherContactId
334 *
335 * @return array
336 */
337 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
338 $sqls = array();
339 if (!$tableName || !$mainContactId || !$otherContactId) {
340 return $sqls;
341 }
342
343 $paymentTables = self::paymentTables();
344 if (!in_array($tableName, $paymentTables)) {
345 return $sqls;
346 }
347
348 switch ($tableName) {
349 case 'civicrm_pledge':
350 $sqls[] = "
351 UPDATE IGNORE civicrm_contribution contribution
352 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
353 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
354 SET contribution.contact_id = $mainContactId
355 WHERE pledge.contact_id = $otherContactId";
356 break;
357
358 case 'civicrm_membership':
359 $sqls[] = "
360 UPDATE IGNORE civicrm_contribution contribution
361 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
362 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
363 SET contribution.contact_id = $mainContactId
364 WHERE membership.contact_id = $otherContactId";
365 break;
366
367 case 'civicrm_participant':
368 $sqls[] = "
369 UPDATE IGNORE civicrm_contribution contribution
370 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
371 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
372 SET contribution.contact_id = $mainContactId
373 WHERE participant.contact_id = $otherContactId";
374 break;
375 }
376
377 return $sqls;
378 }
379
380 /**
381 * @param int $mainId
382 * @param int $otherId
383 * @param string $tableName
384 * @param array $tableOperations
385 * @param string $mode
386 *
387 * @return array
388 */
389 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
390 $sqls = array();
391 if (!$tableName || !$mainId || !$otherId) {
392 return $sqls;
393 }
394
395 switch ($tableName) {
396 case 'civicrm_membership':
397 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
398 break;
399 }
400 if ($mode == 'add') {
401 $sqls[] = "
402 DELETE membership1.* FROM civicrm_membership membership1
403 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
404 AND membership1.contact_id = {$mainId}
405 AND membership2.contact_id = {$otherId} ";
406 }
407 if ($mode == 'payment') {
408 $sqls[] = "
409 DELETE contribution.* FROM civicrm_contribution contribution
410 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
411 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
412 AND membership1.contact_id = {$mainId}
413 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
414 AND membership2.contact_id = {$otherId}";
415 }
416 break;
417
418 case 'civicrm_uf_match':
419 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
420 // failing to meet intended result. Therefore we introduce this additional query:
421 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
422 break;
423 }
424
425 return $sqls;
426 }
427
428 /**
429 * Based on the provided two contact_ids and a set of tables, move the
430 * belongings of the other contact to the main one.
431 *
432 * @param int $mainId
433 * @param int $otherId
434 * @param bool $tables
435 * @param array $tableOperations
436 */
437 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
438 $cidRefs = self::cidRefs();
439 $eidRefs = self::eidRefs();
440 $cpTables = self::cpTables();
441 $paymentTables = self::paymentTables();
442 // CRM-12695:
443 $membershipMerge = FALSE;
444
445 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
446 if ($tables !== FALSE) {
447 // if there are specific tables, sanitize the list
448 $affected = array_unique(array_intersect($affected, $tables));
449 }
450 else {
451 // if there aren't any specific tables, don't affect the ones handled by relTables()
452 // also don't affect tables in locTables() CRM-15658
453 $relTables = self::relTables();
454 $handled = self::locTables();
455 foreach ($relTables as $params) {
456 $handled = array_merge($handled, $params['tables']);
457 }
458 $affected = array_diff($affected, $handled);
459 /**
460 * CRM-12695
461 * Set $membershipMerge flag only once
462 * while doing contact related migration
463 * to call addMembershipToRealtedContacts()
464 * function only once.
465 * Since the current function (moveContactBelongings) is called twice
466 * with & without parameters $tables & $tableOperations
467 */
468 // retrieve main contact's related table(s)
469 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
470 // check if membership table exists in main contact's related table(s)
471 // set membership flag - CRM-12695
472 if (in_array('rel_table_memberships', $activeMainRelTables)) {
473 $membershipMerge = TRUE;
474 }
475 }
476
477 $mainId = (int) $mainId;
478 $otherId = (int) $otherId;
479
480 $sqls = array();
481 foreach ($affected as $table) {
482 // Call custom processing function for objects that require it
483 if (isset($cpTables[$table])) {
484 foreach ($cpTables[$table] as $className => $fnName) {
485 $className::$fnName($mainId, $otherId, $sqls);
486 }
487 // Skip normal processing
488 continue;
489 }
490
491 // use UPDATE IGNORE + DELETE query pair to skip on situations when
492 // there's a UNIQUE restriction on ($field, some_other_field) pair
493 if (isset($cidRefs[$table])) {
494 foreach ($cidRefs[$table] as $field) {
495 // carry related contributions CRM-5359
496 if (in_array($table, $paymentTables)) {
497 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
498 $sqls = array_merge($sqls, $paymentSqls);
499
500 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
501 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
502 $sqls = array_merge($sqls, $payOprSqls);
503 }
504 }
505
506 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
507 $sqls = array_merge($sqls, $preOperationSqls);
508
509 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
510 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
511 }
512 }
513 if (isset($eidRefs[$table])) {
514 foreach ($eidRefs[$table] as $entityTable => $entityId) {
515 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
516 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
517 }
518 }
519 }
520
521 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
522 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
523
524 // call the SQL queries in one transaction
525 $transaction = new CRM_Core_Transaction();
526 foreach ($sqls as $sql) {
527 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE);
528 }
529 // CRM-12695
530 if ($membershipMerge) {
531 // call to function adding membership to related contacts
532 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
533 }
534 $transaction->commit();
535 }
536
537 /**
538 * Load all non-empty fields for the contacts
539 *
540 * @param array $main
541 * Contact details.
542 * @param array $other
543 * Contact details.
544 *
545 * @return array
546 */
547 public static function retrieveFields($main, $other) {
548 $result = array(
549 'contact' => array(),
550 'custom' => array(),
551 );
552 foreach (self::getContactFields() as $validField) {
553 // CRM-17556 Get all non-empty fields, to make comparison easier
554 if (!empty($main[$validField]) || !empty($other[$validField])) {
555 $result['contact'][] = $validField;
556 }
557 }
558
559 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
560 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
561 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
562 foreach ($keys as $key) {
563 // Exclude multi-value fields CRM-13836
564 if (strpos($key, '_')) {
565 continue;
566 }
567 $key1 = CRM_Utils_Array::value($key, $mainEvs);
568 $key2 = CRM_Utils_Array::value($key, $otherEvs);
569 // CRM-17556 Get all non-empty fields, to make comparison easier
570 if (!empty($key1) || !empty($key2)) {
571 $result['custom'][] = $key;
572 }
573 }
574 return $result;
575 }
576
577 /**
578 * Batch merge a set of contacts based on rule-group and group.
579 *
580 * @param int $rgid
581 * Rule group id.
582 * @param int $gid
583 * Group id.
584 * @param string $mode
585 * Helps decide how to behave when there are conflicts.
586 * A 'safe' value skips the merge if there are any un-resolved conflicts.
587 * Does a force merge otherwise.
588 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
589 * Whether to let api decide which contact to retain and which to delete.
590 * @param int $batchLimit number of merges to carry out in one batch.
591 * @param int $isSelected if records with is_selected column needs to be processed.
592 *
593 * @return array|bool
594 */
595 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $batchLimit = 1, $isSelected = 2) {
596 $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
597 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
598 $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected);
599
600 $cacheParams = array(
601 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid),
602 // @todo stop passing these parameters in & instead calculate them in the merge function based
603 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
604 'join' => self::getJoinOnDedupeTable(),
605 'where' => self::getWhereString($batchLimit, $isSelected),
606 );
607 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
608 }
609
610 /**
611 * Get the string to join the prevnext cache to the dedupe table.
612 *
613 * @return string
614 * The join string to join prevnext cache on the dedupe table.
615 */
616 public static function getJoinOnDedupeTable() {
617 return "
618 LEFT JOIN civicrm_dedupe_exception de
619 ON (
620 pn.entity_id1 = de.contact_id1
621 AND pn.entity_id2 = de.contact_id2 )
622 ";
623 }
624
625 /**
626 * Get where string for dedupe join.
627 *
628 * @param int $batchLimit
629 * @param bool $isSelected
630 *
631 * @return string
632 */
633 protected static function getWhereString($batchLimit, $isSelected) {
634 $where = "de.id IS NULL";
635 if ($isSelected === 0 || $isSelected === 1) {
636 $where .= " AND pn.is_selected = {$isSelected}";
637 }
638 // else consider all dupe pairs
639 // @todo Adding limit to Where??!!
640 $where .= " LIMIT {$batchLimit}";
641 return $where;
642 }
643
644 public static function updateMergeStats($cacheKeyString, $result = array()) {
645 // gather latest stats
646 $merged = count($result['merged']);
647 $skipped = count($result['skipped']);
648
649 if ($merged <= 0 && $skipped <= 0) {
650 return;
651 }
652
653 // get previous stats
654 $previousStats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
655 if (!empty($previousStats)) {
656 if ($previousStats[0]['merged']) {
657 $merged = $merged + $previousStats[0]['merged'];
658 }
659 if ($previousStats[0]['skipped']) {
660 $skipped = $skipped + $previousStats[0]['skipped'];
661 }
662 }
663
664 // delete old stats
665 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
666
667 // store the updated stats
668 $data = array(
669 'merged' => $merged,
670 'skipped' => $skipped,
671 );
672 $data = CRM_Core_DAO::escapeString(serialize($data));
673
674 $values = array();
675 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
676 CRM_Core_BAO_PrevNextCache::setItem($values);
677 }
678
679 public static function resetMergeStats($cacheKeyString) {
680 return CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
681 }
682
683 public static function getMergeStats($cacheKeyString) {
684 $stats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
685 if (!empty($stats)) {
686 $stats = $stats[0];
687 }
688 return $stats;
689 }
690
691 public static function getMergeStatsMsg($cacheKeyString) {
692 $msg = '';
693 $stats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
694 if (!empty($stats['merged'])) {
695 $msg = "{$stats['merged']} " . ts('Contact(s) were merged.');
696 }
697 if (!empty($stats['skipped'])) {
698 $msg .= $stats['skipped'] . ts('Contact(s) were skipped.');
699 }
700 return $msg;
701 }
702
703 /**
704 * Merge given set of contacts. Performs core operation.
705 *
706 * @param array $dupePairs
707 * Set of pair of contacts for whom merge is to be done.
708 * @param array $cacheParams
709 * Prev-next-cache params based on which next pair of contacts are computed.
710 * Generally used with batch-merge.
711 * @param string $mode
712 * Helps decide how to behave when there are conflicts.
713 * A 'safe' value skips the merge if there are any un-resolved conflicts.
714 * Does a force merge otherwise (aggressive mode).
715 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
716 * Wether to let api decide which contact to retain and which to delete.
717 *
718 *
719 * @param bool $redirectForPerformance
720 *
721 * @return array|bool
722 */
723 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
724 $autoFlip = TRUE, $redirectForPerformance = FALSE
725 ) {
726 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
727 $resultStats = array('merged' => array(), 'skipped' => array());
728
729 // we don't want dupe caching to get reset after every-merge, and therefore set the
730 // doNotResetCache flag
731 $config = CRM_Core_Config::singleton();
732 $config->doNotResetCache = 1;
733
734 while (!empty($dupePairs)) {
735 foreach ($dupePairs as $dupes) {
736 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
737 $mainId = $dupes['dstID'];
738 $otherId = $dupes['srcID'];
739 $isAutoFlip = CRM_Utils_Array::value('auto_flip', $dupes, $autoFlip);
740 // if we can, make sure that $mainId is the one with lower id number
741 if ($isAutoFlip && ($mainId > $otherId)) {
742 $mainId = $dupes['srcID'];
743 $otherId = $dupes['dstID'];
744 }
745 if (!$mainId || !$otherId) {
746 // return error
747 return FALSE;
748 }
749
750 // Generate var $migrationInfo. The variable structure is exactly same as
751 // $formValues submitted during a UI merge for a pair of contacts.
752 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId);
753
754 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
755
756 // add additional details that we might need to resolve conflicts
757 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
758 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
759 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
760
761 // go ahead with merge if there is no conflict
762 $conflicts = array();
763 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
764 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo);
765 $resultStats['merged'][] = array('main_id' => $mainId, 'other_id' => $otherId);
766 }
767 else {
768 $resultStats['skipped'][] = array('main_id' => $mainId, 'other_id' => $otherId);
769 }
770
771 // store any conflicts
772 if (!empty($conflicts)) {
773 foreach ($conflicts as $key => $dnc) {
774 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
775 }
776 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
777 }
778 else {
779 // delete entry from PrevNextCache table so we don't consider the pair next time
780 // pair may have been flipped, so make sure we delete using both orders
781 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
782 }
783
784 CRM_Core_DAO::freeResult();
785 unset($rowsElementsAndInfo, $migrationInfo);
786 }
787
788 if ($cacheKeyString && !$redirectForPerformance) {
789 // retrieve next pair of dupes
790 // @todo call getDuplicatePairs.
791 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
792 $cacheParams['join'],
793 $cacheParams['where']
794 );
795 }
796 else {
797 // do not proceed. Terminate the loop
798 unset($dupePairs);
799 }
800 }
801
802 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
803 return $resultStats;
804 }
805
806 /**
807 * A function which uses various rules / algorithms for choosing which contact to bias to
808 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
809 *
810 * @param int $mainId
811 * Main contact with whom merge has to happen.
812 * @param int $otherId
813 * Duplicate contact which would be deleted after merge operation.
814 * @param array $migrationInfo
815 * Array of information about which elements to merge.
816 * @param string $mode
817 * Helps decide how to behave when there are conflicts.
818 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
819 * - Does a force merge otherwise (aggressive mode).
820 *
821 * @param array $conflicts
822 *
823 * @return bool
824 */
825 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
826
827 $migrationData = array(
828 'old_migration_info' => $migrationInfo,
829 'mode' => $mode,
830 );
831
832 foreach ($migrationInfo as $key => $val) {
833 if ($val === "null") {
834 // Rule: Never overwrite with an empty value (in any mode)
835 unset($migrationInfo[$key]);
836 continue;
837 }
838 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
839 substr($key, 0, 12) == 'move_custom_'
840 ) and $val != NULL
841 ) {
842 // Rule: If both main-contact, and other-contact have a field with a
843 // different value, then let $mode decide if to merge it or not
844 if (
845 !empty($migrationInfo['rows'][$key]['main'])
846 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
847 ) {
848
849 // note it down & lets wait for response from the hook.
850 // For no response $mode will decide if to skip this merge
851 $conflicts[$key] = NULL;
852 }
853 }
854 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
855 $locField = explode('_', $key);
856 $fieldName = $locField[2];
857 $fieldCount = $locField[3];
858
859 // Rule: Catch address conflicts (same address type on both contacts)
860 if ($fieldName == 'address') {
861 $mainNewLocTypeId = $migrationInfo['location_blocks'][$fieldName][$fieldCount]['locTypeId'];
862 if (
863 isset($migrationInfo['main_details']['location_blocks']['address']) &&
864 !empty($migrationInfo['main_details']['location_blocks']['address'])
865 ) {
866 // Look for this LocTypeId in the results
867 // @todo This can be streamlined using array_column() in PHP 5.5+
868 foreach ($migrationInfo['main_details']['location_blocks']['address'] as $addressKey => $addressRecord) {
869 if ($addressRecord['location_type_id'] == $mainNewLocTypeId) {
870 $conflicts[$key] = NULL;
871 break;
872 }
873 }
874
875 }
876 }
877 // For other locations, don't merge/add if the values are the same
878 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
879 unset($migrationInfo[$key]);
880 }
881 }
882 }
883
884 // A hook to implement other algorithms for choosing which contact to bias to when
885 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
886 // merge happens with new values filled in here. For a particular field / row not to be merged
887 // field should be unset from fields_in_conflict.
888 $migrationData['fields_in_conflict'] = $conflicts;
889 $migrationData['merge_mode'] = $mode;
890 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
891 $conflicts = $migrationData['fields_in_conflict'];
892 // allow hook to override / manipulate migrationInfo as well
893 $migrationInfo = $migrationData['old_migration_info'];
894
895 if (!empty($conflicts)) {
896 foreach ($conflicts as $key => $val) {
897 if ($val === NULL and $mode == 'safe') {
898 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
899 return TRUE;
900 }
901 else {
902 // copy over the resolved values
903 $migrationInfo[$key] = $val;
904 }
905 }
906 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
907 if (array_key_exists('skip_merge', $migrationData)) {
908 return (bool) $migrationData['skip_merge'];
909 }
910 }
911 return FALSE;
912 }
913
914 /**
915 * A function to build an array of information about location blocks that is
916 * required when merging location fields
917 *
918 * @return array
919 */
920 public static function getLocationBlockInfo() {
921 $locationBlocks = array(
922 'address' => array(
923 'label' => 'Address',
924 'displayField' => 'display',
925 'sortString' => 'location_type_id',
926 'hasLocation' => TRUE,
927 'hasType' => FALSE,
928 ),
929 'email' => array(
930 'label' => 'Email',
931 'displayField' => 'email',
932 'sortString' => 'location_type_id',
933 'hasLocation' => TRUE,
934 'hasType' => FALSE,
935 ),
936 'im' => array(
937 'label' => 'IM',
938 'displayField' => 'name',
939 'sortString' => 'location_type_id,provider_id',
940 'hasLocation' => TRUE,
941 'hasType' => 'provider_id',
942 ),
943 'phone' => array(
944 'label' => 'Phone',
945 'displayField' => 'phone',
946 'sortString' => 'location_type_id,phone_type_id',
947 'hasLocation' => TRUE,
948 'hasType' => 'phone_type_id',
949 ),
950 'website' => array(
951 'label' => 'Website',
952 'displayField' => 'url',
953 'sortString' => 'website_type_id',
954 'hasLocation' => FALSE,
955 'hasType' => 'website_type_id',
956 ),
957 );
958 return $locationBlocks;
959 }
960
961 /**
962 * A function to build an array of information required by merge function and the merge UI.
963 *
964 * @param int $mainId
965 * Main contact with whom merge has to happen.
966 * @param int $otherId
967 * Duplicate contact which would be deleted after merge operation.
968 *
969 * @return array|bool|int
970 *
971 * rows => An array of arrays, each is row of merge information for the table
972 * Format: move_fieldname, eg: move_contact_type
973 * main => Value associated with the main contact
974 * other => Value associated with the other contact
975 * title => The title of the field to display in the merge table
976 *
977 * elements => An array of form elements for the merge UI
978 *
979 * rel_table_elements => An array of form elements for the merge UI for
980 * entities related to the contact (eg: checkbox to move 'mailings')
981 *
982 * rel_tables => Stores the tables that have related entities for the contact
983 * for example mailings, groups
984 *
985 * main_details => An array of core contact field values, eg: first_name, etc.
986 * location_blocks => An array of location block data for the main contact
987 * stored as the 'result' of an API call.
988 * eg: main_details['location_blocks']['address'][0]['id']
989 * eg: main_details['location_blocks']['email'][1]['id']
990 *
991 * other_details => As above, but for the 'other' contact
992 *
993 * migration_info => Stores the 'default' merge actions for each field which
994 * is used when programatically merging contacts. It contains instructions
995 * to move all fields from the 'other' contact to the 'main' contact, as
996 * though the form had been submitted with those options.
997 *
998 */
999 public static function getRowsElementsAndInfo($mainId, $otherId) {
1000 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1001
1002 // Fetch contacts
1003 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
1004 $params = array(
1005 'contact_id' => $cid,
1006 'version' => 3,
1007 'return' => array_merge(array('display_name'), self::getContactFields()),
1008 );
1009 $result = civicrm_api('contact', 'get', $params);
1010
1011 if (empty($result['values'][$cid]['contact_type'])) {
1012 return FALSE;
1013 }
1014
1015 // CRM-18480: Cancel the process if the contact is already deleted
1016 if (isset($result['values'][$cid]['contact_is_deleted']) && !empty($result['values'][$cid]['contact_is_deleted'])) {
1017 CRM_Core_Error::fatal(ts('Cannot merge because the \'%1\' contact (ID %2) has been deleted.', array(1 => $moniker, 2 => $cid)));
1018 }
1019
1020 $$moniker = $result['values'][$cid];
1021 }
1022
1023 $fields = CRM_Contact_DAO_Contact::fields();
1024
1025 // FIXME: there must be a better way
1026 foreach (array('main', 'other') as $moniker) {
1027 $contact = &$$moniker;
1028 $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
1029 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
1030 $specialValues[$moniker] = array(
1031 'preferred_communication_method' => $value,
1032 'communication_style_id' => $value,
1033 );
1034
1035 if (!empty($contact['preferred_communication_method'])) {
1036 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
1037 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
1038 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
1039 }
1040 $names = array(
1041 'preferred_communication_method' => array(
1042 'newName' => 'preferred_communication_method_display',
1043 'groupName' => 'preferred_communication_method',
1044 ),
1045 );
1046 CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
1047
1048 if (!empty($contact['communication_style'])) {
1049 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
1050 }
1051 }
1052
1053 static $optionValueFields = array();
1054 if (empty($optionValueFields)) {
1055 $optionValueFields = CRM_Core_OptionValue::getFields();
1056 }
1057 foreach ($optionValueFields as $field => $params) {
1058 $fields[$field]['title'] = $params['title'];
1059 }
1060
1061 $compareFields = self::retrieveFields($main, $other);
1062
1063 $rows = $elements = $relTableElements = $migrationInfo = array();
1064
1065 foreach ($compareFields['contact'] as $field) {
1066 if ($field == 'contact_sub_type') {
1067 // CRM-15681 don't display sub-types in UI
1068 continue;
1069 }
1070 foreach (array('main', 'other') as $moniker) {
1071 $contact = &$$moniker;
1072 $value = CRM_Utils_Array::value($field, $contact);
1073 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
1074 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
1075 }
1076 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
1077 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
1078 if ($value) {
1079 $value = str_replace('-', '', $value);
1080 $label = CRM_Utils_Date::customFormat($label);
1081 }
1082 else {
1083 $value = "null";
1084 }
1085 }
1086 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
1087 if ($label === '0') {
1088 $label = ts('[ ]');
1089 }
1090 if ($label === '1') {
1091 $label = ts('[x]');
1092 }
1093 }
1094 elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
1095 $label = CRM_Utils_Array::value('individual_prefix', $contact);
1096 $value = CRM_Utils_Array::value('prefix_id', $contact);
1097 $field = 'prefix_id';
1098 }
1099 elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
1100 $label = CRM_Utils_Array::value('individual_suffix', $contact);
1101 $value = CRM_Utils_Array::value('suffix_id', $contact);
1102 $field = 'suffix_id';
1103 }
1104 elseif ($field == 'gender_id' && !empty($value)) {
1105 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
1106 $label = $genderOptions['values'][$value];
1107 }
1108 elseif ($field == 'current_employer_id' && !empty($value)) {
1109 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
1110 }
1111 $rows["move_$field"][$moniker] = $label;
1112 if ($moniker == 'other') {
1113 //CRM-14334
1114 if ($value === NULL || $value == '') {
1115 $value = 'null';
1116 }
1117 if ($value === 0 or $value === '0') {
1118 $value = $qfZeroBug;
1119 }
1120 if (is_array($value) && empty($value[1])) {
1121 $value[1] = NULL;
1122 }
1123
1124 // Display a checkbox to migrate, only if the values are different
1125 if ($value != $main[$field]) {
1126 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1127 }
1128
1129 $migrationInfo["move_$field"] = $value;
1130 }
1131 }
1132 $rows["move_$field"]['title'] = $fields[$field]['title'];
1133 }
1134
1135 // Handle location blocks.
1136 // @todo OpenID not in API yet, so is not supported here.
1137
1138 // Set up useful information about the location blocks
1139 $locationBlocks = self::getLocationBlockInfo();
1140
1141 $locations = array(
1142 'main' => array(),
1143 'other' => array(),
1144 );
1145
1146 // @todo This could probably be defined and used earlier
1147 $mergeTargets = array(
1148 'main' => $mainId,
1149 'other' => $otherId,
1150 );
1151
1152 foreach ($locationBlocks as $blockName => $blockInfo) {
1153
1154 // Collect existing fields from both 'main' and 'other' contacts first
1155 // This allows us to match up location/types when building the table rows
1156 foreach ($mergeTargets as $moniker => $cid) {
1157 $cnt = 1;
1158 $searchParams = array(
1159 'version' => 3,
1160 'contact_id' => $cid,
1161 // CRM-17556 Order by field-specific criteria
1162 'options' => array(
1163 'sort' => $blockInfo['sortString'],
1164 ),
1165 );
1166 $values = civicrm_api($blockName, 'get', $searchParams);
1167 if ($values['count']) {
1168 $cnt = 0;
1169 foreach ($values['values'] as $index => $value) {
1170 $locations[$moniker][$blockName][$cnt] = $value;
1171 // Fix address display
1172 $display = '';
1173 if ($blockName == 'address') {
1174 CRM_Core_BAO_Address::fixAddress($value);
1175 $display = CRM_Utils_Address::format($value);
1176 $locations[$moniker][$blockName][$cnt]['display'] = $display;
1177 }
1178
1179 $cnt++;
1180 }
1181 }
1182 }
1183
1184 // Now, build the table rows appropriately, based off the information on
1185 // the 'other' contact
1186 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1187 foreach ($locations['other'][$blockName] as $count => $value) {
1188
1189 $displayValue = $value[$blockInfo['displayField']];
1190
1191 // Add this value to the table rows
1192 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1193
1194 // CRM-17556 Only display 'main' contact value if it's the same location + type
1195 // Look it up from main values...
1196
1197 $lookupLocation = FALSE;
1198 if ($blockInfo['hasLocation']) {
1199 $lookupLocation = $value['location_type_id'];
1200 }
1201
1202 $lookupType = FALSE;
1203 if ($blockInfo['hasType']) {
1204 $lookupType = $value[$blockInfo['hasType']];
1205 }
1206
1207 // Hold ID of main contact's matching block
1208 $mainContactBlockId = 0;
1209
1210 if (!empty($locations['main'][$blockName])) {
1211 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1212 // No location/type, or matching location and type
1213 if (
1214 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
1215 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
1216 ) {
1217 // Set this value as the default against the 'other' contact value
1218 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1219 $mainContactBlockId = $mainValueCheck['id'];
1220 break;
1221 }
1222 }
1223 }
1224
1225 // Add checkbox to migrate data from 'other' to 'main'
1226 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
1227
1228 // Flag up this field to skipMerge function (@todo: do we need to?)
1229 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1230
1231 // Add a hidden field to store the ID of the target main contact block
1232 $elements[] = array('hidden', "location_blocks[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
1233
1234 // Setup variables
1235 $thisTypeId = FALSE;
1236 $thisLocId = FALSE;
1237
1238 // Provide a select drop-down for the location's location type
1239 // eg: Home, Work...
1240
1241 $js = NULL;
1242
1243 if ($blockInfo['hasLocation']) {
1244
1245 // Load the location options for this entity
1246 $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
1247
1248 // JS lookup 'main' contact's location (if there are any)
1249 if (!empty($locations['main'][$blockName])) {
1250 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'locTypeId' );");
1251 }
1252
1253 $thisLocId = $value['location_type_id'];
1254
1255 // Put this field's location type at the top of the list
1256 $tmpIdList = $locationOptions['values'];
1257 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1258 unset($tmpIdList[$thisLocId]);
1259
1260 // Add the element
1261 $elements[] = array(
1262 'select',
1263 "location_blocks[$blockName][$count][locTypeId]",
1264 NULL,
1265 $defaultLocId + $tmpIdList,
1266 $js,
1267 );
1268
1269 // Add the relevant information to the $migrationInfo
1270 // Keep location-type-id same as that of other-contact
1271 // @todo Check this logic out
1272 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1273 if ($blockName != 'address') {
1274 $elements[] = array('advcheckbox', "location_blocks[{$blockName}][$count][operation]", NULL, ts('add new'));
1275 // always use add operation
1276 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1277 }
1278
1279 }
1280
1281 // Provide a select drop-down for the location's type/provider
1282 // eg websites: Google+, Facebook...
1283
1284 $js = NULL;
1285
1286 if ($blockInfo['hasType']) {
1287
1288 // Load the type options for this entity
1289 $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
1290
1291 // CRM-17556 Set up JS lookup of 'main' contact's value by type
1292 if (!empty($locations['main'][$blockName])) {
1293 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'typeTypeId' );");
1294 }
1295
1296 $thisTypeId = $value[$blockInfo['hasType']];
1297
1298 // Put this field's location type at the top of the list
1299 $tmpIdList = $typeOptions['values'];
1300 $defaultTypeId = array($thisTypeId => $tmpIdList[$thisTypeId]);
1301 unset($tmpIdList[$thisTypeId]);
1302
1303 // Add the element
1304 $elements[] = array(
1305 'select',
1306 "location_blocks[$blockName][$count][typeTypeId]",
1307 NULL,
1308 $defaultTypeId + $tmpIdList,
1309 $js,
1310 );
1311
1312 // Add the information to the migrationInfo
1313 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1314
1315 }
1316
1317 // Set the label for this row
1318 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
1319 if (!empty($thisLocId)) {
1320 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1321 }
1322 if (!empty($thisTypeId)) {
1323 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1324 }
1325 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1326
1327 } // End loop through 'other' locations of this type
1328
1329 } // End if 'other' location for this type exists
1330
1331 } // End loop through each location block entity
1332
1333 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1334 $config = CRM_Core_Config::singleton();
1335 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1336 $mainUser = NULL;
1337 if ($mainUfId) {
1338 // d6 compatible
1339 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1340 $mainUser = user_load($mainUfId);
1341 }
1342 elseif ($config->userFramework == 'Joomla') {
1343 $mainUser = JFactory::getUser($mainUfId);
1344 }
1345 }
1346 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1347 $otherUser = NULL;
1348 if ($otherUfId) {
1349 // d6 compatible
1350 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1351 $otherUser = user_load($otherUfId);
1352 }
1353 elseif ($config->userFramework == 'Joomla') {
1354 $otherUser = JFactory::getUser($otherUfId);
1355 }
1356 }
1357
1358 $relTables = CRM_Dedupe_Merger::relTables();
1359 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1360 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1361 foreach ($relTables as $name => $null) {
1362 if (!in_array($name, $activeRelTables) &&
1363 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1364 ) {
1365 unset($relTables[$name]);
1366 continue;
1367 }
1368
1369 $relTableElements[] = array('checkbox', "move_$name");
1370 $migrationInfo["move_$name"] = 1;
1371
1372 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1373 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1374 if ($name == 'rel_table_users') {
1375 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1376 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1377 $find = array('$ufid', '$ufname');
1378 if ($mainUser) {
1379 $replace = array($mainUfId, $mainUser->name);
1380 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1381 }
1382 if ($otherUser) {
1383 $replace = array($otherUfId, $otherUser->name);
1384 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1385 }
1386 }
1387 if ($name == 'rel_table_memberships') {
1388 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1389 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1390 }
1391 }
1392 foreach ($relTables as $name => $null) {
1393 $relTables["move_$name"] = $relTables[$name];
1394 unset($relTables[$name]);
1395 }
1396
1397 // handle custom fields
1398 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1,
1399 CRM_Utils_Array::value('contact_sub_type', $main)
1400 );
1401 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1,
1402 CRM_Utils_Array::value('contact_sub_type', $other)
1403 );
1404 CRM_Core_DAO::freeResult();
1405
1406 foreach ($otherTree as $gid => $group) {
1407 $foundField = FALSE;
1408 if (!isset($group['fields'])) {
1409 continue;
1410 }
1411
1412 foreach ($group['fields'] as $fid => $field) {
1413 if (in_array($fid, $compareFields['custom'])) {
1414 if (!$foundField) {
1415 $rows["custom_group_$gid"]['title'] = $group['title'];
1416 $foundField = TRUE;
1417 }
1418 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1419 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1420 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
1421 }
1422 }
1423 $value = "null";
1424 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1425 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1426 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
1427 if ($values['data'] === 0 || $values['data'] === '0') {
1428 $values['data'] = $qfZeroBug;
1429 }
1430 $value = ($values['data']) ? $values['data'] : $value;
1431 }
1432 }
1433 $rows["move_custom_$fid"]['title'] = $field['label'];
1434
1435 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1436 $migrationInfo["move_custom_$fid"] = $value;
1437 }
1438 }
1439 }
1440
1441 $result = array(
1442 'rows' => $rows,
1443 'elements' => $elements,
1444 'rel_table_elements' => $relTableElements,
1445 'rel_tables' => $relTables,
1446 'main_details' => $main,
1447 'other_details' => $other,
1448 'migration_info' => $migrationInfo,
1449 );
1450
1451 $result['main_details']['location_blocks'] = $locations['main'];
1452 $result['other_details']['location_blocks'] = $locations['other'];
1453
1454 return $result;
1455 }
1456
1457 /**
1458 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1459 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1460 * A superset of moveContactBelongings() function.
1461 *
1462 * @param int $mainId
1463 * Main contact with whom merge has to happen.
1464 * @param int $otherId
1465 * Duplicate contact which would be deleted after merge operation.
1466 *
1467 * @param $migrationInfo
1468 *
1469 * @return bool
1470 */
1471 public static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1472 if (empty($migrationInfo)) {
1473 return FALSE;
1474 }
1475
1476 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1477 $relTables = CRM_Dedupe_Merger::relTables();
1478 $moveTables = $locBlocks = $tableOperations = array();
1479 foreach ($migrationInfo as $key => $value) {
1480 if ($value == $qfZeroBug) {
1481 $value = '0';
1482 }
1483 if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) ||
1484 substr($key, 0, 12) == 'move_custom_') &&
1485 $value != NULL
1486 ) {
1487 $submitted[substr($key, 5)] = $value;
1488 }
1489
1490 // Set up initial information for handling migration of location blocks
1491 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1492 $locField = explode('_', $key);
1493 $fieldName = $locField[2];
1494 $fieldCount = $locField[3];
1495
1496 // Set up the operation type (add/overwrite)
1497 // Ignore operation for websites
1498 // @todo Tidy this up
1499 $operation = 0;
1500 if ($fieldName != 'website') {
1501 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1502 }
1503 // default operation is overwrite.
1504 if (!$operation) {
1505 $operation = 2;
1506 }
1507 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1508
1509 }
1510
1511 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1512 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1513 if (array_key_exists('operation', $migrationInfo)) {
1514 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1515 if (array_key_exists($key, $migrationInfo['operation'])) {
1516 $tableOperations[$table] = $migrationInfo['operation'][$key];
1517 }
1518 }
1519 }
1520 }
1521 }
1522
1523 // **** Do location related migration.
1524 // @todo Handle OpenID (not currently in API).
1525 if (!empty($locBlocks)) {
1526
1527 $locationBlocks = self::getLocationBlockInfo();
1528
1529 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
1530 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
1531
1532 foreach ($locBlocks as $name => $block) {
1533 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1534 continue;
1535 }
1536 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
1537 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1538 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1539
1540 foreach ($block as $blkCount => $values) {
1541
1542 // For the block which belongs to other-contact, link the location block to main-contact
1543 $otherBlockDAO = new $daoName();
1544 $otherBlockDAO->contact_id = $mainId;
1545
1546 // Get the ID of this block on the 'other' contact, otherwise skip
1547 $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
1548 if (!$otherBlockId) {
1549 continue;
1550 }
1551 $otherBlockDAO->id = $otherBlockId;
1552
1553 // Add/update location and type information from the form, if applicable
1554 if ($locationBlocks[$name]['hasLocation']) {
1555 $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1556 $otherBlockDAO->location_type_id = $locTypeId;
1557 }
1558 if ($locationBlocks[$name]['hasType']) {
1559 $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1560 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
1561 }
1562
1563 // Get main block ID
1564 $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1565
1566 // if main contact already has primary & billing, set the flags to 0.
1567 if ($primaryDAOId) {
1568 $otherBlockDAO->is_primary = 0;
1569 }
1570 if ($billingDAOId) {
1571 $otherBlockDAO->is_billing = 0;
1572 }
1573
1574 $operation = CRM_Utils_Array::value('operation', $values, 2);
1575 // overwrite - need to delete block which belongs to main-contact.
1576 if (!empty($mainBlockId) && ($operation == 2)) {
1577 $deleteDAO = new $daoName();
1578 $deleteDAO->id = $mainBlockId;
1579 $deleteDAO->find(TRUE);
1580
1581 // if we about to delete a primary / billing block, set the flags for new block
1582 // that we going to assign to main-contact
1583 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1584 $otherBlockDAO->is_primary = 1;
1585 }
1586 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1587 $otherBlockDAO->is_billing = 1;
1588 }
1589
1590 $deleteDAO->delete();
1591 $deleteDAO->free();
1592 }
1593
1594 $otherBlockDAO->update();
1595 $otherBlockDAO->free();
1596 }
1597 }
1598 }
1599
1600 // **** Do tables related migrations
1601 if (!empty($moveTables)) {
1602 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1603 unset($moveTables, $tableOperations);
1604 }
1605
1606 // **** Do contact related migrations
1607 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
1608
1609 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1610 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1611 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1612 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1613 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1614 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1615 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1616 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1617 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1618
1619 // fix custom fields so they're edible by createProfileContact()
1620 static $treeCache = array();
1621 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1622 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'],
1623 CRM_Core_DAO::$_nullObject, NULL, -1
1624 );
1625 }
1626 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1627
1628 $cFields = array();
1629 foreach ($cgTree as $key => $group) {
1630 if (!isset($group['fields'])) {
1631 continue;
1632 }
1633 foreach ($group['fields'] as $fid => $field) {
1634 $cFields[$fid]['attributes'] = $field;
1635 }
1636 }
1637
1638 if (!isset($submitted)) {
1639 $submitted = array();
1640 }
1641 foreach ($submitted as $key => $value) {
1642 if (substr($key, 0, 7) == 'custom_') {
1643 $fid = (int) substr($key, 7);
1644 if (empty($cFields[$fid])) {
1645 continue;
1646 }
1647 $htmlType = $cFields[$fid]['attributes']['html_type'];
1648 switch ($htmlType) {
1649 case 'File':
1650 $customFiles[] = $fid;
1651 unset($submitted["custom_$fid"]);
1652 break;
1653
1654 case 'Select Country':
1655 case 'Select State/Province':
1656 $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
1657 break;
1658
1659 case 'CheckBox':
1660 case 'AdvMulti-Select':
1661 case 'Multi-Select':
1662 case 'Multi-Select Country':
1663 case 'Multi-Select State/Province':
1664 // Merge values from both contacts for multivalue fields, CRM-4385
1665 // get the existing custom values from db.
1666 $customParams = array('entityID' => $mainId, $key => TRUE);
1667 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
1668 if (!empty($customfieldValues[$key])) {
1669 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1670 if (is_array($existingValue) && !empty($existingValue)) {
1671 $mergeValue = $submmtedCustomValue = array();
1672 if ($value) {
1673 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1674 }
1675
1676 //hack to remove null and duplicate values from array.
1677 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1678 if ($v != '' && !in_array($v, $mergeValue)) {
1679 $mergeValue[] = $v;
1680 }
1681 }
1682
1683 //keep state and country as array format.
1684 //for checkbox and m-select format w/ VALUE_SEPARATOR
1685 if (in_array($htmlType, array(
1686 'CheckBox',
1687 'Multi-Select',
1688 'AdvMulti-Select',
1689 ))) {
1690 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1691 $mergeValue
1692 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1693 }
1694 else {
1695 $submitted[$key] = $mergeValue;
1696 }
1697 }
1698 }
1699 elseif (in_array($htmlType, array(
1700 'Multi-Select Country',
1701 'Multi-Select State/Province',
1702 ))) {
1703 //we require submitted values should be in array format
1704 if ($value) {
1705 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1706 //hack to remove null values from array.
1707 $mergeValue = array();
1708 foreach ($mergeValueArray as $k => $v) {
1709 if ($v != '') {
1710 $mergeValue[] = $v;
1711 }
1712 }
1713 $submitted[$key] = $mergeValue;
1714 }
1715 }
1716 break;
1717
1718 default:
1719 break;
1720 }
1721 }
1722 }
1723
1724 // **** Do file custom fields related migrations
1725 // FIXME: move this someplace else (one of the BAOs) after discussing
1726 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1727 // like, delete a file...
1728
1729 if (!isset($customFiles)) {
1730 $customFiles = array();
1731 }
1732 foreach ($customFiles as $customId) {
1733 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1734
1735 // get the contact_id -> file_id mapping
1736 $fileIds = array();
1737 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1738 $dao = CRM_Core_DAO::executeQuery($sql);
1739 while ($dao->fetch()) {
1740 $fileIds[$dao->entity_id] = $dao->file_id;
1741 }
1742 $dao->free();
1743
1744 // delete the main contact's file
1745 if (!empty($fileIds[$mainId])) {
1746 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1747 }
1748
1749 // move the other contact's file to main contact
1750 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1751 if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
1752 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1753 }
1754 else {
1755 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1756 }
1757 CRM_Core_DAO::executeQuery($sql);
1758
1759 if (CRM_Core_DAO::singleValueQuery("
1760 SELECT id
1761 FROM civicrm_entity_file
1762 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1763 ) {
1764 $sql = "
1765 UPDATE civicrm_entity_file
1766 SET entity_id = {$mainId}
1767 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1768 }
1769 else {
1770 $sql = "
1771 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1772 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1773 }
1774 CRM_Core_DAO::executeQuery($sql);
1775 }
1776
1777 // move view only custom fields CRM-5362
1778 $viewOnlyCustomFields = array();
1779 foreach ($submitted as $key => $value) {
1780 $fid = (int) substr($key, 7);
1781 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1782 $viewOnlyCustomFields[$key] = $value;
1783 }
1784 }
1785
1786 // special case to set values for view only, CRM-5362
1787 if (!empty($viewOnlyCustomFields)) {
1788 $viewOnlyCustomFields['entityID'] = $mainId;
1789 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1790 }
1791
1792 if (CRM_Core_Permission::check('merge duplicate contacts') &&
1793 CRM_Core_Permission::check('delete contacts')
1794 ) {
1795 // if ext id is submitted then set it null for contact to be deleted
1796 if (!empty($submitted['external_identifier'])) {
1797 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1798 CRM_Core_DAO::executeQuery($query);
1799 }
1800
1801 civicrm_api3('contact', 'delete', array('id' => $otherId));
1802 CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
1803 }
1804 // FIXME: else part
1805 // else {
1806 // CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') );
1807 // }
1808
1809 // CRM-15681 merge sub_types
1810 if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
1811 if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
1812 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1813 }
1814 else {
1815 $submitted['contact_sub_type'] = $other_sub_types;
1816 }
1817 }
1818
1819 // **** Update contact related info for the main contact
1820 if (!empty($submitted)) {
1821 $submitted['contact_id'] = $mainId;
1822
1823 //update current employer field
1824 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1825 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1826 $submitted['current_employer'] = $submitted['current_employer_id'];
1827 }
1828 else {
1829 $submitted['current_employer'] = '';
1830 }
1831 unset($submitted['current_employer_id']);
1832 }
1833
1834 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1835 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1836 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1837 }
1838 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1839 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1840 }
1841
1842 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
1843 }
1844
1845 CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
1846 self::createMergeActivities($mainId, $otherId);
1847
1848 return TRUE;
1849 }
1850
1851 /**
1852 * Get fields in the contact table suitable for merging.
1853 *
1854 * @return array
1855 * Array of field names to be potentially merged.
1856 */
1857 public static function getContactFields() {
1858 $contactFields = CRM_Contact_DAO_Contact::fields();
1859 $invalidFields = array(
1860 'api_key',
1861 'created_date',
1862 'display_name',
1863 'hash',
1864 'id',
1865 'modified_date',
1866 'primary_contact_id',
1867 'sort_name',
1868 'user_unique_id',
1869 );
1870 foreach ($contactFields as $field => $value) {
1871 if (in_array($field, $invalidFields)) {
1872 unset($contactFields[$field]);
1873 }
1874 }
1875 return array_keys($contactFields);
1876 }
1877
1878 /**
1879 * Added for CRM-12695
1880 * Based on the contactID provided
1881 * add/update membership(s) to related contacts
1882 *
1883 * @param int $contactID
1884 */
1885 public static function addMembershipToRealtedContacts($contactID) {
1886 $dao = new CRM_Member_DAO_Membership();
1887 $dao->contact_id = $contactID;
1888 $dao->is_test = 0;
1889 $dao->find();
1890
1891 //checks membership of contact itself
1892 while ($dao->fetch()) {
1893 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1894 if ($relationshipTypeId) {
1895 $membershipParams = array(
1896 'id' => $dao->id,
1897 'contact_id' => $dao->contact_id,
1898 'membership_type_id' => $dao->membership_type_id,
1899 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1900 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1901 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1902 'source' => $dao->source,
1903 'status_id' => $dao->status_id,
1904 );
1905 // create/update membership(s) for related contact(s)
1906 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1907 } // end of if relationshipTypeId
1908 }
1909 }
1910
1911 /**
1912 * Add custom tables that extend contacts to the list of contact references.
1913 *
1914 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
1915 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
1916 * - the down side is it is not cached.
1917 *
1918 * Further changes should be include tests in the CRM_Core_MergerTest class
1919 * to ensure that disabled, subtype, multiple etc groups are still captured.
1920 *
1921 * @param array $cidRefs
1922 */
1923 public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
1924 $customValueTables = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
1925 $customValueTables->find();
1926 while ($customValueTables->fetch()) {
1927 $cidRefs[$customValueTables->table_name] = array('entity_id');
1928 }
1929 }
1930
1931 /**
1932 * Create activities tracking the merge on affected contacts.
1933 *
1934 * @param int $mainId
1935 * @param int $otherId
1936 *
1937 * @throws \CiviCRM_API3_Exception
1938 */
1939 public static function createMergeActivities($mainId, $otherId) {
1940 $params = array(
1941 1 => $otherId,
1942 2 => $mainId,
1943 );
1944 $activity = civicrm_api3('activity', 'create', array(
1945 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1946 $mainId,
1947 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1948 'target_contact_id' => $mainId,
1949 'activity_type_id' => 'Contact Merged',
1950 'status_id' => 'Completed',
1951 ));
1952 if (civicrm_api3('Setting', 'getvalue', array('name' => 'contact_undelete', 'group' => 'CiviCRM Preferences'))) {
1953 civicrm_api3('activity', 'create', array(
1954 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1955 $otherId,
1956 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1957 'target_contact_id' => $otherId,
1958 'activity_type_id' => 'Contact Deleted by Merge',
1959 'parent_id' => $activity['id'],
1960 'status_id' => 'Completed',
1961 ));
1962 }
1963 }
1964
1965 /**
1966 * Get Duplicate Pairs based on a rule for a group.
1967 *
1968 * @param int $rule_group_id
1969 * @param int $group_id
1970 * @param bool $reloadCacheIfEmpty
1971 * @param int $batchLimit
1972 * @param bool $isSelected
1973 *
1974 * @return array
1975 * Array of matches meeting the criteria.
1976 */
1977 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected) {
1978 $where = self::getWhereString($batchLimit, $isSelected);
1979 $cacheKeyString = self::getMergeCacheKeyString($rule_group_id, $group_id);
1980 $join = self::getJoinOnDedupeTable();
1981 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
1982 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1983 // If we haven't found any dupes, probably cache is empty.
1984 // Try filling cache and give another try.
1985 CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $cacheKeyString);
1986 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
1987 return $dupePairs;
1988 }
1989 return $dupePairs;
1990 }
1991
1992 /**
1993 * Get the cache key string for the merge action.
1994 *
1995 * @param int $rule_group_id
1996 * @param int $group_id
1997 *
1998 * @return string
1999 */
2000 public static function getMergeCacheKeyString($rule_group_id, $group_id) {
2001 $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
2002 $cacheKeyString = "merge {$contactType}";
2003 $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
2004 $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
2005 return $cacheKeyString;
2006 }
2007
2008 }