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