Merge pull request #3873 from jitendrapurohit/CRM-15096
[civicrm-core.git] / CRM / Dedupe / Merger.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35 class CRM_Dedupe_Merger {
36
37 // FIXME: consider creating a common structure with cidRefs() and eidRefs()
38 // FIXME: the sub-pages references by the URLs should
39 // be loaded dynamically on the merge form instead
40 static function relTables() {
41 static $relTables;
42
43 $config = CRM_Core_Config::singleton();
44 if ($config->userSystem->is_drupal) {
45 $userRecordUrl = CRM_Utils_System::url('user/%ufid');
46 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
47 }
48 elseif ($config->userFramework == 'Joomla') {
49 $userRecordUrl = $config->userFrameworkVersion > 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';
50 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
51 }
52
53 if (!$relTables) {
54 $relTables = array(
55 'rel_table_contributions' => array(
56 'title' => ts('Contributions'),
57 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
58 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
59 ),
60 'rel_table_contribution_page' => array(
61 'title' => ts('Contribution Pages'),
62 'tables' => array('civicrm_contribution_page'),
63 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
64 ),
65 'rel_table_memberships' => array(
66 'title' => ts('Memberships'),
67 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
68 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
69 ),
70 'rel_table_participants' => array(
71 'title' => ts('Participants'),
72 'tables' => array('civicrm_participant'),
73 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
74 ),
75 'rel_table_events' => array(
76 'title' => ts('Events'),
77 'tables' => array('civicrm_event'),
78 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
79 ),
80 'rel_table_activities' => array(
81 'title' => ts('Activities'),
82 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
83 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
84 ),
85 'rel_table_relationships' => array(
86 'title' => ts('Relationships'),
87 'tables' => array('civicrm_relationship'),
88 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
89 ),
90 'rel_table_custom_groups' => array(
91 'title' => ts('Custom Groups'),
92 'tables' => array('civicrm_custom_group'),
93 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
94 ),
95 'rel_table_uf_groups' => array(
96 'title' => ts('Profiles'),
97 'tables' => array('civicrm_uf_group'),
98 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
99 ),
100 'rel_table_groups' => array(
101 'title' => ts('Groups'),
102 'tables' => array('civicrm_group_contact'),
103 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
104 ),
105 'rel_table_notes' => array(
106 'title' => ts('Notes'),
107 'tables' => array('civicrm_note'),
108 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
109 ),
110 'rel_table_tags' => array(
111 'title' => ts('Tags'),
112 'tables' => array('civicrm_entity_tag'),
113 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
114 ),
115 'rel_table_mailings' => array(
116 'title' => ts('Mailings'),
117 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
118 'url' => CRM_Utils_System::url('civicrm/mailing', 'reset=1&force=1&cid=$cid'),
119 ),
120 'rel_table_cases' => array(
121 'title' => ts('Cases'),
122 'tables' => array('civicrm_case_contact'),
123 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
124 ),
125 'rel_table_grants' => array(
126 'title' => ts('Grants'),
127 'tables' => array('civicrm_grant'),
128 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
129 ),
130 'rel_table_pcp' => array(
131 'title' => ts('PCPs'),
132 'tables' => array('civicrm_pcp'),
133 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
134 ),
135 'rel_table_pledges' => array(
136 'title' => ts('Pledges'),
137 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
138 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
139 ),
140 'rel_table_users' => array(
141 'title' => $title,
142 'tables' => array('civicrm_uf_match'),
143 'url' => $userRecordUrl,
144 ),
145 );
146
147 $relTables += self::getMultiValueCustomSets('relTables');
148
149 // Allow hook_civicrm_merge() to adjust $relTables
150 CRM_Utils_Hook::merge('relTables', $relTables);
151 }
152 return $relTables;
153 }
154
155 /**
156 * Returns the related tables groups for which a contact has any info entered
157 */
158 static function getActiveRelTables($cid) {
159 $cid = (int) $cid;
160 $groups = array();
161
162 $relTables = self::relTables();
163 $cidRefs = self::cidRefs();
164 $eidRefs = self::eidRefs();
165 foreach ($relTables as $group => $params) {
166 $sqls = array();
167 foreach ($params['tables'] as $table) {
168 if (isset($cidRefs[$table])) {
169 foreach ($cidRefs[$table] as $field) {
170 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
171 }
172 }
173 if (isset($eidRefs[$table])) {
174 foreach ($eidRefs[$table] as $entityTable => $entityId) {
175 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
176 }
177 }
178 foreach ($sqls as $sql) {
179 if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
180 $groups[] = $group;
181 }
182 }
183 }
184 }
185 return array_unique($groups);
186 }
187
188 /**
189 * Return tables and their fields referencing civicrm_contact.contact_id explicitely
190 */
191 static function cidRefs() {
192 static $cidRefs;
193 if (!$cidRefs) {
194 // FIXME: this should be generated dynamically from the schema's
195 // foreign keys referencing civicrm_contact(id)
196 $cidRefs = array(
197 'civicrm_acl_cache' => array('contact_id'),
198 'civicrm_activity_contact' => array('contact_id'),
199 'civicrm_case_contact' => array('contact_id'),
200 'civicrm_contact' => array('primary_contact_id'),
201 'civicrm_contribution' => array('contact_id', 'honor_contact_id'),
202 'civicrm_contribution_page' => array('created_id'),
203 'civicrm_contribution_recur' => array('contact_id'),
204 'civicrm_contribution_soft' => array('contact_id'),
205 'civicrm_financial_item' => array('contact_id'),
206 'civicrm_custom_group' => array('created_id'),
207 'civicrm_entity_tag' => array('entity_id'),
208 'civicrm_event' => array('created_id'),
209 'civicrm_grant' => array('contact_id'),
210 'civicrm_group_contact' => array('contact_id'),
211 'civicrm_group_organization' => array('organization_id'),
212 'civicrm_log' => array('modified_id'),
213 'civicrm_mailing' => array('created_id', 'scheduled_id'),
214 'civicrm_mailing_event_queue' => array('contact_id'),
215 'civicrm_mailing_event_subscribe' => array('contact_id'),
216 'civicrm_membership' => array('contact_id'),
217 'civicrm_membership_log' => array('modified_id'),
218 'civicrm_membership_type' => array('member_of_contact_id'),
219 'civicrm_note' => array('contact_id'),
220 'civicrm_participant' => array('contact_id'),
221 'civicrm_pcp' => array('contact_id'),
222 'civicrm_relationship' => array('contact_id_a', 'contact_id_b'),
223 'civicrm_uf_match' => array('contact_id'),
224 'civicrm_uf_group' => array('created_id'),
225 'civicrm_pledge' => array('contact_id'),
226 );
227
228 $cidRefs += self::getMultiValueCustomSets('cidRefs');
229
230 // Add ContactReference custom fields CRM-9561
231 $sql = "SELECT cg.table_name, cf.column_name
232 FROM civicrm_custom_group cg, civicrm_custom_field cf
233 WHERE cg.id = cf.custom_group_id AND cf.data_type = 'ContactReference'";
234 $dao = CRM_Core_DAO::executeQuery($sql);
235 while ($dao->fetch()) {
236 $cidRefs[$dao->table_name][] = $dao->column_name;
237 }
238 $dao->free();
239
240 // Allow hook_civicrm_merge() to adjust $cidRefs
241 CRM_Utils_Hook::merge('cidRefs', $cidRefs);
242 }
243 return $cidRefs;
244 }
245
246 /**
247 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
248 */
249 static function eidRefs() {
250 static $eidRefs;
251 if (!$eidRefs) {
252 // FIXME: this should be generated dynamically from the schema
253 // tables that reference contacts with entity_{id,table}
254 $eidRefs = array(
255 'civicrm_acl' => array('entity_table' => 'entity_id'),
256 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
257 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
258 'civicrm_log' => array('entity_table' => 'entity_id'),
259 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
260 'civicrm_note' => array('entity_table' => 'entity_id'),
261 );
262
263 // Allow hook_civicrm_merge() to adjust $eidRefs
264 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
265 }
266 return $eidRefs;
267 }
268
269 /**
270 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
271 * @param string $request 'relTables' or 'cidRefs'
272 * @see CRM-13836
273 */
274 static function getMultiValueCustomSets($request) {
275 static $data = NULL;
276 if ($data === NULL) {
277 $data = array(
278 'relTables' => array(),
279 'cidRefs' => array(),
280 );
281 $result = civicrm_api3('custom_group', 'get', array(
282 'is_multiple' => 1,
283 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
284 'return' => array('id', 'title', 'table_name', 'style'),
285 ));
286 foreach($result['values'] as $custom) {
287 $data['cidRefs'][$custom['table_name']] = array('entity_id');
288 $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
289 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
290 'title' => $custom['title'],
291 'tables' => array($custom['table_name']),
292 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
293 );
294 }
295 }
296 return $data[$request];
297 }
298
299 /**
300 * Tables which require custom processing should declare functions to call here.
301 * Doing so will override normal processing.
302 */
303 static function cpTables() {
304 static $tables;
305 if (!$tables) {
306 $tables = array(
307 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
308 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
309 // Empty array == do nothing - this table is handled by mergeGroupContact
310 'civicrm_subscription_history' => array(),
311 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
312 );
313 }
314 return $tables;
315 }
316
317 /**
318 * return payment related table.
319 */
320 static function paymentTables() {
321 static $tables;
322 if (!$tables) {
323 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
324 }
325
326 return $tables;
327 }
328
329 /**
330 * return payment update Query.
331 */
332 static function paymentSql($tableName, $mainContactId, $otherContactId) {
333 $sqls = array();
334 if (!$tableName || !$mainContactId || !$otherContactId) {
335 return $sqls;
336 }
337
338 $paymentTables = self::paymentTables();
339 if (!in_array($tableName, $paymentTables)) {
340 return $sqls;
341 }
342
343 switch ($tableName) {
344 case 'civicrm_pledge':
345 $sqls[] = "
346 UPDATE IGNORE civicrm_contribution contribution
347 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
348 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
349 SET contribution.contact_id = $mainContactId
350 WHERE pledge.contact_id = $otherContactId";
351 break;
352
353 case 'civicrm_membership':
354 $sqls[] = "
355 UPDATE IGNORE civicrm_contribution contribution
356 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
357 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
358 SET contribution.contact_id = $mainContactId
359 WHERE membership.contact_id = $otherContactId";
360 break;
361
362 case 'civicrm_participant':
363 $sqls[] = "
364 UPDATE IGNORE civicrm_contribution contribution
365 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
366 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
367 SET contribution.contact_id = $mainContactId
368 WHERE participant.contact_id = $otherContactId";
369 break;
370 }
371
372 return $sqls;
373 }
374
375 static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
376 $sqls = array();
377 if (!$tableName || !$mainId || !$otherId) {
378 return $sqls;
379 }
380
381
382 switch ($tableName) {
383 case 'civicrm_membership':
384 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add'])
385 break;
386 if ($mode == 'add') {
387 $sqls[] = "
388 DELETE membership1.* FROM civicrm_membership membership1
389 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
390 AND membership1.contact_id = {$mainId}
391 AND membership2.contact_id = {$otherId} ";
392 }
393 if ($mode == 'payment') {
394 $sqls[] = "
395 DELETE contribution.* FROM civicrm_contribution contribution
396 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
397 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
398 AND membership1.contact_id = {$mainId}
399 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
400 AND membership2.contact_id = {$otherId}";
401 }
402 break;
403
404 case 'civicrm_uf_match':
405 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
406 // failing to meet intended result. Therefore we introduce this additonal query:
407 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
408 break;
409 }
410
411 return $sqls;
412 }
413
414 /**
415 * Based on the provided two contact_ids and a set of tables, move the
416 * belongings of the other contact to the main one.
417 *
418 * @static
419 */
420 static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
421 $cidRefs = self::cidRefs();
422 $eidRefs = self::eidRefs();
423 $cpTables = self::cpTables();
424 $paymentTables = self::paymentTables();
425 $membershipMerge = FALSE; // CRM-12695
426
427 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
428 if ($tables !== FALSE) {
429 // if there are specific tables, sanitize the list
430 $affected = array_unique(array_intersect($affected, $tables));
431 }
432 else {
433 // if there aren't any specific tables, don't affect the ones handled by relTables()
434 $relTables = self::relTables();
435 $handled = array();
436 foreach ($relTables as $params) {
437 $handled = array_merge($handled, $params['tables']);
438 }
439 $affected = array_diff($affected, $handled);
440 /**
441 * CRM-12695
442 * Set $membershipMerge flag only once
443 * while doing contact related migration
444 * to call addMembershipToRealtedContacts()
445 * function only once.
446 * Since the current function (moveContactBelongings) is called twice
447 * with & without parameters $tables & $tableOperations
448 */
449 // retrieve main contact's related table(s)
450 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
451 // check if membership table exists in main contact's related table(s)
452 if (in_array('rel_table_memberships', $activeMainRelTables)) {
453 $membershipMerge = TRUE; // set membership flag - CRM-12695
454 }
455 }
456
457 $mainId = (int) $mainId;
458 $otherId = (int) $otherId;
459
460 $sqls = array();
461 foreach ($affected as $table) {
462 // Call custom processing function for objects that require it
463 if (isset($cpTables[$table])) {
464 foreach ($cpTables[$table] as $className => $fnName) {
465 $className::$fnName($mainId, $otherId, $sqls);
466 }
467 // Skip normal processing
468 continue;
469 }
470
471 // use UPDATE IGNORE + DELETE query pair to skip on situations when
472 // there's a UNIQUE restriction on ($field, some_other_field) pair
473 if (isset($cidRefs[$table])) {
474 foreach ($cidRefs[$table] as $field) {
475 // carry related contributions CRM-5359
476 if (in_array($table, $paymentTables)) {
477 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
478 $sqls = array_merge($sqls, $payOprSqls);
479
480 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
481 $sqls = array_merge($sqls, $paymentSqls);
482 }
483
484 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
485 $sqls = array_merge($sqls, $preOperationSqls);
486
487 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
488 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
489 }
490 }
491 if (isset($eidRefs[$table])) {
492 foreach ($eidRefs[$table] as $entityTable => $entityId) {
493 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
494 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
495 }
496 }
497 }
498
499 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
500 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
501
502 // call the SQL queries in one transaction
503 $transaction = new CRM_Core_Transaction();
504 foreach ($sqls as $sql) {
505 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE);
506 }
507 // CRM-12695
508 if ($membershipMerge) {
509 // call to function adding membership to related contacts
510 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
511 }
512 $transaction->commit();
513 }
514
515 /**
516 * Find differences between contacts.
517 *
518 * @param array $main contact details
519 * @param array $other contact details
520 *
521 * @static
522 */
523 static function findDifferences($main, $other) {
524 $result = array(
525 'contact' => array(),
526 'custom' => array(),
527 );
528 foreach (self::getContactFields() as $validField) {
529 if (CRM_Utils_Array::value($validField, $main) != CRM_Utils_Array::value($validField, $other)) {
530 $result['contact'][] = $validField;
531 }
532 }
533
534 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
535 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
536 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
537 foreach ($keys as $key) {
538 // Exclude multi-value fields CRM-13836
539 if (strpos($key, '_')) {
540 continue;
541 }
542 $key1 = CRM_Utils_Array::value($key, $mainEvs);
543 $key2 = CRM_Utils_Array::value($key, $otherEvs);
544 if ($key1 != $key2) {
545 $result['custom'][] = $key;
546 }
547 }
548 return $result;
549 }
550
551 /**
552 * Function to batch merge a set of contacts based on rule-group and group.
553 *
554 * @param int $rgid rule group id
555 * @param int $gid group id
556 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
557 * Generally used with batch-merge.
558 * @param string $mode helps decide how to behave when there are conflicts.
559 * A 'safe' value skips the merge if there are any un-resolved conflicts.
560 * Does a force merge otherwise.
561 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
562 *
563 *
564 * @static
565 * @access public
566 */
567 static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $redirectForPerformance = FALSE) {
568 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
569 $cacheKeyString = "merge {$contactType}";
570 $cacheKeyString .= $rgid ? "_{$rgid}" : '_0';
571 $cacheKeyString .= $gid ? "_{$gid}" : '_0';
572 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
573 pn.entity_id2 = de.contact_id2 )";
574
575 $limit = $redirectForPerformance ? 75 : 1;
576 $where = "de.id IS NULL LIMIT {$limit}";
577
578 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
579 if (empty($dupePairs) && !$redirectForPerformance) {
580 // If we haven't found any dupes, probably cache is empty.
581 // Try filling cache and give another try.
582 CRM_Core_BAO_PrevNextCache::refillCache($rgid, $gid, $cacheKeyString);
583 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
584 }
585
586 $cacheParams = array(
587 'cache_key_string' => $cacheKeyString,
588 'join' => $join,
589 'where' => $where,
590 );
591 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
592 }
593
594 /**
595 * Function to merge given set of contacts. Performs core operation.
596 *
597 * @param array $dupePairs set of pair of contacts for whom merge is to be done.
598 * @param array $cacheParams prev-next-cache params based on which next pair of contacts are computed.
599 * Generally used with batch-merge.
600 * @param string $mode helps decide how to behave when there are conflicts.
601 * A 'safe' value skips the merge if there are any un-resolved conflicts.
602 * Does a force merge otherwise (aggressive mode).
603 * @param boolean $autoFlip wether to let api decide which contact to retain and which to delete.
604 *
605 *
606 * @static
607 * @access public
608 */
609 static function merge($dupePairs = array(
610 ), $cacheParams = array(), $mode = 'safe',
611 $autoFlip = TRUE, $redirectForPerformance = FALSE
612 ) {
613 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
614 $resultStats = array('merged' => array(), 'skipped' => array());
615
616 // we don't want dupe caching to get reset after every-merge, and therefore set the
617 // doNotResetCache flag
618 $config = CRM_Core_Config::singleton();
619 $config->doNotResetCache = 1;
620
621 while (!empty($dupePairs)) {
622 foreach ($dupePairs as $dupes) {
623 $mainId = $dupes['dstID'];
624 $otherId = $dupes['srcID'];
625 // make sure that $mainId is the one with lower id number
626 if ($autoFlip && ($mainId > $otherId)) {
627 $mainId = $dupes['srcID'];
628 $otherId = $dupes['dstID'];
629 }
630 if (!$mainId || !$otherId) {
631 // return error
632 return FALSE;
633 }
634
635 // Generate var $migrationInfo. The variable structure is exactly same as
636 // $formValues submitted during a UI merge for a pair of contacts.
637 $rowsElementsAndInfo = &CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId);
638
639 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
640
641 // add additional details that we might need to resolve conflicts
642 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
643 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
644 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
645 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
646
647 // go ahead with merge if there is no conflict
648 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode)) {
649 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo);
650 $resultStats['merged'][] = array('main_d' => $mainId, 'other_id' => $otherId);
651 }
652 else {
653 $resultStats['skipped'][] = array('main_d' => $mainId, 'other_id' => $otherId);
654 }
655
656 // delete entry from PrevNextCache table so we don't consider the pair next time
657 // pair may have been flipped, so make sure we delete using both orders
658 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString);
659 CRM_Core_BAO_PrevNextCache::deletePair($otherId, $mainId, $cacheKeyString);
660
661 CRM_Core_DAO::freeResult();
662 unset($rowsElementsAndInfo, $migrationInfo);
663 }
664
665 if ($cacheKeyString && !$redirectForPerformance) {
666 // retrieve next pair of dupes
667 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
668 $cacheParams['join'],
669 $cacheParams['where']
670 );
671 }
672 else {
673 // do not proceed. Terminate the loop
674 unset($dupePairs);
675 }
676 }
677 return $resultStats;
678 }
679
680 /**
681 * A function which uses various rules / algorithms for choosing which contact to bias to
682 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
683 *
684 * @param int $mainId main contact with whom merge has to happen
685 * @param int $otherId duplicate contact which would be deleted after merge operation
686 * @param array $migrationInfo array of information about which elements to merge.
687 * @param string $mode helps decide how to behave when there are conflicts.
688 * A 'safe' value skips the merge if there are any un-resolved conflicts.
689 * Does a force merge otherwise (aggressive mode).
690 *
691 * @static
692 * @access public
693 */
694 static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe') {
695 $conflicts = array();
696 $migrationData = array(
697 'old_migration_info' => $migrationInfo,
698 'mode' => $mode,
699 );
700 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
701
702 foreach ($migrationInfo as $key => $val) {
703 if ($val === "null") {
704 // Rule: no overwriting with empty values in any mode
705 unset($migrationInfo[$key]);
706 continue;
707 }
708 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
709 substr($key, 0, 12) == 'move_custom_'
710 ) and $val != NULL) {
711 // Rule: if both main-contact has other-contact, let $mode decide if to merge a
712 // particular field or not
713 if (!empty($migrationInfo['rows'][$key]['main'])) {
714 // if main also has a value its a conflict
715 if ($mode == 'safe') {
716 // note it down & lets wait for response from the hook.
717 // For no response skip this merge
718 $conflicts[$key] = NULL;
719 }
720 elseif ($mode == 'aggressive') {
721 // let the main-field be overwritten
722 continue;
723 }
724 }
725 }
726 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
727 $locField = explode('_', $key);
728 $fieldName = $locField[2];
729 $fieldCount = $locField[3];
730
731 // Rule: resolve address conflict if any -
732 if ($fieldName == 'address') {
733 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
734 if (CRM_Utils_Array::value('main_loc_address', $migrationInfo) &&
735 array_key_exists("main_{$mainNewLocTypeId}", $migrationInfo['main_loc_address'])) {
736 // main loc already has some address for the loc-type. Its a overwrite situation.
737
738 // look for next available loc-type
739 $newTypeId = NULL;
740 foreach ($allLocationTypes as $typeId => $typeLabel) {
741 if (!array_key_exists("main_{$typeId}", $migrationInfo['main_loc_address'])) {
742 $newTypeId = $typeId;
743 }
744 }
745 if ($newTypeId) {
746 // try insert address at new available loc-type
747 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
748 }
749 elseif ($mode == 'safe') {
750 // note it down & lets wait for response from the hook.
751 // For no response skip this merge
752 $conflicts[$key] = NULL;
753 }
754 elseif ($mode == 'aggressive') {
755 // let the loc-type-id be same as that of other-contact & go ahead
756 // with merge assuming aggressive mode
757 continue;
758 }
759 }
760 }
761 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
762 // for loc blocks other than address like email, phone .. if values are same no point in merging
763 // and adding redundant value
764 unset($migrationInfo[$key]);
765 }
766 }
767 }
768
769 // A hook to implement other algorithms for choosing which contact to bias to when
770 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
771 // merge happens with new values filled in here. For a particular field / row not to be merged
772 // field should be unset from fields_in_conflict.
773 $migrationData['fields_in_conflict'] = $conflicts;
774 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
775 $conflicts = $migrationData['fields_in_conflict'];
776
777 if (!empty($conflicts)) {
778 foreach ($conflicts as $key => $val) {
779 if ($val === NULL and $mode == 'safe') {
780 // un-resolved conflicts still present. Lets skip this merge.
781 return TRUE;
782 }
783 else {
784 // copy over the resolved values
785 $migrationInfo[$key] = $val;
786 }
787 }
788 }
789 return FALSE;
790 }
791
792 /**
793 * A function to build an array of information required by merge function and the merge UI.
794 *
795 * @param int $mainId main contact with whom merge has to happen
796 * @param int $otherId duplicate contact which would be deleted after merge operation
797 *
798 * @static
799 * @access public
800 */
801 static function getRowsElementsAndInfo($mainId, $otherId) {
802 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
803
804 // Fetch contacts
805 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
806 $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields()));
807 $result = civicrm_api('contact', 'get', $params);
808
809 if (empty($result['values'][$cid]['contact_type'])) {
810 return FALSE;
811 }
812 $$moniker = $result['values'][$cid];
813 }
814
815 static $fields = array();
816 if (empty($fields)) {
817 $fields = CRM_Contact_DAO_Contact::fields();
818 CRM_Core_DAO::freeResult();
819 }
820
821 // FIXME: there must be a better way
822 foreach (array('main', 'other') as $moniker) {
823 $contact = &$$moniker;
824 $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
825 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
826 $specialValues[$moniker] = array(
827 'preferred_communication_method' => $value,
828 );
829
830 if (CRM_Utils_array::value('preferred_communication_method', $contact)){
831 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
832 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ?
833 implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) :
834 $specialValues[$moniker]['preferred_communication_method'];
835 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
836 }
837 $names = array(
838 'preferred_communication_method' =>
839 array(
840 'newName' => 'preferred_communication_method_display',
841 'groupName' => 'preferred_communication_method',
842 ),
843 );
844 CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
845 }
846
847 static $optionValueFields = array();
848 if (empty($optionValueFields)) {
849 $optionValueFields = CRM_Core_OptionValue::getFields();
850 }
851 foreach ($optionValueFields as $field => $params) {
852 $fields[$field]['title'] = $params['title'];
853 }
854
855 $diffs = self::findDifferences($main, $other);
856
857 $rows = $elements = $relTableElements = $migrationInfo = array();
858
859 foreach ($diffs['contact'] as $field) {
860 foreach (array('main', 'other') as $moniker) {
861 $contact = &$$moniker;
862 $value = CRM_Utils_Array::value($field, $contact);
863 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
864 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
865 }
866 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
867 if (CRM_Utils_Array::value('type', $fields[$field]) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
868 if ($value) {
869 $value = str_replace('-', '', $value);
870 $label = CRM_Utils_Date::customFormat($label);
871 }
872 else {
873 $value = "null";
874 }
875 }
876 elseif (CRM_Utils_Array::value('type', $fields[$field]) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
877 if ($label === '0') {
878 $label = ts('[ ]');
879 }
880 if ($label === '1') {
881 $label = ts('[x]');
882 }
883 } elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
884 $label = CRM_Utils_Array::value('prefix', $contact);
885 $value = CRM_Utils_Array::value('prefix_id', $contact);
886 $field = 'prefix_id';
887 } elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
888 $label = CRM_Utils_Array::value('suffix', $contact);
889 $value = CRM_Utils_Array::value('suffix_id', $contact);
890 $field = 'suffix_id';
891 }
892 $rows["move_$field"][$moniker] = $label;
893 if ($moniker == 'other') {
894 //CRM-14334
895 if ($value === NULL || $value == '') {
896 $value = 'null';
897 }
898 if ($value === 0 or $value === '0') {
899 $value = $qfZeroBug;
900 }
901 if (is_array($value) &&
902 !CRM_Utils_Array::value(1, $value)) {
903 $value[1] = NULL;
904 }
905 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
906 $migrationInfo["move_$field"] = $value;
907 }
908 }
909 $rows["move_$field"]['title'] = $fields[$field]['title'];
910 }
911
912 // handle location blocks.
913 $locationBlocks = array('email', 'phone', 'address');
914 $locations = array();
915
916 foreach ($locationBlocks as $block) {
917 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
918 $cnt = 1;
919 $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3));
920 $count = $values['count'];
921 if ($count) {
922 if ($count > $cnt) {
923 foreach ($values['values'] as $value) {
924 if ($block == 'address') {
925 CRM_Core_BAO_Address::fixAddress($value);
926 $display = CRM_Utils_Address::format($value);
927 $locations[$moniker][$block][$cnt] = $value;
928 $locations[$moniker][$block][$cnt]['display'] = $display;
929 }
930 else {
931 $locations[$moniker][$block][$cnt] = $value;
932 }
933
934 $cnt++;
935 }
936 }
937 else {
938 $id = $values['id'];
939 if ($block == 'address') {
940 CRM_Core_BAO_Address::fixAddress($values['values'][$id]);
941 $display = CRM_Utils_Address::format($values['values'][$id]);
942 $locations[$moniker][$block][$cnt] = $values['values'][$id];
943 $locations[$moniker][$block][$cnt]['display'] = $display;
944 }
945 else {
946 $locations[$moniker][$block][$cnt] = $values['values'][$id];
947 }
948 }
949 }
950 }
951 }
952
953 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
954
955 $mainLocBlock = $locBlockIds = array();
956 $locBlockIds['main'] = $locBlockIds['other'] = array();
957 foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) {
958 $name = strtolower($block);
959 foreach (array('main', 'other') as $moniker) {
960 $locIndex = CRM_Utils_Array::value($moniker, $locations);
961 $blockValue = CRM_Utils_Array::value($name, $locIndex, array());
962 if (empty($blockValue)) {
963 $locValue[$moniker][$name] = 0;
964 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array();
965 }
966 else {
967 $locValue[$moniker][$name] = TRUE;
968 foreach ($blockValue as $count => $blkValues) {
969 $fldName = $name;
970 $locTypeId = $blkValues['location_type_id'];
971 if ($name == 'im') {
972 $fldName = 'name';
973 }
974 if ($name == 'address') {
975 $fldName = 'display';
976 }
977 $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName,
978 $blkValues
979 );
980 $locTypes[$moniker][$name][$count] = $locTypeId;
981 if ($moniker == 'main' && in_array($name, $locationBlocks)) {
982 $mainLocBlock["main_$name$locTypeId"] = CRM_Utils_Array::value($fldName,
983 $blkValues
984 );
985 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
986 }
987 else {
988 $locBlockIds[$moniker][$name][$count] = $blkValues['id'];
989 }
990 }
991 }
992 }
993
994 if ($locValue['other'][$name] != 0) {
995 foreach ($locLabel['other'][$name] as $count => $value) {
996 $locTypeId = $locTypes['other'][$name][$count];
997 $rows["move_location_{$name}_$count"]['other'] = $value;
998 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array::value($count,
999 $locLabel['main'][$name]
1000 );
1001 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
1002 array(
1003 1 => $block,
1004 2 => $count,
1005 3 => $allLocationTypes[$locTypeId]
1006 )
1007 );
1008
1009 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
1010 $migrationInfo["move_location_{$name}_{$count}"] = 1;
1011
1012 // make sure default location type is always on top
1013 $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId);
1014 $locTypeValues = $allLocationTypes;
1015 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
1016 unset($locTypeValues[$mainLocTypeId]);
1017
1018 // keep 1-1 mapping for address - location type.
1019 $js = NULL;
1020 if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) {
1021 $js = array('onChange' => "mergeBlock('$name', this, $count );");
1022 }
1023 $elements[] = array(
1024 'select', "location[{$name}][$count][locTypeId]", NULL,
1025 $defaultLocType + $locTypeValues, $js,
1026 );
1027 // keep location-type-id same as that of other-contact
1028 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
1029
1030 if ($name != 'address') {
1031 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
1032 // always use add operation
1033 $migrationInfo['location'][$name][$count]['operation'] = 1;
1034 }
1035 }
1036 }
1037 }
1038
1039 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1040 $config = CRM_Core_Config::singleton();
1041 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1042 $mainUser = NULL;
1043 if ($mainUfId) {
1044 // d6 compatible
1045 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1046 $mainUser = user_load($mainUfId);
1047 }
1048 elseif ($config->userFramework == 'Joomla') {
1049 $mainUser = JFactory::getUser($mainUfId);
1050 }
1051 }
1052 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1053 $otherUser = NULL;
1054 if ($otherUfId) {
1055 // d6 compatible
1056 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1057 $otherUser = user_load($otherUfId);
1058 }
1059 elseif ($config->userFramework == 'Joomla') {
1060 $otherUser = JFactory::getUser($otherUfId);
1061 }
1062 }
1063
1064 $relTables = CRM_Dedupe_Merger::relTables();
1065 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1066 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1067 foreach ($relTables as $name => $null) {
1068 if (!in_array($name, $activeRelTables) &&
1069 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1070 ) {
1071 unset($relTables[$name]);
1072 continue;
1073 }
1074
1075 $relTableElements[] = array('checkbox', "move_$name");
1076 $migrationInfo["move_$name"] = 1;
1077
1078 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1079 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1080 if ($name == 'rel_table_users') {
1081 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1082 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1083 $find = array('$ufid', '$ufname');
1084 if ($mainUser) {
1085 $replace = array($mainUfId, $mainUser->name);
1086 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1087 }
1088 if ($otherUser) {
1089 $replace = array($otherUfId, $otherUser->name);
1090 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1091 }
1092 }
1093 if ($name == 'rel_table_memberships') {
1094 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1095 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1096 }
1097 }
1098 foreach ($relTables as $name => $null) {
1099 $relTables["move_$name"] = $relTables[$name];
1100 unset($relTables[$name]);
1101 }
1102
1103 // handle custom fields
1104 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1,
1105 CRM_Utils_Array::value('contact_sub_type', $main)
1106 );
1107 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1,
1108 CRM_Utils_Array::value('contact_sub_type', $other)
1109 );
1110 CRM_Core_DAO::freeResult();
1111
1112 foreach ($otherTree as $gid => $group) {
1113 $foundField = FALSE;
1114 if (!isset($group['fields'])) {
1115 continue;
1116 }
1117
1118 foreach ($group['fields'] as $fid => $field) {
1119 if (in_array($fid, $diffs['custom'])) {
1120 if (!$foundField) {
1121 $rows["custom_group_$gid"]['title'] = $group['title'];
1122 $foundField = TRUE;
1123 }
1124 if (CRM_Utils_Array::value('customValue', $mainTree[$gid]['fields'][$fid])) {
1125 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1126 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1127 $field, TRUE
1128 );
1129 }
1130 }
1131 $value = "null";
1132 if (CRM_Utils_Array::value('customValue', $otherTree[$gid]['fields'][$fid])) {
1133 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1134 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1135 $field, TRUE
1136 );
1137 if ($values['data'] === 0 || $values['data'] === '0') {
1138 $values['data'] = $qfZeroBug;
1139 }
1140 $value = ($values['data']) ? $values['data'] : $value;
1141 }
1142 }
1143 $rows["move_custom_$fid"]['title'] = $field['label'];
1144
1145 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1146 $migrationInfo["move_custom_$fid"] = $value;
1147 }
1148 }
1149 }
1150 $result = array(
1151 'rows' => $rows,
1152 'elements' => $elements,
1153 'rel_table_elements' => $relTableElements,
1154 'main_loc_block' => $mainLocBlock,
1155 'rel_tables' => $relTables,
1156 'main_details' => $main,
1157 'other_details' => $other,
1158 'migration_info' => $migrationInfo,
1159 );
1160
1161 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1162 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1163
1164 return $result;
1165 }
1166
1167 /**
1168 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1169 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1170 * A superset of moveContactBelongings() function.
1171 *
1172 * @param int $mainId main contact with whom merge has to happen
1173 * @param int $otherId duplicate contact which would be deleted after merge operation
1174 *
1175 * @static
1176 * @access public
1177 */
1178 static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1179 if (empty($migrationInfo)) {
1180 return FALSE;
1181 }
1182
1183 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1184 $relTables = CRM_Dedupe_Merger::relTables();
1185 $moveTables = $locBlocks = $tableOperations = array();
1186 foreach ($migrationInfo as $key => $value) {
1187 if ($value == $qfZeroBug) {
1188 $value = '0';
1189 }
1190 if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) ||
1191 substr($key, 0, 12) == 'move_custom_') &&
1192 $value != NULL
1193 ) {
1194 $submitted[substr($key, 5)] = $value;
1195 }
1196 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1197 $locField = explode('_', $key);
1198 $fieldName = $locField[2];
1199 $fieldCount = $locField[3];
1200 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1201 // default operation is overwrite.
1202 if (!$operation) {
1203 $operation = 2;
1204 }
1205
1206 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1207 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1208 }
1209 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1210 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1211 if (array_key_exists('operation', $migrationInfo)) {
1212 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1213 if (array_key_exists($key, $migrationInfo['operation'])) {
1214 $tableOperations[$table] = $migrationInfo['operation'][$key];
1215 }
1216 }
1217 }
1218 }
1219 }
1220
1221
1222 // **** Do location related migration:
1223 if (!empty($locBlocks)) {
1224 $locComponent = array(
1225 'email' => 'Email',
1226 'phone' => 'Phone',
1227 'im' => 'IM',
1228 'openid' => 'OpenID',
1229 'address' => 'Address',
1230 );
1231
1232 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
1233 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
1234
1235 foreach ($locBlocks as $name => $block) {
1236 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1237 continue;
1238 }
1239 $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
1240 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1241 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1242
1243 foreach ($block as $blkCount => $values) {
1244 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
1245 $operation = CRM_Utils_Array::value('operation', $values, 2);
1246 $otherBlockId = CRM_Utils_Array::value($blkCount,
1247 $migrationInfo['other_details']['loc_block_ids'][$name]
1248 );
1249
1250 // keep 1-1 mapping for address - loc type.
1251 $idKey = $blkCount;
1252 if (array_key_exists($name, $locComponent)) {
1253 $idKey = $locTypeId;
1254 }
1255
1256 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1257 $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1258 }
1259
1260 if (!$otherBlockId) {
1261 continue;
1262 }
1263
1264 // for the block which belongs to other-contact, link the contact to main-contact
1265 $otherBlockDAO = new $daoName();
1266 $otherBlockDAO->id = $otherBlockId;
1267 $otherBlockDAO->contact_id = $mainId;
1268 $otherBlockDAO->location_type_id = $locTypeId;
1269
1270 // if main contact already has primary & billing, set the flags to 0.
1271 if ($primaryDAOId) {
1272 $otherBlockDAO->is_primary = 0;
1273 }
1274 if ($billingDAOId) {
1275 $otherBlockDAO->is_billing = 0;
1276 }
1277
1278 // overwrite - need to delete block which belongs to main-contact.
1279 if ($mainBlockId && ($operation == 2)) {
1280 $deleteDAO = new $daoName();
1281 $deleteDAO->id = $mainBlockId;
1282 $deleteDAO->find(TRUE);
1283
1284 // if we about to delete a primary / billing block, set the flags for new block
1285 // that we going to assign to main-contact
1286 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1287 $otherBlockDAO->is_primary = 1;
1288 }
1289 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1290 $otherBlockDAO->is_billing = 1;
1291 }
1292
1293 $deleteDAO->delete();
1294 $deleteDAO->free();
1295 }
1296
1297 $otherBlockDAO->update();
1298 $otherBlockDAO->free();
1299 }
1300 }
1301 }
1302
1303 // **** Do tables related migrations
1304 if (!empty($moveTables)) {
1305 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1306 unset($moveTables, $tableOperations);
1307 }
1308
1309 // **** Do contact related migrations
1310 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
1311
1312 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1313 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1314 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1315 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1316 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1317 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1318 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1319 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1320
1321 // fix custom fields so they're edible by createProfileContact()
1322 static $treeCache = array();
1323 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1324 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'],
1325 CRM_Core_DAO::$_nullObject, NULL, -1
1326 );
1327 }
1328 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1329
1330 $cFields = array();
1331 foreach ($cgTree as $key => $group) {
1332 if (!isset($group['fields'])) {
1333 continue;
1334 }
1335 foreach ($group['fields'] as $fid => $field) {
1336 $cFields[$fid]['attributes'] = $field;
1337 }
1338 }
1339
1340 if (!isset($submitted)) {
1341 $submitted = array();
1342 }
1343 foreach ($submitted as $key => $value) {
1344 if (substr($key, 0, 7) == 'custom_') {
1345 $fid = (int) substr($key, 7);
1346 $htmlType = $cFields[$fid]['attributes']['html_type'];
1347 switch ($htmlType) {
1348 case 'File':
1349 $customFiles[] = $fid;
1350 unset($submitted["custom_$fid"]);
1351 break;
1352
1353 case 'Select Country':
1354 case 'Select State/Province':
1355 $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
1356 break;
1357
1358 case 'CheckBox':
1359 case 'AdvMulti-Select':
1360 case 'Multi-Select':
1361 case 'Multi-Select Country':
1362 case 'Multi-Select State/Province':
1363 // Merge values from both contacts for multivalue fields, CRM-4385
1364 // get the existing custom values from db.
1365 $customParams = array('entityID' => $mainId, $key => TRUE);
1366 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
1367 if (CRM_Utils_array::value($key, $customfieldValues)) {
1368 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1369 if (is_array($existingValue) && !empty($existingValue)) {
1370 $mergeValue = $submmtedCustomValue = array();
1371 if ($value) {
1372 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1373 }
1374
1375 //hack to remove null and duplicate values from array.
1376 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1377 if ($v != '' && !in_array($v, $mergeValue)) {
1378 $mergeValue[] = $v;
1379 }
1380 }
1381
1382 //keep state and country as array format.
1383 //for checkbox and m-select format w/ VALUE_SEPARATOR
1384 if (in_array($htmlType, array(
1385 'CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
1386 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1387 $mergeValue
1388 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1389 }
1390 else {
1391 $submitted[$key] = $mergeValue;
1392 }
1393 }
1394 }
1395 elseif (in_array($htmlType, array(
1396 'Multi-Select Country', 'Multi-Select State/Province'))) {
1397 //we require submitted values should be in array format
1398 if ($value) {
1399 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1400 //hack to remove null values from array.
1401 $mergeValue = array();
1402 foreach ($mergeValueArray as $k => $v) {
1403 if ($v != '') {
1404 $mergeValue[] = $v;
1405 }
1406 }
1407 $submitted[$key] = $mergeValue;
1408 }
1409 }
1410 break;
1411
1412 default:
1413 break;
1414 }
1415 }
1416 }
1417
1418 // **** Do file custom fields related migrations
1419 // FIXME: move this someplace else (one of the BAOs) after discussing
1420 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1421 // like, delete a file...
1422
1423 if (!isset($customFiles)) {
1424 $customFiles = array();
1425 }
1426 foreach ($customFiles as $customId) {
1427 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1428
1429 // get the contact_id -> file_id mapping
1430 $fileIds = array();
1431 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1432 $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1433 while ($dao->fetch()) {
1434 $fileIds[$dao->entity_id] = $dao->file_id;
1435 }
1436 $dao->free();
1437
1438 // delete the main contact's file
1439 if (!empty($fileIds[$mainId])) {
1440 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1441 }
1442
1443 // move the other contact's file to main contact
1444 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1445 if ( CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}") ) {
1446 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1447 }
1448 else {
1449 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1450 }
1451 CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1452
1453 if ( CRM_Core_DAO::singleValueQuery("
1454 SELECT id
1455 FROM civicrm_entity_file
1456 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}") ) {
1457 $sql = "
1458 UPDATE civicrm_entity_file
1459 SET entity_id = {$mainId}
1460 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1461 }
1462 else {
1463 $sql = "
1464 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1465 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1466 }
1467 CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
1468 }
1469
1470 // move view only custom fields CRM-5362
1471 $viewOnlyCustomFields = array();
1472 foreach ($submitted as $key => $value) {
1473 $fid = (int) substr($key, 7);
1474 if (array_key_exists($fid, $cFields) &&
1475 CRM_Utils_Array::value('is_view', $cFields[$fid]['attributes'])
1476 ) {
1477 $viewOnlyCustomFields[$key] = $value;
1478 }
1479 }
1480
1481 // special case to set values for view only, CRM-5362
1482 if (!empty($viewOnlyCustomFields)) {
1483 $viewOnlyCustomFields['entityID'] = $mainId;
1484 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1485 }
1486
1487 // **** Delete other contact & update prev-next caching
1488 $otherParams = array(
1489 'contact_id' => $otherId,
1490 'id' => $otherId,
1491 'version' => 3,
1492 );
1493 if (CRM_Core_Permission::check('merge duplicate contacts') &&
1494 CRM_Core_Permission::check('delete contacts')
1495 ) {
1496 // if ext id is submitted then set it null for contact to be deleted
1497 if (CRM_Utils_Array::value('external_identifier', $submitted)) {
1498 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1499 CRM_Core_DAO::executeQuery($query);
1500 }
1501
1502 civicrm_api('contact', 'delete', $otherParams);
1503 CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
1504 }
1505 // FIXME: else part
1506 /* else { */
1507
1508 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1509
1510 /* } */
1511
1512
1513 // **** Update contact related info for the main contact
1514 if (!empty($submitted)) {
1515 $submitted['contact_id'] = $mainId;
1516
1517 //update current employer field
1518 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1519 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1520 $submitted['current_employer'] = $submitted['current_employer_id'];
1521 } else {
1522 $submitted['current_employer'] = '';
1523 }
1524 unset($submitted['current_employer_id']);
1525 }
1526
1527 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
1528 unset($submitted);
1529 }
1530
1531 return TRUE;
1532 }
1533
1534 /**
1535 * @return array of field names which will be compared, so everything except ID.
1536 */
1537 static function getContactFields() {
1538 $contactFields = CRM_Contact_DAO_Contact::fields();
1539 $invalidFields = array('api_key', 'contact_is_deleted', 'created_date', 'display_name', 'hash', 'id', 'modified_date',
1540 'primary_contact_id', 'sort_name', 'user_unique_id');
1541 foreach ($contactFields as $field => $value) {
1542 if (in_array($field, $invalidFields)) {
1543 unset($contactFields[$field]);
1544 }
1545 }
1546 return array_keys($contactFields);
1547 }
1548
1549 /**
1550 * Added for CRM-12695
1551 * Based on the contactId provided
1552 * add/update membership(s) to related contacts
1553 *
1554 * @param contactId
1555 */
1556 static function addMembershipToRealtedContacts($contactID) {
1557 $dao = new CRM_Member_DAO_Membership();
1558 $dao->contact_id = $contactID;
1559 $dao->is_test = 0;
1560 $dao->find();
1561
1562 //checks membership of contact itself
1563 while ($dao->fetch()) {
1564 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1565 if ($relationshipTypeId) {
1566 $membershipParams = array(
1567 'id' => $dao->id,
1568 'contact_id' => $dao->contact_id,
1569 'membership_type_id' => $dao->membership_type_id,
1570 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1571 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1572 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1573 'source' => $dao->source,
1574 'status_id' => $dao->status_id
1575 );
1576 // create/update membership(s) for related contact(s)
1577 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1578 } // end of if relationshipTypeId
1579 }
1580 }
1581 }