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