Merge pull request #8636 from eileenmcnaughton/slow_query
[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, wheras 'aggressive'
587 * mode does a force merge.
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 * @param array $criteria
594 * Criteria to use in the filter.
595 *
596 * @param bool $checkPermissions
597 * Respect logged in user permissions.
598 *
599 * @return array|bool
600 */
601 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $batchLimit = 1, $isSelected = 2, $criteria = array(), $checkPermissions = TRUE) {
602 $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
603 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
604 $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, '', ($mode == 'aggressive'), $criteria, $checkPermissions);
605
606 $cacheParams = array(
607 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
608 // @todo stop passing these parameters in & instead calculate them in the merge function based
609 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
610 'join' => self::getJoinOnDedupeTable(),
611 'where' => self::getWhereString($batchLimit, $isSelected),
612 );
613 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance, $checkPermissions);
614 }
615
616 /**
617 * Get the string to join the prevnext cache to the dedupe table.
618 *
619 * @return string
620 * The join string to join prevnext cache on the dedupe table.
621 */
622 public static function getJoinOnDedupeTable() {
623 return "
624 LEFT JOIN civicrm_dedupe_exception de
625 ON (
626 pn.entity_id1 = de.contact_id1
627 AND pn.entity_id2 = de.contact_id2 )
628 ";
629 }
630
631 /**
632 * Get where string for dedupe join.
633 *
634 * @param int $batchLimit
635 * @param bool $isSelected
636 *
637 * @return string
638 */
639 protected static function getWhereString($batchLimit, $isSelected) {
640 $where = "de.id IS NULL";
641 if ($isSelected === 0 || $isSelected === 1) {
642 $where .= " AND pn.is_selected = {$isSelected}";
643 }
644 // else consider all dupe pairs
645 // @todo Adding limit to Where??!!
646 $where .= " LIMIT {$batchLimit}";
647 return $where;
648 }
649
650 public static function updateMergeStats($cacheKeyString, $result = array()) {
651 // gather latest stats
652 $merged = count($result['merged']);
653 $skipped = count($result['skipped']);
654
655 if ($merged <= 0 && $skipped <= 0) {
656 return;
657 }
658
659 // get previous stats
660 $previousStats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
661 if (!empty($previousStats)) {
662 if ($previousStats[0]['merged']) {
663 $merged = $merged + $previousStats[0]['merged'];
664 }
665 if ($previousStats[0]['skipped']) {
666 $skipped = $skipped + $previousStats[0]['skipped'];
667 }
668 }
669
670 // delete old stats
671 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
672
673 // store the updated stats
674 $data = array(
675 'merged' => $merged,
676 'skipped' => $skipped,
677 );
678 $data = CRM_Core_DAO::escapeString(serialize($data));
679
680 $values = array();
681 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
682 CRM_Core_BAO_PrevNextCache::setItem($values);
683 }
684
685 /**
686 * Delete information about merges for the given string.
687 *
688 * @param $cacheKeyString
689 */
690 public static function resetMergeStats($cacheKeyString) {
691 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
692 }
693
694 public static function getMergeStats($cacheKeyString) {
695 $stats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
696 if (!empty($stats)) {
697 $stats = $stats[0];
698 }
699 return $stats;
700 }
701
702 public static function getMergeStatsMsg($cacheKeyString) {
703 $msg = '';
704 $stats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
705 if (!empty($stats['merged'])) {
706 $msg = "{$stats['merged']} " . ts('Contact(s) were merged.');
707 }
708 if (!empty($stats['skipped'])) {
709 $msg .= $stats['skipped'] . ts(' Contact(s) were skipped.');
710 }
711 return $msg;
712 }
713
714 /**
715 * Merge given set of contacts. Performs core operation.
716 *
717 * @param array $dupePairs
718 * Set of pair of contacts for whom merge is to be done.
719 * @param array $cacheParams
720 * Prev-next-cache params based on which next pair of contacts are computed.
721 * Generally used with batch-merge.
722 * @param string $mode
723 * Helps decide how to behave when there are conflicts.
724 * A 'safe' value skips the merge if there are any un-resolved conflicts.
725 * Does a force merge otherwise (aggressive mode).
726 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
727 * Whether to let api decide which contact to retain and which to delete.
728 *
729 * @param bool $redirectForPerformance
730 * Redirect to a url for batch processing.
731 *
732 * @param bool $checkPermissions
733 * Respect logged in user permissions.
734 *
735 * @return array|bool
736 */
737 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
738 $autoFlip = TRUE, $redirectForPerformance = FALSE, $checkPermissions = TRUE
739 ) {
740 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
741 $resultStats = array('merged' => array(), 'skipped' => array());
742
743 // we don't want dupe caching to get reset after every-merge, and therefore set the
744 // doNotResetCache flag
745 $config = CRM_Core_Config::singleton();
746 $config->doNotResetCache = 1;
747 $deletedContacts = array();
748
749 while (!empty($dupePairs)) {
750 foreach ($dupePairs as $index => $dupes) {
751 if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) {
752 unset($dupePairs[$index]);
753 continue;
754 }
755 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
756 $mainId = $dupes['dstID'];
757 $otherId = $dupes['srcID'];
758
759 if (!$mainId || !$otherId) {
760 // return error
761 return FALSE;
762 }
763
764 // Generate var $migrationInfo. The variable structure is exactly same as
765 // $formValues submitted during a UI merge for a pair of contacts.
766 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions);
767
768 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
769
770 // add additional details that we might need to resolve conflicts
771 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
772 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
773 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
774
775 // go ahead with merge if there is no conflict
776 $conflicts = array();
777 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
778 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
779 $resultStats['merged'][] = array('main_id' => $mainId, 'other_id' => $otherId);
780 $deletedContacts[] = $otherId;
781 }
782 else {
783 $resultStats['skipped'][] = array('main_id' => $mainId, 'other_id' => $otherId);
784 }
785
786 // store any conflicts
787 if (!empty($conflicts)) {
788 foreach ($conflicts as $key => $dnc) {
789 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
790 }
791 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
792 }
793 else {
794 // delete entry from PrevNextCache table so we don't consider the pair next time
795 // pair may have been flipped, so make sure we delete using both orders
796 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
797 }
798
799 CRM_Core_DAO::freeResult();
800 unset($rowsElementsAndInfo, $migrationInfo);
801 }
802
803 if ($cacheKeyString && !$redirectForPerformance) {
804 // retrieve next pair of dupes
805 // @todo call getDuplicatePairs.
806 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
807 $cacheParams['join'],
808 $cacheParams['where'],
809 0,
810 0,
811 array(),
812 '',
813 FALSE
814 );
815 }
816 else {
817 // do not proceed. Terminate the loop
818 unset($dupePairs);
819 }
820 }
821
822 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
823 return $resultStats;
824 }
825
826 /**
827 * A function which uses various rules / algorithms for choosing which contact to bias to
828 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
829 *
830 * @param int $mainId
831 * Main contact with whom merge has to happen.
832 * @param int $otherId
833 * Duplicate contact which would be deleted after merge operation.
834 * @param array $migrationInfo
835 * Array of information about which elements to merge.
836 * @param string $mode
837 * Helps decide how to behave when there are conflicts.
838 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
839 * - Does a force merge otherwise (aggressive mode).
840 *
841 * @param array $conflicts
842 *
843 * @return bool
844 */
845 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
846
847 $originalMigrationInfo = $migrationInfo;
848 foreach ($migrationInfo as $key => $val) {
849 if ($val === "null") {
850 // Rule: Never overwrite with an empty value (in any mode)
851 unset($migrationInfo[$key]);
852 continue;
853 }
854 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
855 substr($key, 0, 12) == 'move_custom_'
856 ) and $val != NULL
857 ) {
858 // Rule: If both main-contact, and other-contact have a field with a
859 // different value, then let $mode decide if to merge it or not
860 if (
861 (!empty($migrationInfo['rows'][$key]['main'])
862 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
863 // is probably true for other fields too - e.g. 'do_not_email' but
864 // leaving that investigation as a @todo - until tests can be written.
865 // Note the handling of this has test coverage - although the data-typing
866 // of '0' feels flakey we have insurance.
867 || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
868 )
869 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
870 ) {
871
872 // note it down & lets wait for response from the hook.
873 // For no response $mode will decide if to skip this merge
874 $conflicts[$key] = NULL;
875 }
876 }
877 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
878 $locField = explode('_', $key);
879 $fieldName = $locField[2];
880 $fieldCount = $locField[3];
881
882 // Rule: Catch address conflicts (same address type on both contacts)
883 if ($fieldName == 'address') {
884 if (
885 isset($migrationInfo['main_details']['location_blocks']['address']) &&
886 !empty($migrationInfo['main_details']['location_blocks']['address'])
887 ) {
888 $otherAddresses = $migrationInfo['other_details']['location_blocks']['address'];
889 $otherAddressLookup = array();
890 foreach ($otherAddresses as $otherAddressIndex => $otherAddress) {
891 $otherAddressLookup[$otherAddress['location_type_id']] = $otherAddressIndex;
892 }
893 // Look for this LocTypeId in the results
894 // @todo This can be streamlined using array_column() in PHP 5.5+
895 foreach ($migrationInfo['main_details']['location_blocks']['address'] as $addressKey => $addressRecord) {
896 $otherAddressIndex = CRM_Utils_Array::value($addressRecord['location_type_id'], $otherAddressLookup);
897 $hasMatchingAddress = FALSE;
898 foreach ($otherAddresses as $otherAddress) {
899 if (self::addressIsSame($addressRecord, $otherAddress)) {
900 $hasMatchingAddress = TRUE;
901 }
902 }
903 if ($hasMatchingAddress) {
904 unset($migrationInfo[$key]);
905 }
906 elseif (!empty($otherAddresses[$otherAddressIndex]) && !self::addressIsSame($addressRecord, $otherAddresses[$otherAddressIndex])) {
907 $conflicts[$key] = NULL;
908 break;
909 }
910 }
911 }
912 }
913 // For other locations, don't merge/add if the values are the same
914 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
915 unset($migrationInfo[$key]);
916 }
917 }
918 }
919
920 // A hook to implement other algorithms for choosing which contact to bias to when
921 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
922 // merge happens with new values filled in here. For a particular field / row not to be merged
923 // field should be unset from fields_in_conflict.
924 $migrationData = array(
925 'old_migration_info' => $originalMigrationInfo,
926 'mode' => $mode,
927 'fields_in_conflict' => $conflicts,
928 'merge_mode' => $mode,
929 'migration_info' => $migrationInfo,
930 );
931 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
932 $conflicts = $migrationData['fields_in_conflict'];
933 // allow hook to override / manipulate migrationInfo as well
934 $migrationInfo = $migrationData['migration_info'];
935
936 if (!empty($conflicts)) {
937 foreach ($conflicts as $key => $val) {
938 if ($val === NULL and $mode == 'safe') {
939 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
940 return TRUE;
941 }
942 else {
943 // copy over the resolved values
944 $migrationInfo[$key] = $val;
945 }
946 }
947 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
948 if (array_key_exists('skip_merge', $migrationData)) {
949 return (bool) $migrationData['skip_merge'];
950 }
951 }
952 return FALSE;
953 }
954
955 /**
956 * Compare 2 addresses to see if they are the same.
957 *
958 * @param array $mainAddress
959 * @param array $comparisonAddress
960 *
961 * @return bool
962 */
963 static protected function addressIsSame($mainAddress, $comparisonAddress) {
964 $keysToIgnore = array('id', 'is_primary', 'is_billing', 'manual_geo_code', 'contact_id');
965 foreach ($comparisonAddress as $field => $value) {
966 if (in_array($field, $keysToIgnore)) {
967 continue;
968 }
969 if (!empty($value) && $mainAddress[$field] != $value) {
970 return FALSE;
971 }
972 }
973 return TRUE;
974 }
975
976 /**
977 * A function to build an array of information about location blocks that is
978 * required when merging location fields
979 *
980 * @return array
981 */
982 public static function getLocationBlockInfo() {
983 $locationBlocks = array(
984 'address' => array(
985 'label' => 'Address',
986 'displayField' => 'display',
987 'sortString' => 'location_type_id',
988 'hasLocation' => TRUE,
989 'hasType' => FALSE,
990 ),
991 'email' => array(
992 'label' => 'Email',
993 'displayField' => 'email',
994 'sortString' => 'location_type_id',
995 'hasLocation' => TRUE,
996 'hasType' => FALSE,
997 ),
998 'im' => array(
999 'label' => 'IM',
1000 'displayField' => 'name',
1001 'sortString' => 'location_type_id,provider_id',
1002 'hasLocation' => TRUE,
1003 'hasType' => 'provider_id',
1004 ),
1005 'phone' => array(
1006 'label' => 'Phone',
1007 'displayField' => 'phone',
1008 'sortString' => 'location_type_id,phone_type_id',
1009 'hasLocation' => TRUE,
1010 'hasType' => 'phone_type_id',
1011 ),
1012 'website' => array(
1013 'label' => 'Website',
1014 'displayField' => 'url',
1015 'sortString' => 'website_type_id',
1016 'hasLocation' => FALSE,
1017 'hasType' => 'website_type_id',
1018 ),
1019 );
1020 return $locationBlocks;
1021 }
1022
1023 /**
1024 * A function to build an array of information required by merge function and the merge UI.
1025 *
1026 * @param int $mainId
1027 * Main contact with whom merge has to happen.
1028 * @param int $otherId
1029 * Duplicate contact which would be deleted after merge operation.
1030 * @param bool $checkPermissions
1031 * Should the logged in user's permissions be ignore. Setting this to false is
1032 * highly risky as it could cause data to be lost due to conflicts not showing up.
1033 * OTOH there is a risk a merger might view custom data they do not have permission to.
1034 * Hence for now only making this really explicit and making it reflect perms in
1035 * an api call.
1036 *
1037 * @todo review permissions issue!
1038 *
1039 * @return array|bool|int
1040 *
1041 * rows => An array of arrays, each is row of merge information for the table
1042 * Format: move_fieldname, eg: move_contact_type
1043 * main => Value associated with the main contact
1044 * other => Value associated with the other contact
1045 * title => The title of the field to display in the merge table
1046 *
1047 * elements => An array of form elements for the merge UI
1048 *
1049 * rel_table_elements => An array of form elements for the merge UI for
1050 * entities related to the contact (eg: checkbox to move 'mailings')
1051 *
1052 * rel_tables => Stores the tables that have related entities for the contact
1053 * for example mailings, groups
1054 *
1055 * main_details => An array of core contact field values, eg: first_name, etc.
1056 * location_blocks => An array of location block data for the main contact
1057 * stored as the 'result' of an API call.
1058 * eg: main_details['location_blocks']['address'][0]['id']
1059 * eg: main_details['location_blocks']['email'][1]['id']
1060 *
1061 * other_details => As above, but for the 'other' contact
1062 *
1063 * migration_info => Stores the 'default' merge actions for each field which
1064 * is used when programatically merging contacts. It contains instructions
1065 * to move all fields from the 'other' contact to the 'main' contact, as
1066 * though the form had been submitted with those options.
1067 *
1068 * @throws \CRM_Core_Exception
1069 * @throws \CiviCRM_API3_Exception
1070 * @throws \Exception
1071 */
1072 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1073 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1074
1075 // Fetch contacts
1076 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
1077 $params = array(
1078 'contact_id' => $cid,
1079 'version' => 3,
1080 'return' => array_merge(array('display_name'), self::getContactFields()),
1081 );
1082 $result = civicrm_api('contact', 'get', $params);
1083
1084 if (empty($result['values'][$cid]['contact_type'])) {
1085 return FALSE;
1086 }
1087
1088 // CRM-18480: Cancel the process if the contact is already deleted
1089 if (isset($result['values'][$cid]['contact_is_deleted']) && !empty($result['values'][$cid]['contact_is_deleted'])) {
1090 throw new CRM_Core_Exception(ts('Cannot merge because the \'%1\' contact (ID %2) has been deleted.', array(1 => $moniker, 2 => $cid)));
1091 }
1092
1093 $$moniker = $result['values'][$cid];
1094 }
1095
1096 $fields = CRM_Contact_DAO_Contact::fields();
1097
1098 // FIXME: there must be a better way
1099 foreach (array('main', 'other') as $moniker) {
1100 $contact = &$$moniker;
1101 $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
1102 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
1103 $specialValues[$moniker] = array(
1104 'preferred_communication_method' => $value,
1105 'communication_style_id' => $value,
1106 );
1107
1108 if (!empty($contact['preferred_communication_method'])) {
1109 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
1110 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
1111 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
1112 }
1113 $names = array(
1114 'preferred_communication_method' => array(
1115 'newName' => 'preferred_communication_method_display',
1116 'groupName' => 'preferred_communication_method',
1117 ),
1118 );
1119 CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
1120
1121 if (!empty($contact['communication_style'])) {
1122 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
1123 }
1124 }
1125
1126 static $optionValueFields = array();
1127 if (empty($optionValueFields)) {
1128 $optionValueFields = CRM_Core_OptionValue::getFields();
1129 }
1130 foreach ($optionValueFields as $field => $params) {
1131 $fields[$field]['title'] = $params['title'];
1132 }
1133
1134 $compareFields = self::retrieveFields($main, $other);
1135
1136 $rows = $elements = $relTableElements = $migrationInfo = array();
1137
1138 foreach ($compareFields['contact'] as $field) {
1139 if ($field == 'contact_sub_type') {
1140 // CRM-15681 don't display sub-types in UI
1141 continue;
1142 }
1143 foreach (array('main', 'other') as $moniker) {
1144 $contact = &$$moniker;
1145 $value = CRM_Utils_Array::value($field, $contact);
1146 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
1147 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
1148 }
1149 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
1150 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
1151 if ($value) {
1152 $value = str_replace('-', '', $value);
1153 $label = CRM_Utils_Date::customFormat($label);
1154 }
1155 else {
1156 $value = "null";
1157 }
1158 }
1159 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
1160 if ($label === '0') {
1161 $label = ts('[ ]');
1162 }
1163 if ($label === '1') {
1164 $label = ts('[x]');
1165 }
1166 }
1167 elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
1168 $label = CRM_Utils_Array::value('individual_prefix', $contact);
1169 $value = CRM_Utils_Array::value('prefix_id', $contact);
1170 $field = 'prefix_id';
1171 }
1172 elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
1173 $label = CRM_Utils_Array::value('individual_suffix', $contact);
1174 $value = CRM_Utils_Array::value('suffix_id', $contact);
1175 $field = 'suffix_id';
1176 }
1177 elseif ($field == 'gender_id' && !empty($value)) {
1178 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
1179 $label = $genderOptions['values'][$value];
1180 }
1181 elseif ($field == 'current_employer_id' && !empty($value)) {
1182 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
1183 }
1184 $rows["move_$field"][$moniker] = $label;
1185 if ($moniker == 'other') {
1186 //CRM-14334
1187 if ($value === NULL || $value == '') {
1188 $value = 'null';
1189 }
1190 if ($value === 0 or $value === '0') {
1191 $value = $qfZeroBug;
1192 }
1193 if (is_array($value) && empty($value[1])) {
1194 $value[1] = NULL;
1195 }
1196
1197 // Display a checkbox to migrate, only if the values are different
1198 if ($value != $main[$field]) {
1199 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1200 }
1201
1202 $migrationInfo["move_$field"] = $value;
1203 }
1204 }
1205 $rows["move_$field"]['title'] = $fields[$field]['title'];
1206 }
1207
1208 // Handle location blocks.
1209 // @todo OpenID not in API yet, so is not supported here.
1210
1211 // Set up useful information about the location blocks
1212 $locationBlocks = self::getLocationBlockInfo();
1213
1214 $locations = array(
1215 'main' => array(),
1216 'other' => array(),
1217 );
1218
1219 // @todo This could probably be defined and used earlier
1220 $mergeTargets = array(
1221 'main' => $mainId,
1222 'other' => $otherId,
1223 );
1224
1225 foreach ($locationBlocks as $blockName => $blockInfo) {
1226
1227 // Collect existing fields from both 'main' and 'other' contacts first
1228 // This allows us to match up location/types when building the table rows
1229 foreach ($mergeTargets as $moniker => $cid) {
1230 $cnt = 1;
1231 $searchParams = array(
1232 'version' => 3,
1233 'contact_id' => $cid,
1234 // CRM-17556 Order by field-specific criteria
1235 'options' => array(
1236 'sort' => $blockInfo['sortString'],
1237 ),
1238 );
1239 $values = civicrm_api($blockName, 'get', $searchParams);
1240 if ($values['count']) {
1241 $cnt = 0;
1242 foreach ($values['values'] as $index => $value) {
1243 $locations[$moniker][$blockName][$cnt] = $value;
1244 // Fix address display
1245 if ($blockName == 'address') {
1246 CRM_Core_BAO_Address::fixAddress($value);
1247 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address::format($value);
1248 }
1249
1250 $cnt++;
1251 }
1252 }
1253 }
1254
1255 // Now, build the table rows appropriately, based off the information on
1256 // the 'other' contact
1257 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1258 foreach ($locations['other'][$blockName] as $count => $value) {
1259
1260 $displayValue = $value[$blockInfo['displayField']];
1261
1262 // Add this value to the table rows
1263 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1264
1265 // CRM-17556 Only display 'main' contact value if it's the same location + type
1266 // Look it up from main values...
1267
1268 $lookupLocation = FALSE;
1269 if ($blockInfo['hasLocation']) {
1270 $lookupLocation = $value['location_type_id'];
1271 }
1272
1273 $lookupType = FALSE;
1274 if ($blockInfo['hasType']) {
1275 $lookupType = $value[$blockInfo['hasType']];
1276 }
1277
1278 // Hold ID of main contact's matching block
1279 $mainContactBlockId = 0;
1280
1281 if (!empty($locations['main'][$blockName])) {
1282 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1283 // No location/type, or matching location and type
1284 if (
1285 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
1286 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
1287 ) {
1288 // Set this value as the default against the 'other' contact value
1289 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1290 $mainContactBlockId = $mainValueCheck['id'];
1291 break;
1292 }
1293 }
1294 }
1295
1296 // Add checkbox to migrate data from 'other' to 'main'
1297 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
1298
1299 // Flag up this field to skipMerge function (@todo: do we need to?)
1300 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1301
1302 // Add a hidden field to store the ID of the target main contact block
1303 $elements[] = array('hidden', "location_blocks[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
1304
1305 // Setup variables
1306 $thisTypeId = FALSE;
1307 $thisLocId = FALSE;
1308
1309 // Provide a select drop-down for the location's location type
1310 // eg: Home, Work...
1311
1312 $js = NULL;
1313
1314 if ($blockInfo['hasLocation']) {
1315
1316 // Load the location options for this entity
1317 $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
1318
1319 // JS lookup 'main' contact's location (if there are any)
1320 if (!empty($locations['main'][$blockName])) {
1321 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'locTypeId' );");
1322 }
1323
1324 $thisLocId = $value['location_type_id'];
1325
1326 // Put this field's location type at the top of the list
1327 $tmpIdList = $locationOptions['values'];
1328 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1329 unset($tmpIdList[$thisLocId]);
1330
1331 // Add the element
1332 $elements[] = array(
1333 'select',
1334 "location_blocks[$blockName][$count][locTypeId]",
1335 NULL,
1336 $defaultLocId + $tmpIdList,
1337 $js,
1338 );
1339
1340 // Add the relevant information to the $migrationInfo
1341 // Keep location-type-id same as that of other-contact
1342 // @todo Check this logic out
1343 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1344 if ($blockName != 'address') {
1345 $elements[] = array('advcheckbox', "location_blocks[{$blockName}][$count][operation]", NULL, ts('add new'));
1346 // always use add operation
1347 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1348 }
1349
1350 }
1351
1352 // Provide a select drop-down for the location's type/provider
1353 // eg websites: Google+, Facebook...
1354
1355 $js = NULL;
1356
1357 if ($blockInfo['hasType']) {
1358
1359 // Load the type options for this entity
1360 $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
1361
1362 // CRM-17556 Set up JS lookup of 'main' contact's value by type
1363 if (!empty($locations['main'][$blockName])) {
1364 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'typeTypeId' );");
1365 }
1366
1367 $thisTypeId = $value[$blockInfo['hasType']];
1368
1369 // Put this field's location type at the top of the list
1370 $tmpIdList = $typeOptions['values'];
1371 $defaultTypeId = array($thisTypeId => $tmpIdList[$thisTypeId]);
1372 unset($tmpIdList[$thisTypeId]);
1373
1374 // Add the element
1375 $elements[] = array(
1376 'select',
1377 "location_blocks[$blockName][$count][typeTypeId]",
1378 NULL,
1379 $defaultTypeId + $tmpIdList,
1380 $js,
1381 );
1382
1383 // Add the information to the migrationInfo
1384 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1385
1386 }
1387
1388 // Set the label for this row
1389 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
1390 if (!empty($thisLocId)) {
1391 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1392 }
1393 if (!empty($thisTypeId)) {
1394 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1395 }
1396 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1397
1398 } // End loop through 'other' locations of this type
1399
1400 } // End if 'other' location for this type exists
1401
1402 } // End loop through each location block entity
1403
1404 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1405 $config = CRM_Core_Config::singleton();
1406 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1407 $mainUser = NULL;
1408 if ($mainUfId) {
1409 // d6 compatible
1410 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1411 $mainUser = user_load($mainUfId);
1412 }
1413 elseif ($config->userFramework == 'Joomla') {
1414 $mainUser = JFactory::getUser($mainUfId);
1415 }
1416 }
1417 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1418 $otherUser = NULL;
1419 if ($otherUfId) {
1420 // d6 compatible
1421 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1422 $otherUser = user_load($otherUfId);
1423 }
1424 elseif ($config->userFramework == 'Joomla') {
1425 $otherUser = JFactory::getUser($otherUfId);
1426 }
1427 }
1428
1429 $relTables = CRM_Dedupe_Merger::relTables();
1430 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1431 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1432 foreach ($relTables as $name => $null) {
1433 if (!in_array($name, $activeRelTables) &&
1434 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1435 ) {
1436 unset($relTables[$name]);
1437 continue;
1438 }
1439
1440 $relTableElements[] = array('checkbox', "move_$name");
1441 $migrationInfo["move_$name"] = 1;
1442
1443 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1444 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1445 if ($name == 'rel_table_users') {
1446 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1447 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1448 $find = array('$ufid', '$ufname');
1449 if ($mainUser) {
1450 $replace = array($mainUfId, $mainUser->name);
1451 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1452 }
1453 if ($otherUser) {
1454 $replace = array($otherUfId, $otherUser->name);
1455 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1456 }
1457 }
1458 if ($name == 'rel_table_memberships') {
1459 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1460 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1461 }
1462 }
1463 foreach ($relTables as $name => $null) {
1464 $relTables["move_$name"] = $relTables[$name];
1465 unset($relTables[$name]);
1466 }
1467
1468 // handle custom fields
1469 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1,
1470 CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
1471 );
1472 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1,
1473 CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
1474 );
1475 CRM_Core_DAO::freeResult();
1476
1477 foreach ($otherTree as $gid => $group) {
1478 $foundField = FALSE;
1479 if (!isset($group['fields'])) {
1480 continue;
1481 }
1482
1483 foreach ($group['fields'] as $fid => $field) {
1484 if (in_array($fid, $compareFields['custom'])) {
1485 if (!$foundField) {
1486 $rows["custom_group_$gid"]['title'] = $group['title'];
1487 $foundField = TRUE;
1488 }
1489 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1490 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1491 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
1492 }
1493 }
1494 $value = "null";
1495 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1496 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1497 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
1498 if ($values['data'] === 0 || $values['data'] === '0') {
1499 $values['data'] = $qfZeroBug;
1500 }
1501 $value = ($values['data']) ? $values['data'] : $value;
1502 }
1503 }
1504 $rows["move_custom_$fid"]['title'] = $field['label'];
1505
1506 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1507 $migrationInfo["move_custom_$fid"] = $value;
1508 }
1509 }
1510 }
1511
1512 $result = array(
1513 'rows' => $rows,
1514 'elements' => $elements,
1515 'rel_table_elements' => $relTableElements,
1516 'rel_tables' => $relTables,
1517 'main_details' => $main,
1518 'other_details' => $other,
1519 'migration_info' => $migrationInfo,
1520 );
1521
1522 $result['main_details']['location_blocks'] = $locations['main'];
1523 $result['other_details']['location_blocks'] = $locations['other'];
1524
1525 return $result;
1526 }
1527
1528 /**
1529 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1530 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1531 * A superset of moveContactBelongings() function.
1532 *
1533 * @param int $mainId
1534 * Main contact with whom merge has to happen.
1535 * @param int $otherId
1536 * Duplicate contact which would be deleted after merge operation.
1537 *
1538 * @param $migrationInfo
1539 *
1540 * @param bool $checkPermissions
1541 * Respect logged in user permissions.
1542 *
1543 * @return bool
1544 */
1545 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1546 if (empty($migrationInfo)) {
1547 return FALSE;
1548 }
1549
1550 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1551 $relTables = CRM_Dedupe_Merger::relTables();
1552 $moveTables = $locBlocks = $tableOperations = array();
1553 foreach ($migrationInfo as $key => $value) {
1554 if ($value == $qfZeroBug) {
1555 $value = '0';
1556 }
1557 if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) ||
1558 substr($key, 0, 12) == 'move_custom_') &&
1559 $value != NULL
1560 ) {
1561 $submitted[substr($key, 5)] = $value;
1562 }
1563
1564 // Set up initial information for handling migration of location blocks
1565 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1566 $locField = explode('_', $key);
1567 $fieldName = $locField[2];
1568 $fieldCount = $locField[3];
1569
1570 // Set up the operation type (add/overwrite)
1571 // Ignore operation for websites
1572 // @todo Tidy this up
1573 $operation = 0;
1574 if ($fieldName != 'website') {
1575 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1576 }
1577 // default operation is overwrite.
1578 if (!$operation) {
1579 $operation = 2;
1580 }
1581 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1582
1583 }
1584
1585 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1586 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1587 if (array_key_exists('operation', $migrationInfo)) {
1588 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1589 if (array_key_exists($key, $migrationInfo['operation'])) {
1590 $tableOperations[$table] = $migrationInfo['operation'][$key];
1591 }
1592 }
1593 }
1594 }
1595 }
1596
1597 // **** Do location related migration.
1598 // @todo Handle OpenID (not currently in API).
1599 if (!empty($locBlocks)) {
1600
1601 $locationBlocks = self::getLocationBlockInfo();
1602
1603 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
1604 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
1605
1606 foreach ($locBlocks as $name => $block) {
1607 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1608 continue;
1609 }
1610 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
1611 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1612 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1613
1614 foreach ($block as $blkCount => $values) {
1615
1616 // For the block which belongs to other-contact, link the location block to main-contact
1617 $otherBlockDAO = new $daoName();
1618 $otherBlockDAO->contact_id = $mainId;
1619
1620 // Get the ID of this block on the 'other' contact, otherwise skip
1621 $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
1622 if (!$otherBlockId) {
1623 continue;
1624 }
1625 $otherBlockDAO->id = $otherBlockId;
1626
1627 // Add/update location and type information from the form, if applicable
1628 if ($locationBlocks[$name]['hasLocation']) {
1629 $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1630 $otherBlockDAO->location_type_id = $locTypeId;
1631 }
1632 if ($locationBlocks[$name]['hasType']) {
1633 $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1634 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
1635 }
1636
1637 // Get main block ID
1638 $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1639
1640 // if main contact already has primary & billing, set the flags to 0.
1641 if ($primaryDAOId) {
1642 $otherBlockDAO->is_primary = 0;
1643 }
1644 if ($billingDAOId) {
1645 $otherBlockDAO->is_billing = 0;
1646 }
1647
1648 $operation = CRM_Utils_Array::value('operation', $values, 2);
1649 // overwrite - need to delete block which belongs to main-contact.
1650 if (!empty($mainBlockId) && ($operation == 2)) {
1651 $deleteDAO = new $daoName();
1652 $deleteDAO->id = $mainBlockId;
1653 $deleteDAO->find(TRUE);
1654
1655 // if we about to delete a primary / billing block, set the flags for new block
1656 // that we going to assign to main-contact
1657 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1658 $otherBlockDAO->is_primary = 1;
1659 }
1660 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1661 $otherBlockDAO->is_billing = 1;
1662 }
1663
1664 $deleteDAO->delete();
1665 $deleteDAO->free();
1666 }
1667
1668 $otherBlockDAO->update();
1669 $otherBlockDAO->free();
1670 }
1671 }
1672 }
1673
1674 // **** Do tables related migrations
1675 if (!empty($moveTables)) {
1676 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1677 unset($moveTables, $tableOperations);
1678 }
1679
1680 // **** Do contact related migrations
1681 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
1682
1683 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1684 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1685 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1686 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1687 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1688 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1689 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1690 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1691 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1692
1693 // fix custom fields so they're edible by createProfileContact()
1694 static $treeCache = array();
1695 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1696 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'],
1697 CRM_Core_DAO::$_nullObject, NULL, -1
1698 );
1699 }
1700 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1701
1702 $cFields = array();
1703 foreach ($cgTree as $key => $group) {
1704 if (!isset($group['fields'])) {
1705 continue;
1706 }
1707 foreach ($group['fields'] as $fid => $field) {
1708 $cFields[$fid]['attributes'] = $field;
1709 }
1710 }
1711
1712 if (!isset($submitted)) {
1713 $submitted = array();
1714 }
1715 foreach ($submitted as $key => $value) {
1716 if (substr($key, 0, 7) == 'custom_') {
1717 $fid = (int) substr($key, 7);
1718 if (empty($cFields[$fid])) {
1719 continue;
1720 }
1721 $htmlType = $cFields[$fid]['attributes']['html_type'];
1722 switch ($htmlType) {
1723 case 'File':
1724 $customFiles[] = $fid;
1725 unset($submitted["custom_$fid"]);
1726 break;
1727
1728 case 'Select Country':
1729 case 'Select State/Province':
1730 $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
1731 break;
1732
1733 case 'Select Date':
1734 if ($cFields[$fid]['attributes']['is_view']) {
1735 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
1736 }
1737 break;
1738
1739 case 'CheckBox':
1740 case 'AdvMulti-Select':
1741 case 'Multi-Select':
1742 case 'Multi-Select Country':
1743 case 'Multi-Select State/Province':
1744 // Merge values from both contacts for multivalue fields, CRM-4385
1745 // get the existing custom values from db.
1746 $customParams = array('entityID' => $mainId, $key => TRUE);
1747 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
1748 if (!empty($customfieldValues[$key])) {
1749 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1750 if (is_array($existingValue) && !empty($existingValue)) {
1751 $mergeValue = $submmtedCustomValue = array();
1752 if ($value) {
1753 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1754 }
1755
1756 //hack to remove null and duplicate values from array.
1757 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1758 if ($v != '' && !in_array($v, $mergeValue)) {
1759 $mergeValue[] = $v;
1760 }
1761 }
1762
1763 //keep state and country as array format.
1764 //for checkbox and m-select format w/ VALUE_SEPARATOR
1765 if (in_array($htmlType, array(
1766 'CheckBox',
1767 'Multi-Select',
1768 'AdvMulti-Select',
1769 ))) {
1770 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1771 $mergeValue
1772 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1773 }
1774 else {
1775 $submitted[$key] = $mergeValue;
1776 }
1777 }
1778 }
1779 elseif (in_array($htmlType, array(
1780 'Multi-Select Country',
1781 'Multi-Select State/Province',
1782 ))) {
1783 //we require submitted values should be in array format
1784 if ($value) {
1785 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1786 //hack to remove null values from array.
1787 $mergeValue = array();
1788 foreach ($mergeValueArray as $k => $v) {
1789 if ($v != '') {
1790 $mergeValue[] = $v;
1791 }
1792 }
1793 $submitted[$key] = $mergeValue;
1794 }
1795 }
1796 break;
1797
1798 default:
1799 break;
1800 }
1801 }
1802 }
1803
1804 // **** Do file custom fields related migrations
1805 // FIXME: move this someplace else (one of the BAOs) after discussing
1806 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1807 // like, delete a file...
1808
1809 if (!isset($customFiles)) {
1810 $customFiles = array();
1811 }
1812 foreach ($customFiles as $customId) {
1813 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1814
1815 // get the contact_id -> file_id mapping
1816 $fileIds = array();
1817 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1818 $dao = CRM_Core_DAO::executeQuery($sql);
1819 while ($dao->fetch()) {
1820 $fileIds[$dao->entity_id] = $dao->file_id;
1821 }
1822 $dao->free();
1823
1824 // delete the main contact's file
1825 if (!empty($fileIds[$mainId])) {
1826 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1827 }
1828
1829 // move the other contact's file to main contact
1830 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1831 if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
1832 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1833 }
1834 else {
1835 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1836 }
1837 CRM_Core_DAO::executeQuery($sql);
1838
1839 if (CRM_Core_DAO::singleValueQuery("
1840 SELECT id
1841 FROM civicrm_entity_file
1842 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1843 ) {
1844 $sql = "
1845 UPDATE civicrm_entity_file
1846 SET entity_id = {$mainId}
1847 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1848 }
1849 else {
1850 $sql = "
1851 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1852 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1853 }
1854 CRM_Core_DAO::executeQuery($sql);
1855 }
1856
1857 // move view only custom fields CRM-5362
1858 $viewOnlyCustomFields = array();
1859 foreach ($submitted as $key => $value) {
1860 $fid = (int) substr($key, 7);
1861 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1862 $viewOnlyCustomFields[$key] = $value;
1863 }
1864 }
1865
1866 // special case to set values for view only, CRM-5362
1867 if (!empty($viewOnlyCustomFields)) {
1868 $viewOnlyCustomFields['entityID'] = $mainId;
1869 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1870 }
1871
1872 if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') &&
1873 CRM_Core_Permission::check('delete contacts'))
1874 ) {
1875 // if ext id is submitted then set it null for contact to be deleted
1876 if (!empty($submitted['external_identifier'])) {
1877 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1878 CRM_Core_DAO::executeQuery($query);
1879 }
1880 civicrm_api3('contact', 'delete', array('id' => $otherId));
1881 }
1882
1883 // CRM-15681 merge sub_types
1884 if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
1885 if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
1886 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1887 }
1888 else {
1889 $submitted['contact_sub_type'] = $other_sub_types;
1890 }
1891 }
1892
1893 // **** Update contact related info for the main contact
1894 if (!empty($submitted)) {
1895 $submitted['contact_id'] = $mainId;
1896
1897 //update current employer field
1898 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1899 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1900 $submitted['current_employer'] = $submitted['current_employer_id'];
1901 }
1902 else {
1903 $submitted['current_employer'] = '';
1904 }
1905 unset($submitted['current_employer_id']);
1906 }
1907
1908 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1909 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1910 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1911 }
1912 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1913 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1914 }
1915
1916 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
1917 }
1918
1919 CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
1920 self::createMergeActivities($mainId, $otherId);
1921
1922 return TRUE;
1923 }
1924
1925 /**
1926 * Get fields in the contact table suitable for merging.
1927 *
1928 * @return array
1929 * Array of field names to be potentially merged.
1930 */
1931 public static function getContactFields() {
1932 $contactFields = CRM_Contact_DAO_Contact::fields();
1933 $invalidFields = array(
1934 'api_key',
1935 'created_date',
1936 'display_name',
1937 'hash',
1938 'id',
1939 'modified_date',
1940 'primary_contact_id',
1941 'sort_name',
1942 'user_unique_id',
1943 );
1944 foreach ($contactFields as $field => $value) {
1945 if (in_array($field, $invalidFields)) {
1946 unset($contactFields[$field]);
1947 }
1948 }
1949 return array_keys($contactFields);
1950 }
1951
1952 /**
1953 * Added for CRM-12695
1954 * Based on the contactID provided
1955 * add/update membership(s) to related contacts
1956 *
1957 * @param int $contactID
1958 */
1959 public static function addMembershipToRealtedContacts($contactID) {
1960 $dao = new CRM_Member_DAO_Membership();
1961 $dao->contact_id = $contactID;
1962 $dao->is_test = 0;
1963 $dao->find();
1964
1965 //checks membership of contact itself
1966 while ($dao->fetch()) {
1967 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1968 if ($relationshipTypeId) {
1969 $membershipParams = array(
1970 'id' => $dao->id,
1971 'contact_id' => $dao->contact_id,
1972 'membership_type_id' => $dao->membership_type_id,
1973 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1974 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1975 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1976 'source' => $dao->source,
1977 'status_id' => $dao->status_id,
1978 );
1979 // create/update membership(s) for related contact(s)
1980 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1981 } // end of if relationshipTypeId
1982 }
1983 }
1984
1985 /**
1986 * Add custom tables that extend contacts to the list of contact references.
1987 *
1988 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
1989 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
1990 * - the down side is it is not cached.
1991 *
1992 * Further changes should be include tests in the CRM_Core_MergerTest class
1993 * to ensure that disabled, subtype, multiple etc groups are still captured.
1994 *
1995 * @param array $cidRefs
1996 */
1997 public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
1998 $customValueTables = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
1999 $customValueTables->find();
2000 while ($customValueTables->fetch()) {
2001 $cidRefs[$customValueTables->table_name] = array('entity_id');
2002 }
2003 }
2004
2005 /**
2006 * Create activities tracking the merge on affected contacts.
2007 *
2008 * @param int $mainId
2009 * @param int $otherId
2010 *
2011 * @throws \CiviCRM_API3_Exception
2012 */
2013 public static function createMergeActivities($mainId, $otherId) {
2014 $params = array(
2015 1 => $otherId,
2016 2 => $mainId,
2017 );
2018 $activity = civicrm_api3('activity', 'create', array(
2019 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
2020 $mainId,
2021 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
2022 'target_contact_id' => $mainId,
2023 'activity_type_id' => 'Contact Merged',
2024 'status_id' => 'Completed',
2025 ));
2026 if (civicrm_api3('Setting', 'getvalue', array('name' => 'contact_undelete', 'group' => 'CiviCRM Preferences'))) {
2027 civicrm_api3('activity', 'create', array(
2028 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
2029 $otherId,
2030 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
2031 'target_contact_id' => $otherId,
2032 'activity_type_id' => 'Contact Deleted by Merge',
2033 'parent_id' => $activity['id'],
2034 'status_id' => 'Completed',
2035 ));
2036 }
2037 }
2038
2039 /**
2040 * Get Duplicate Pairs based on a rule for a group.
2041 *
2042 * @param int $rule_group_id
2043 * @param int $group_id
2044 * @param bool $reloadCacheIfEmpty
2045 * @param int $batchLimit
2046 * @param bool $isSelected
2047 * @param array|string $orderByClause
2048 * @param bool $includeConflicts
2049 * @param array $criteria
2050 * Additional criteria to narrow down the merge group.
2051 *
2052 * @param bool $checkPermissions
2053 * Respect logged in user permissions.
2054 *
2055 * @return array
2056 * Array of matches meeting the criteria.
2057 */
2058 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $orderByClause = '', $includeConflicts = TRUE, $criteria = array(), $checkPermissions = TRUE) {
2059 $where = self::getWhereString($batchLimit, $isSelected);
2060 $cacheKeyString = self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions);
2061 $join = self::getJoinOnDedupeTable();
2062 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
2063 if (empty($dupePairs) && $reloadCacheIfEmpty) {
2064 // If we haven't found any dupes, probably cache is empty.
2065 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
2066 // until we have done some processing.
2067 CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions);
2068 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
2069 return $dupePairs;
2070 }
2071 return $dupePairs;
2072 }
2073
2074 /**
2075 * Get the cache key string for the merge action.
2076 *
2077 * @param int $rule_group_id
2078 * @param int $group_id
2079 * @param array $criteria
2080 * Additional criteria to narrow down the merge group.
2081 * Currently we are only supporting the key 'contact' within it.
2082 *
2083 * @param bool $checkPermissions
2084 * Respect the users permissions.
2085 *
2086 * @return string
2087 */
2088 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = array(), $checkPermissions = TRUE) {
2089 $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
2090 $cacheKeyString = "merge {$contactType}";
2091 $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
2092 $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
2093 $cacheKeyString .= !empty($criteria) ? serialize($criteria) : '_0';
2094 if ($checkPermissions) {
2095 $contactID = CRM_Core_Session::getLoggedInContactID();
2096 if (!$contactID) {
2097 // Distinguish between no permission check & no logged in user.
2098 $contactID = 'null';
2099 }
2100 $cacheKeyString .= '_' . $contactID;
2101 }
2102 else {
2103 $cacheKeyString .= '_0';
2104 }
2105 return $cacheKeyString;
2106 }
2107
2108 }