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