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