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