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