Refactoring and UI improvements
[civicrm-core.git] / CRM / Dedupe / Merger.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 */
33 class CRM_Dedupe_Merger {
34
35 /**
36 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
37 * FIXME: the sub-pages references by the URLs should
38 * be loaded dynamically on the merge form instead
39 * @return array
40 */
41 public static function relTables() {
42 static $relTables;
43
44 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
45 // if the url can't be retrieved. A more standardised way to retrieve them is.
46 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
47 // we may need a different function when it is not known.
48 $title = $userRecordUrl = '';
49
50 $config = CRM_Core_Config::singleton();
51 if ($config->userSystem->is_drupal) {
52 $userRecordUrl = CRM_Utils_System::url('user/%ufid');
53 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
54 }
55 elseif ($config->userFramework == 'Joomla') {
56 $userRecordUrl = $config->userSystem->getVersion() > 1.5 ? $config->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . '%ufid' : $config->userFrameworkBaseURL . "index2.php?option=com_users&view=user&task=edit&id[]=" . '%ufid';
57 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
58 }
59
60 if (!$relTables) {
61 $relTables = array(
62 'rel_table_contributions' => array(
63 'title' => ts('Contributions'),
64 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
65 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
66 ),
67 'rel_table_contribution_page' => array(
68 'title' => ts('Contribution Pages'),
69 'tables' => array('civicrm_contribution_page'),
70 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
71 ),
72 'rel_table_memberships' => array(
73 'title' => ts('Memberships'),
74 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
75 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
76 ),
77 'rel_table_participants' => array(
78 'title' => ts('Participants'),
79 'tables' => array('civicrm_participant'),
80 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
81 ),
82 'rel_table_events' => array(
83 'title' => ts('Events'),
84 'tables' => array('civicrm_event'),
85 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
86 ),
87 'rel_table_activities' => array(
88 'title' => ts('Activities'),
89 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
90 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
91 ),
92 'rel_table_relationships' => array(
93 'title' => ts('Relationships'),
94 'tables' => array('civicrm_relationship'),
95 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
96 ),
97 'rel_table_custom_groups' => array(
98 'title' => ts('Custom Groups'),
99 'tables' => array('civicrm_custom_group'),
100 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
101 ),
102 'rel_table_uf_groups' => array(
103 'title' => ts('Profiles'),
104 'tables' => array('civicrm_uf_group'),
105 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
106 ),
107 'rel_table_groups' => array(
108 'title' => ts('Groups'),
109 'tables' => array('civicrm_group_contact'),
110 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
111 ),
112 'rel_table_notes' => array(
113 'title' => ts('Notes'),
114 'tables' => array('civicrm_note'),
115 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
116 ),
117 'rel_table_tags' => array(
118 'title' => ts('Tags'),
119 'tables' => array('civicrm_entity_tag'),
120 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
121 ),
122 'rel_table_mailings' => array(
123 'title' => ts('Mailings'),
124 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
125 'url' => CRM_Utils_System::url('civicrm/mailing', 'reset=1&force=1&cid=$cid'),
126 ),
127 'rel_table_cases' => array(
128 'title' => ts('Cases'),
129 'tables' => array('civicrm_case_contact'),
130 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
131 ),
132 'rel_table_grants' => array(
133 'title' => ts('Grants'),
134 'tables' => array('civicrm_grant'),
135 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
136 ),
137 'rel_table_pcp' => array(
138 'title' => ts('PCPs'),
139 'tables' => array('civicrm_pcp'),
140 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
141 ),
142 'rel_table_pledges' => array(
143 'title' => ts('Pledges'),
144 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
145 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
146 ),
147 'rel_table_users' => array(
148 'title' => $title,
149 'tables' => array('civicrm_uf_match'),
150 'url' => $userRecordUrl,
151 ),
152 );
153
154 $relTables += self::getMultiValueCustomSets('relTables');
155
156 // Allow hook_civicrm_merge() to adjust $relTables
157 CRM_Utils_Hook::merge('relTables', $relTables);
158 }
159 return $relTables;
160 }
161
162 /**
163 * Returns the related tables groups for which a contact has any info entered.
164 *
165 * @param int $cid
166 *
167 * @return array
168 */
169 public static function getActiveRelTables($cid) {
170 $cid = (int) $cid;
171 $groups = array();
172
173 $relTables = self::relTables();
174 $cidRefs = self::cidRefs();
175 $eidRefs = self::eidRefs();
176 foreach ($relTables as $group => $params) {
177 $sqls = array();
178 foreach ($params['tables'] as $table) {
179 if (isset($cidRefs[$table])) {
180 foreach ($cidRefs[$table] as $field) {
181 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
182 }
183 }
184 if (isset($eidRefs[$table])) {
185 foreach ($eidRefs[$table] as $entityTable => $entityId) {
186 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
187 }
188 }
189 foreach ($sqls as $sql) {
190 if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
191 $groups[] = $group;
192 }
193 }
194 }
195 }
196 return array_unique($groups);
197 }
198
199 /**
200 * Return tables and their fields referencing civicrm_contact.contact_id explicitly
201 */
202 public static function cidRefs() {
203 static $cidRefs;
204 if (!$cidRefs) {
205 $sql = "
206 SELECT
207 table_name,
208 column_name
209 FROM information_schema.key_column_usage
210 WHERE
211 referenced_table_schema = database() AND
212 referenced_table_name = 'civicrm_contact' AND
213 referenced_column_name = 'id';
214 ";
215 $dao = CRM_Core_DAO::executeQuery($sql);
216 while ($dao->fetch()) {
217 $cidRefs[$dao->table_name][] = $dao->column_name;
218 }
219
220 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
221 $cidRefs['civicrm_entity_tag'][] = 'entity_id';
222 $dao->free();
223
224 // Allow hook_civicrm_merge() to adjust $cidRefs
225 CRM_Utils_Hook::merge('cidRefs', $cidRefs);
226 }
227 return $cidRefs;
228 }
229
230 /**
231 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
232 */
233 public static function eidRefs() {
234 static $eidRefs;
235 if (!$eidRefs) {
236 // FIXME: this should be generated dynamically from the schema
237 // tables that reference contacts with entity_{id,table}
238 $eidRefs = array(
239 'civicrm_acl' => array('entity_table' => 'entity_id'),
240 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
241 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
242 'civicrm_log' => array('entity_table' => 'entity_id'),
243 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
244 'civicrm_note' => array('entity_table' => 'entity_id'),
245 );
246
247 // Allow hook_civicrm_merge() to adjust $eidRefs
248 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
249 }
250 return $eidRefs;
251 }
252
253 /**
254 * Return tables using locations.
255 */
256 public static function locTables() {
257 static $locTables;
258 if (!$locTables) {
259 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
260
261 // Allow hook_civicrm_merge() to adjust $locTables
262 CRM_Utils_Hook::merge('locTables', $locTables);
263 }
264 return $locTables;
265 }
266
267 /**
268 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
269 * @param string $request
270 * 'relTables' or 'cidRefs'.
271 * @see CRM-13836
272 */
273 public static function getMultiValueCustomSets($request) {
274 static $data = NULL;
275 if ($data === NULL) {
276 $data = array(
277 'relTables' => array(),
278 'cidRefs' => array(),
279 );
280 $result = civicrm_api3('custom_group', 'get', array(
281 'is_multiple' => 1,
282 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
283 'return' => array('id', 'title', 'table_name', 'style'),
284 ));
285 foreach ($result['values'] as $custom) {
286 $data['cidRefs'][$custom['table_name']] = array('entity_id');
287 $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
288 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
289 'title' => $custom['title'],
290 'tables' => array($custom['table_name']),
291 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
292 );
293 }
294 }
295 return $data[$request];
296 }
297
298 /**
299 * Tables which require custom processing should declare functions to call here.
300 * Doing so will override normal processing.
301 */
302 public static function cpTables() {
303 static $tables;
304 if (!$tables) {
305 $tables = array(
306 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
307 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
308 // Empty array == do nothing - this table is handled by mergeGroupContact
309 'civicrm_subscription_history' => array(),
310 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
311 );
312 }
313 return $tables;
314 }
315
316 /**
317 * Return payment related table.
318 */
319 public static function paymentTables() {
320 static $tables;
321 if (!$tables) {
322 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
323 }
324 return $tables;
325 }
326
327 /**
328 * Return payment update Query.
329 *
330 * @param string $tableName
331 * @param int $mainContactId
332 * @param int $otherContactId
333 *
334 * @return array
335 */
336 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
337 $sqls = array();
338 if (!$tableName || !$mainContactId || !$otherContactId) {
339 return $sqls;
340 }
341
342 $paymentTables = self::paymentTables();
343 if (!in_array($tableName, $paymentTables)) {
344 return $sqls;
345 }
346
347 switch ($tableName) {
348 case 'civicrm_pledge':
349 $sqls[] = "
350 UPDATE IGNORE civicrm_contribution contribution
351 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
352 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
353 SET contribution.contact_id = $mainContactId
354 WHERE pledge.contact_id = $otherContactId";
355 break;
356
357 case 'civicrm_membership':
358 $sqls[] = "
359 UPDATE IGNORE civicrm_contribution contribution
360 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
361 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
362 SET contribution.contact_id = $mainContactId
363 WHERE membership.contact_id = $otherContactId";
364 break;
365
366 case 'civicrm_participant':
367 $sqls[] = "
368 UPDATE IGNORE civicrm_contribution contribution
369 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
370 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
371 SET contribution.contact_id = $mainContactId
372 WHERE participant.contact_id = $otherContactId";
373 break;
374 }
375
376 return $sqls;
377 }
378
379 /**
380 * @param int $mainId
381 * @param int $otherId
382 * @param string $tableName
383 * @param array $tableOperations
384 * @param string $mode
385 *
386 * @return array
387 */
388 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
389 $sqls = array();
390 if (!$tableName || !$mainId || !$otherId) {
391 return $sqls;
392 }
393
394 switch ($tableName) {
395 case 'civicrm_membership':
396 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
397 break;
398 }
399 if ($mode == 'add') {
400 $sqls[] = "
401 DELETE membership1.* FROM civicrm_membership membership1
402 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
403 AND membership1.contact_id = {$mainId}
404 AND membership2.contact_id = {$otherId} ";
405 }
406 if ($mode == 'payment') {
407 $sqls[] = "
408 DELETE contribution.* FROM civicrm_contribution contribution
409 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
410 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
411 AND membership1.contact_id = {$mainId}
412 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
413 AND membership2.contact_id = {$otherId}";
414 }
415 break;
416
417 case 'civicrm_uf_match':
418 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
419 // failing to meet intended result. Therefore we introduce this additional query:
420 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
421 break;
422 }
423
424 return $sqls;
425 }
426
427 /**
428 * Based on the provided two contact_ids and a set of tables, move the
429 * belongings of the other contact to the main one.
430 *
431 * @param int $mainId
432 * @param int $otherId
433 * @param bool $tables
434 * @param array $tableOperations
435 */
436 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
437 $cidRefs = self::cidRefs();
438 $eidRefs = self::eidRefs();
439 $cpTables = self::cpTables();
440 $paymentTables = self::paymentTables();
441 $membershipMerge = FALSE; // CRM-12695
442
443 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
444 if ($tables !== FALSE) {
445 // if there are specific tables, sanitize the list
446 $affected = array_unique(array_intersect($affected, $tables));
447 }
448 else {
449 // if there aren't any specific tables, don't affect the ones handled by relTables()
450 // also don't affect tables in locTables() CRM-15658
451 $relTables = self::relTables();
452 $handled = self::locTables();
453 foreach ($relTables as $params) {
454 $handled = array_merge($handled, $params['tables']);
455 }
456 $affected = array_diff($affected, $handled);
457 /**
458 * CRM-12695
459 * Set $membershipMerge flag only once
460 * while doing contact related migration
461 * to call addMembershipToRealtedContacts()
462 * function only once.
463 * Since the current function (moveContactBelongings) is called twice
464 * with & without parameters $tables & $tableOperations
465 */
466 // retrieve main contact's related table(s)
467 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
468 // check if membership table exists in main contact's related table(s)
469 if (in_array('rel_table_memberships', $activeMainRelTables)) {
470 $membershipMerge = TRUE; // set membership flag - CRM-12695
471 }
472 }
473
474 $mainId = (int) $mainId;
475 $otherId = (int) $otherId;
476
477 $sqls = array();
478 foreach ($affected as $table) {
479 // Call custom processing function for objects that require it
480 if (isset($cpTables[$table])) {
481 foreach ($cpTables[$table] as $className => $fnName) {
482 $className::$fnName($mainId, $otherId, $sqls);
483 }
484 // Skip normal processing
485 continue;
486 }
487
488 // use UPDATE IGNORE + DELETE query pair to skip on situations when
489 // there's a UNIQUE restriction on ($field, some_other_field) pair
490 if (isset($cidRefs[$table])) {
491 foreach ($cidRefs[$table] as $field) {
492 // carry related contributions CRM-5359
493 if (in_array($table, $paymentTables)) {
494 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
495 $sqls = array_merge($sqls, $paymentSqls);
496
497 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
498 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
499 $sqls = array_merge($sqls, $payOprSqls);
500 }
501 }
502
503 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
504 $sqls = array_merge($sqls, $preOperationSqls);
505
506 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
507 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
508 }
509 }
510 if (isset($eidRefs[$table])) {
511 foreach ($eidRefs[$table] as $entityTable => $entityId) {
512 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
513 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
514 }
515 }
516 }
517
518 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
519 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
520
521 // call the SQL queries in one transaction
522 $transaction = new CRM_Core_Transaction();
523 foreach ($sqls as $sql) {
524 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE);
525 }
526 // CRM-12695
527 if ($membershipMerge) {
528 // call to function adding membership to related contacts
529 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
530 }
531 $transaction->commit();
532 }
533
534 /**
535 * Load all non-empty fields for the contacts
536 *
537 * @param array $main
538 * Contact details.
539 * @param array $other
540 * Contact details.
541 *
542 * @return array
543 */
544 public static function retrieveFields($main, $other) {
545 $result = array(
546 'contact' => array(),
547 'custom' => array(),
548 );
549 foreach (self::getContactFields() as $validField) {
550 // CRM-17556 Get all non-empty fields, to make comparison easier
551 if (!empty($main[$validField]) || !empty($other[$validField])) {
552 $result['contact'][] = $validField;
553 }
554 }
555
556 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
557 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
558 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
559 foreach ($keys as $key) {
560 // Exclude multi-value fields CRM-13836
561 if (strpos($key, '_')) {
562 continue;
563 }
564 $key1 = CRM_Utils_Array::value($key, $mainEvs);
565 $key2 = CRM_Utils_Array::value($key, $otherEvs);
566 // CRM-17556 Get all non-empty fields, to make comparison easier
567 if (!empty($key1) || !empty($key2)) {
568 $result['custom'][] = $key;
569 }
570 }
571 return $result;
572 }
573
574 /**
575 * Batch merge a set of contacts based on rule-group and group.
576 *
577 * @param int $rgid
578 * Rule group id.
579 * @param int $gid
580 * Group id.
581 * @param string $mode
582 * Helps decide how to behave when there are conflicts.
583 * A 'safe' value skips the merge if there are any un-resolved conflicts.
584 * Does a force merge otherwise.
585 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
586 * Wether to let api decide which contact to retain and which to delete.
587 * @param int $batchLimit number of merges to carry out in one batch.
588 * @param int $isSelected if records with is_selected column needs to be processed.
589 *
590 * @return array|bool
591 */
592 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $batchLimit = 1, $isSelected = 2) {
593 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
594 $cacheKeyString = "merge {$contactType}";
595 $cacheKeyString .= $rgid ? "_{$rgid}" : '_0';
596 $cacheKeyString .= $gid ? "_{$gid}" : '_0';
597 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
598 pn.entity_id2 = de.contact_id2 )";
599
600 $where = "de.id IS NULL";
601 if ($isSelected === 0 || $isSelected === 1) {
602 $where .= " AND pn.is_selected = {$isSelected}";
603 }// else consider all dupe pairs
604 $where .= " LIMIT {$batchLimit}";
605
606 $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
607
608 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
609 if (empty($dupePairs) && !$redirectForPerformance && $isSelected == 2) {
610 // If we haven't found any dupes, probably cache is empty.
611 // Try filling cache and give another try.
612 CRM_Core_BAO_PrevNextCache::refillCache($rgid, $gid, $cacheKeyString);
613 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
614 }
615
616 $cacheParams = array(
617 'cache_key_string' => $cacheKeyString,
618 'join' => $join,
619 'where' => $where,
620 );
621 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance);
622 }
623
624 public static function updateMergeStats($cacheKeyString, $result = array()) {
625 // gather latest stats
626 $merged = count($result['merged']);
627 $skipped = count($result['skipped']);
628
629 if ($merged <= 0 && $skipped <= 0) {
630 return;
631 }
632
633 // get previous stats
634 $previousStats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
635 if (!empty($previousStats)) {
636 if ($previousStats[0]['merged']) {
637 $merged = $merged + $previousStats[0]['merged'];
638 }
639 if ($previousStats[0]['skipped']) {
640 $skipped = $skipped + $previousStats[0]['skipped'];
641 }
642 }
643
644 // delete old stats
645 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
646
647 // store the updated stats
648 $data = array(
649 'merged' => $merged,
650 'skipped' => $skipped,
651 );
652 $data = CRM_Core_DAO::escapeString(serialize($data));
653
654 $values = array();
655 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
656 CRM_Core_BAO_PrevNextCache::setItem($values);
657 }
658
659 public static function resetMergeStats($cacheKeyString) {
660 return CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
661 }
662
663 public static function getMergeStats($cacheKeyString) {
664 $stats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
665 if (!empty($stats)) {
666 $stats = $stats[0];
667 }
668 return $stats;
669 }
670
671 public static function getMergeStatsMsg($cacheKeyString) {
672 $msg = '';
673 $stats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
674 if (!empty($stats['merged'])) {
675 $msg = "{$stats['merged']} " . ts(' Contact(s) were merged. ');
676 }
677 if (!empty($stats['skipped'])) {
678 $msg .= $stats['skipped'] . ts(' Contact(s) were skipped.');
679 }
680 return $msg;
681 }
682
683 /**
684 * Merge given set of contacts. Performs core operation.
685 *
686 * @param array $dupePairs
687 * Set of pair of contacts for whom merge is to be done.
688 * @param array $cacheParams
689 * Prev-next-cache params based on which next pair of contacts are computed.
690 * Generally used with batch-merge.
691 * @param string $mode
692 * Helps decide how to behave when there are conflicts.
693 * A 'safe' value skips the merge if there are any un-resolved conflicts.
694 * Does a force merge otherwise (aggressive mode).
695 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
696 * Wether to let api decide which contact to retain and which to delete.
697 *
698 *
699 * @param bool $redirectForPerformance
700 *
701 * @return array|bool
702 */
703 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
704 $autoFlip = TRUE, $redirectForPerformance = FALSE
705 ) {
706 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
707 $resultStats = array('merged' => array(), 'skipped' => array());
708
709 // we don't want dupe caching to get reset after every-merge, and therefore set the
710 // doNotResetCache flag
711 $config = CRM_Core_Config::singleton();
712 $config->doNotResetCache = 1;
713
714 while (!empty($dupePairs)) {
715 foreach ($dupePairs as $dupes) {
716 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
717 $mainId = $dupes['dstID'];
718 $otherId = $dupes['srcID'];
719 $isAutoFlip = CRM_Utils_Array::value('auto_flip', $dupes, $autoFlip);
720 // if we can, make sure that $mainId is the one with lower id number
721 if ($isAutoFlip && ($mainId > $otherId)) {
722 $mainId = $dupes['srcID'];
723 $otherId = $dupes['dstID'];
724 }
725 if (!$mainId || !$otherId) {
726 // return error
727 return FALSE;
728 }
729
730 // Generate var $migrationInfo. The variable structure is exactly same as
731 // $formValues submitted during a UI merge for a pair of contacts.
732 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId);
733
734 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
735
736 // add additional details that we might need to resolve conflicts
737 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
738 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
739 $migrationInfo['main_loc_block'] = &$rowsElementsAndInfo['main_loc_block'];
740 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
741
742 // go ahead with merge if there is no conflict
743 $conflicts = array();
744 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
745 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo);
746 $resultStats['merged'][] = array('main_id' => $mainId, 'other_id' => $otherId);
747 }
748 else {
749 $resultStats['skipped'][] = array('main_id' => $mainId, 'other_id' => $otherId);
750 }
751
752 // store any conflicts
753 if (!empty($conflicts)) {
754 foreach ($conflicts as $key => $dnc) {
755 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
756 }
757 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
758 }
759 else {
760 // delete entry from PrevNextCache table so we don't consider the pair next time
761 // pair may have been flipped, so make sure we delete using both orders
762 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
763 }
764
765 CRM_Core_DAO::freeResult();
766 unset($rowsElementsAndInfo, $migrationInfo);
767 }
768
769 if ($cacheKeyString && !$redirectForPerformance) {
770 // retrieve next pair of dupes
771 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
772 $cacheParams['join'],
773 $cacheParams['where']
774 );
775 }
776 else {
777 // do not proceed. Terminate the loop
778 unset($dupePairs);
779 }
780 }
781
782 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
783 return $resultStats;
784 }
785
786 /**
787 * A function which uses various rules / algorithms for choosing which contact to bias to
788 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
789 *
790 * @param int $mainId
791 * Main contact with whom merge has to happen.
792 * @param int $otherId
793 * Duplicate contact which would be deleted after merge operation.
794 * @param array $migrationInfo
795 * Array of information about which elements to merge.
796 * @param string $mode
797 * Helps decide how to behave when there are conflicts.
798 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
799 * - Does a force merge otherwise (aggressive mode).
800 *
801 * @param array $conflicts
802 *
803 * @return bool
804 */
805 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
806
807 $migrationData = array(
808 'old_migration_info' => $migrationInfo,
809 'mode' => $mode,
810 );
811
812 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
813 $allPhoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
814 $allProviderTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
815 $allWebsiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
816
817 foreach ($migrationInfo as $key => $val) {
818 if ($val === "null") {
819 // Rule: Never overwrite with an empty value (in any mode)
820 unset($migrationInfo[$key]);
821 continue;
822 }
823 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
824 substr($key, 0, 12) == 'move_custom_'
825 ) and $val != NULL
826 ) {
827 // Rule: If both main-contact, and other-contact have a field with a
828 // different value, then let $mode decide if to merge it or not
829 if (
830 !empty($migrationInfo['rows'][$key]['main'])
831 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
832 ) {
833
834 // note it down & lets wait for response from the hook.
835 // For no response $mode will decide if to skip this merge
836 $conflicts[$key] = NULL;
837 }
838 }
839 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
840 $locField = explode('_', $key);
841 $fieldName = $locField[2];
842 $fieldCount = $locField[3];
843
844 // Rule: resolve address conflict if any
845 if ($fieldName == 'address') {
846 $mainNewLocTypeId = $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'];
847 if (!empty($migrationInfo['main_loc_block']) &&
848 array_key_exists("main_address_{$mainNewLocTypeId}", $migrationInfo['main_loc_block'])) {
849 // main loc already has some address for the loc-type. Its a overwrite situation.
850 // look for next available loc-type
851 $newTypeId = NULL;
852 foreach ($allLocationTypes as $typeId => $typeLabel) {
853 if (!array_key_exists("main_address_{$typeId}", $migrationInfo['main_loc_block'])) {
854 $newTypeId = $typeId;
855 }
856 }
857 if ($newTypeId) {
858 // try insert address at new available loc-type
859 $migrationInfo['location'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
860 }
861 else {
862 // note it down & lets wait for response from the hook.
863 // For no response $mode will decide if to skip this merge
864 $conflicts[$key] = NULL;
865 }
866 }
867 }
868 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
869 // for loc blocks other than address like email, phone .. if values are same no point in merging
870 // and adding redundant value
871 unset($migrationInfo[$key]);
872 }
873 }
874 }
875
876 // A hook to implement other algorithms for choosing which contact to bias to when
877 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
878 // merge happens with new values filled in here. For a particular field / row not to be merged
879 // field should be unset from fields_in_conflict.
880 $migrationData['fields_in_conflict'] = $conflicts;
881 $migrationData['merge_mode'] = $mode;
882 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
883 $conflicts = $migrationData['fields_in_conflict'];
884 // allow hook to override / manipulate migrationInfo as well
885 $migrationInfo = $migrationData['old_migration_info'];
886
887 if (!empty($conflicts)) {
888 foreach ($conflicts as $key => $val) {
889 if ($val === NULL and $mode == 'safe') {
890 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
891 return TRUE;
892 }
893 else {
894 // copy over the resolved values
895 $migrationInfo[$key] = $val;
896 }
897 }
898 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
899 if (array_key_exists('skip_merge', $migrationData)) {
900 return (bool) $migrationData['skip_merge'];
901 }
902 }
903 return FALSE;
904 }
905
906 /**
907 * A function to build an array of information required by merge function and the merge UI.
908 *
909 * @param int $mainId
910 * Main contact with whom merge has to happen.
911 * @param int $otherId
912 * Duplicate contact which would be deleted after merge operation.
913 *
914 * @return array|bool|int
915 * 'main_loc_block' => Stores all location blocks associated with the 'main' contact
916 */
917 public static function getRowsElementsAndInfo($mainId, $otherId) {
918 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
919
920 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
921 $allPhoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
922 $allProviderTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
923 $allWebsiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
924 $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
925
926 // Fetch contacts
927 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
928 $params = array(
929 'contact_id' => $cid,
930 'version' => 3,
931 'return' => array_merge(array('display_name'), self::getContactFields()),
932 );
933 $result = civicrm_api('contact', 'get', $params);
934
935 if (empty($result['values'][$cid]['contact_type'])) {
936 return FALSE;
937 }
938 $$moniker = $result['values'][$cid];
939 }
940
941 static $fields = array();
942 if (empty($fields)) {
943 $fields = CRM_Contact_DAO_Contact::fields();
944 CRM_Core_DAO::freeResult();
945 }
946
947 // FIXME: there must be a better way
948 foreach (array('main', 'other') as $moniker) {
949 $contact = &$$moniker;
950 $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
951 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
952 $specialValues[$moniker] = array(
953 'preferred_communication_method' => $value,
954 'communication_style_id' => $value,
955 );
956
957 if (!empty($contact['preferred_communication_method'])) {
958 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
959 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
960 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
961 }
962 $names = array(
963 'preferred_communication_method' => array(
964 'newName' => 'preferred_communication_method_display',
965 'groupName' => 'preferred_communication_method',
966 ),
967 );
968 CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
969
970 if (!empty($contact['communication_style'])) {
971 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
972 }
973 }
974
975 static $optionValueFields = array();
976 if (empty($optionValueFields)) {
977 $optionValueFields = CRM_Core_OptionValue::getFields();
978 }
979 foreach ($optionValueFields as $field => $params) {
980 $fields[$field]['title'] = $params['title'];
981 }
982
983 $compareFields = self::retrieveFields($main, $other);
984
985 $rows = $elements = $relTableElements = $migrationInfo = array();
986
987 foreach ($compareFields['contact'] as $field) {
988 if ($field == 'contact_sub_type') {
989 // CRM-15681 don't display sub-types in UI
990 continue;
991 }
992 foreach (array('main', 'other') as $moniker) {
993 $contact = &$$moniker;
994 $value = CRM_Utils_Array::value($field, $contact);
995 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
996 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
997 }
998 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
999 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
1000 if ($value) {
1001 $value = str_replace('-', '', $value);
1002 $label = CRM_Utils_Date::customFormat($label);
1003 }
1004 else {
1005 $value = "null";
1006 }
1007 }
1008 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
1009 if ($label === '0') {
1010 $label = ts('[ ]');
1011 }
1012 if ($label === '1') {
1013 $label = ts('[x]');
1014 }
1015 }
1016 elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
1017 $label = CRM_Utils_Array::value('individual_prefix', $contact);
1018 $value = CRM_Utils_Array::value('prefix_id', $contact);
1019 $field = 'prefix_id';
1020 }
1021 elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
1022 $label = CRM_Utils_Array::value('individual_suffix', $contact);
1023 $value = CRM_Utils_Array::value('suffix_id', $contact);
1024 $field = 'suffix_id';
1025 }
1026 elseif ($field == 'gender_id' && !empty($value)) {
1027 $label = $genders[$value];
1028 }
1029 elseif ($field == 'current_employer_id' && !empty($value)) {
1030 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
1031 }
1032 $rows["move_$field"][$moniker] = $label;
1033 if ($moniker == 'other') {
1034 //CRM-14334
1035 if ($value === NULL || $value == '') {
1036 $value = 'null';
1037 }
1038 if ($value === 0 or $value === '0') {
1039 $value = $qfZeroBug;
1040 }
1041 if (is_array($value) && empty($value[1])) {
1042 $value[1] = NULL;
1043 }
1044
1045 // Display a checkbox to migrate, only if the values are different
1046 if ($value != $main[$field]) {
1047 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1048 }
1049
1050 $migrationInfo["move_$field"] = $value;
1051 }
1052 }
1053 $rows["move_$field"]['title'] = $fields[$field]['title'];
1054 }
1055
1056 // Handle location blocks.
1057 // @todo OpenID not in API yet, so is not supported here.
1058
1059 $locationBlocks = array(
1060 'address' => 'Address',
1061 'email' => 'Email',
1062 'im' => 'IM',
1063 'phone' => 'Phone',
1064 'website' => 'Website',
1065 );
1066 $locations = array();
1067
1068 foreach ($locationBlocks as $blockName => $block) {
1069 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
1070 $cnt = 1;
1071 $searchParams = array(
1072 'version' => 3,
1073 'contact_id' => $cid,
1074 );
1075 // CRM-17556 Order by location and type
1076 // Handle websites (no location, only type)
1077 if ($blockName == 'website') {
1078 $searchParams['options'] = array('sort' => 'website_type_id');
1079 }
1080 // Sort by location and type
1081 elseif ($blockName == 'phone') {
1082 $searchParams['options'] = array('sort' => 'location_type_id,phone_type_id');
1083 }
1084 elseif ($blockName == 'im') {
1085 $searchParams['options'] = array('sort' => 'location_type_id,provider_id');
1086 }
1087 // Sort by just location
1088 else {
1089 $searchParams['options'] = array('sort' => 'location_type_id');
1090 }
1091 $values = civicrm_api($blockName, 'get', $searchParams);
1092 $count = $values['count'];
1093 if ($count) {
1094 if ($count > $cnt) {
1095 foreach ($values['values'] as $value) {
1096 if ($blockName == 'address') {
1097 CRM_Core_BAO_Address::fixAddress($value);
1098 $display = CRM_Utils_Address::format($value);
1099 $locations[$moniker][$blockName][$cnt] = $value;
1100 $locations[$moniker][$blockName][$cnt]['display'] = $display;
1101 }
1102 else {
1103 $locations[$moniker][$blockName][$cnt] = $value;
1104 }
1105
1106 $cnt++;
1107 }
1108 }
1109 else {
1110 $id = $values['id'];
1111 if ($blockName == 'address') {
1112 CRM_Core_BAO_Address::fixAddress($values['values'][$id]);
1113 $display = CRM_Utils_Address::format($values['values'][$id]);
1114 $locations[$moniker][$blockName][$cnt] = $values['values'][$id];
1115 $locations[$moniker][$blockName][$cnt]['display'] = $display;
1116 }
1117 else {
1118 $locations[$moniker][$blockName][$cnt] = $values['values'][$id];
1119 }
1120 }
1121 }
1122 }
1123 }
1124
1125 $mainLocBlock = $locBlockIds = array();
1126 $locBlockIds['main'] = $locBlockIds['other'] = array();
1127 $typeBlockIds['main'] = $typeBlockIds['other'] = array();
1128
1129 foreach ($locationBlocks as $blockName => $block) {
1130 $name = strtolower($block);
1131 foreach (array('main', 'other') as $moniker) {
1132 $locIndex = CRM_Utils_Array::value($moniker, $locations);
1133 $blockValue = CRM_Utils_Array::value($name, $locIndex, array());
1134 if (empty($blockValue)) {
1135 $locValue[$moniker][$name] = 0;
1136 $typeValue[$moniker][$name] = 0;
1137 $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = $typeTypes[$moniker][$name] = array();
1138 }
1139 else {
1140 $locValue[$moniker][$name] = TRUE;
1141 foreach ($blockValue as $count => $blkValues) {
1142
1143 // CRM-17556 Handle the different field settings (locations, types, etc.)
1144 $fldName = $name;
1145 $typeTypeId = NULL;
1146 if ($name == 'email') {
1147 $locTypeId = $blkValues['location_type_id'];
1148 $locTypes[$moniker][$name][$count] = $locTypeId;
1149 }
1150 elseif ($name == 'im') {
1151 $fldName = 'name';
1152 $locTypeId = $blkValues['location_type_id'];
1153 $locTypes[$moniker][$name][$count] = $locTypeId;
1154 $typeTypeId = $blkValues['provider_id'];
1155 $typeTypes[$moniker][$name][$count] = $typeTypeId;
1156 $typeValue[$moniker][$name] = TRUE;
1157 }
1158 elseif ($name == 'address') {
1159 $fldName = 'display';
1160 $locTypeId = $blkValues['location_type_id'];
1161 $locTypes[$moniker][$name][$count] = $locTypeId;
1162 }
1163 elseif ($name == 'website') {
1164 $fldName = 'url';
1165 // Websites have a dummy location type ID, but we don't add it to the 'locTypes' array
1166 // @todo There'll be a better way of handling this
1167 $locTypeId = 0;
1168 $typeTypeId = $blkValues['website_type_id'];
1169 $typeTypes[$moniker][$name][$count] = $typeTypeId;
1170 $typeValue[$moniker][$name] = TRUE;
1171 }
1172 elseif ($name == 'phone') {
1173 $locTypeId = $blkValues['location_type_id'];
1174 $locTypes[$moniker][$name][$count] = $locTypeId;
1175 $typeTypeId = $blkValues['phone_type_id'];
1176 $typeTypes[$moniker][$name][$count] = $typeTypeId;
1177 $typeValue[$moniker][$name] = TRUE;
1178 }
1179
1180 $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName, $blkValues);
1181
1182 // CRM-17556 Add the type (provider) ID to storage
1183 if (!empty($typeTypeId)) {
1184 $typeBlockIds[$moniker][$name][$typeTypeId] = $blkValues['id'];
1185 }
1186
1187 // For the 'main' contact
1188 if ($moniker == 'main') {
1189
1190 // Add this block to the list of 'main' location blocks
1191 // There is a location type, but not necessarily a provider/type (Facebook/mobile/etc.)
1192 if (empty($typeTypeId)) {
1193 $mainLocBlock["main_" . $name . "_" . $locTypeId] = CRM_Utils_Array::value($fldName, $blkValues);
1194 }
1195 else {
1196 $mainLocBlock["main_" . $name . "_" . $locTypeId . "_" . $typeTypeId] = CRM_Utils_Array::value($fldName, $blkValues);
1197 }
1198
1199 // Add this block to the list of location block IDs for the 'main' contact
1200 $locBlockIds['main'][$name][$locTypeId] = $blkValues['id'];
1201
1202 }
1203
1204 // For the 'other' contact
1205 else {
1206 // Add this block to the list of location block IDs for the 'other' contact
1207 // @todo - why is this 'count' not 'locTypeId'?
1208 $locBlockIds['other'][$name][$count] = $blkValues['id'];
1209 }
1210
1211 }
1212 }
1213 }
1214
1215 // Build the selection boxes for changing the location and type on the 'main' contact side of the form
1216
1217 // Websites are skipped later as they don't have location but do have a type
1218 foreach ($locLabel['other'][$name] as $count => $value) {
1219 $rows["move_location_{$name}_$count"]['other'] = $value;
1220 $rows["move_location_{$name}_$count"]['main'] = CRM_Utils_Array::value($count, $locLabel['main'][$name]);
1221
1222 // CRM-17556 Set up JS lookup of 'main' contact's value by type
1223 $js = NULL;
1224 if (!empty($mainLocBlock)) {
1225 $js = array('onChange' => "mergeBlock('$name', this, $count, 'typeTypeId' );");
1226 }
1227
1228 // Select box for type/provider
1229 switch ($name) {
1230
1231 case 'im':
1232 $locTypeId = $locTypes['other'][$name][$count];
1233 $typeTypeId = $typeTypes['other'][$name][$count];
1234 // make sure default type type is always on top
1235 $mainTypeTypeId = CRM_Utils_Array::value($count, $typeTypes['main'][$name], $typeTypeId);
1236 $typeTypeValues = $allProviderTypes;
1237 $defaultTypeType = array($mainTypeTypeId => $typeTypeValues[$mainTypeTypeId]);
1238 unset($typeTypeValues[$mainTypeTypeId]);
1239 $elements[] = array(
1240 'select',
1241 "type[$name][$count][typeTypeId]",
1242 NULL,
1243 $defaultTypeType + $typeTypeValues,
1244 $js,
1245 );
1246 $migrationInfo['type'][$name][$count]['typeTypeId'] = $typeTypeId;
1247 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3:%4',
1248 array(
1249 1 => $block,
1250 2 => $count,
1251 3 => $allLocationTypes[$locTypeId],
1252 4 => $allProviderTypes[$typeTypeId],
1253 )
1254 );
1255 break;
1256
1257 case 'phone':
1258 $locTypeId = $locTypes['other'][$name][$count];
1259 $typeTypeId = $typeTypes['other'][$name][$count];
1260 // make sure default type type is always on top
1261 $mainTypeTypeId = CRM_Utils_Array::value($count, $typeTypes['main'][$name], $typeTypeId);
1262 $typeTypeValues = $allPhoneTypes;
1263 $defaultTypeType = array($mainTypeTypeId => $typeTypeValues[$mainTypeTypeId]);
1264 unset($typeTypeValues[$mainTypeTypeId]);
1265 $elements[] = array(
1266 'select',
1267 "type[$name][$count][typeTypeId]",
1268 NULL,
1269 $defaultTypeType + $typeTypeValues,
1270 $js,
1271 );
1272 $migrationInfo['type'][$name][$count]['typeTypeId'] = $typeTypeId;
1273 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3:%4',
1274 array(
1275 1 => $block,
1276 2 => $count,
1277 3 => $allLocationTypes[$locTypeId],
1278 4 => $allPhoneTypes[$typeTypeId],
1279 )
1280 );
1281 break;
1282
1283 case 'website':
1284 $typeTypeId = $typeTypes['other'][$name][$count];
1285 // make sure default type type is always on top
1286 $mainTypeTypeId = CRM_Utils_Array::value($count, $typeTypes['main'][$name], $typeTypeId);
1287 $typeTypeValues = $allWebsiteTypes;
1288 $defaultTypeType = array($mainTypeTypeId => $typeTypeValues[$mainTypeTypeId]);
1289 unset($typeTypeValues[$mainTypeTypeId]);
1290 $elements[] = array(
1291 'select',
1292 "type[$name][$count][typeTypeId]",
1293 NULL,
1294 $defaultTypeType + $typeTypeValues,
1295 $js,
1296 );
1297 $migrationInfo['type'][$name][$count]['typeTypeId'] = $typeTypeId;
1298 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
1299 array(
1300 1 => $block,
1301 2 => $count,
1302 3 => $allWebsiteTypes[$typeTypeId],
1303 )
1304 );
1305 break;
1306
1307 default:
1308 $locTypeId = $locTypes['other'][$name][$count];
1309 $rows["move_location_{$name}_$count"]['title'] = ts('%1:%2:%3',
1310 array(
1311 1 => $block,
1312 2 => $count,
1313 3 => $allLocationTypes[$locTypeId],
1314 )
1315 );
1316 }
1317
1318 // CRM-17556 Set up JS lookup of 'main' contact's value by location
1319 $js = NULL;
1320 if (!empty($mainLocBlock)) {
1321 $js = array('onChange' => "mergeBlock('$name', this, $count, 'locTypeId' );");
1322 }
1323
1324 // Add checkbox to migrate data from 'other' to 'main'
1325 $elements[] = array('advcheckbox', "move_location_{$name}_{$count}");
1326
1327 // Add location select list for location block (websites don't have a location)
1328 if ($name != 'website') {
1329 $migrationInfo["move_location_{$name}_{$count}"] = 1;
1330 // make sure default location type is always on top
1331 $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId);
1332 $locTypeValues = $allLocationTypes;
1333 $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]);
1334 unset($locTypeValues[$mainLocTypeId]);
1335 // keep 1-1 mapping for address - location type.
1336 $elements[] = array(
1337 'select',
1338 "location[$name][$count][locTypeId]",
1339 NULL,
1340 $defaultLocType + $locTypeValues,
1341 $js,
1342 );
1343 // keep location-type-id same as that of other-contact
1344 $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId;
1345 if ($name != 'address') {
1346 $elements[] = array('advcheckbox', "location[{$name}][$count][operation]", NULL, ts('add new'));
1347 // always use add operation
1348 $migrationInfo['location'][$name][$count]['operation'] = 1;
1349 }
1350 }
1351
1352 }
1353 }
1354
1355 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1356 $config = CRM_Core_Config::singleton();
1357 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1358 $mainUser = NULL;
1359 if ($mainUfId) {
1360 // d6 compatible
1361 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1362 $mainUser = user_load($mainUfId);
1363 }
1364 elseif ($config->userFramework == 'Joomla') {
1365 $mainUser = JFactory::getUser($mainUfId);
1366 }
1367 }
1368 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1369 $otherUser = NULL;
1370 if ($otherUfId) {
1371 // d6 compatible
1372 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1373 $otherUser = user_load($otherUfId);
1374 }
1375 elseif ($config->userFramework == 'Joomla') {
1376 $otherUser = JFactory::getUser($otherUfId);
1377 }
1378 }
1379
1380 $relTables = CRM_Dedupe_Merger::relTables();
1381 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1382 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1383 foreach ($relTables as $name => $null) {
1384 if (!in_array($name, $activeRelTables) &&
1385 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1386 ) {
1387 unset($relTables[$name]);
1388 continue;
1389 }
1390
1391 $relTableElements[] = array('checkbox', "move_$name");
1392 $migrationInfo["move_$name"] = 1;
1393
1394 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1395 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1396 if ($name == 'rel_table_users') {
1397 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1398 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1399 $find = array('$ufid', '$ufname');
1400 if ($mainUser) {
1401 $replace = array($mainUfId, $mainUser->name);
1402 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1403 }
1404 if ($otherUser) {
1405 $replace = array($otherUfId, $otherUser->name);
1406 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1407 }
1408 }
1409 if ($name == 'rel_table_memberships') {
1410 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1411 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1412 }
1413 }
1414 foreach ($relTables as $name => $null) {
1415 $relTables["move_$name"] = $relTables[$name];
1416 unset($relTables[$name]);
1417 }
1418
1419 // handle custom fields
1420 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1,
1421 CRM_Utils_Array::value('contact_sub_type', $main)
1422 );
1423 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1,
1424 CRM_Utils_Array::value('contact_sub_type', $other)
1425 );
1426 CRM_Core_DAO::freeResult();
1427
1428 foreach ($otherTree as $gid => $group) {
1429 $foundField = FALSE;
1430 if (!isset($group['fields'])) {
1431 continue;
1432 }
1433
1434 foreach ($group['fields'] as $fid => $field) {
1435 if (in_array($fid, $compareFields['custom'])) {
1436 if (!$foundField) {
1437 $rows["custom_group_$gid"]['title'] = $group['title'];
1438 $foundField = TRUE;
1439 }
1440 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1441 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1442 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1443 $field, TRUE
1444 );
1445 }
1446 }
1447 $value = "null";
1448 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1449 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1450 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1451 $field, TRUE
1452 );
1453 if ($values['data'] === 0 || $values['data'] === '0') {
1454 $values['data'] = $qfZeroBug;
1455 }
1456 $value = ($values['data']) ? $values['data'] : $value;
1457 }
1458 }
1459 $rows["move_custom_$fid"]['title'] = $field['label'];
1460
1461 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1462 $migrationInfo["move_custom_$fid"] = $value;
1463 }
1464 }
1465 }
1466 $result = array(
1467 'rows' => $rows,
1468 'elements' => $elements,
1469 'rel_table_elements' => $relTableElements,
1470 'main_loc_block' => $mainLocBlock,
1471 'rel_tables' => $relTables,
1472 'main_details' => $main,
1473 'other_details' => $other,
1474 'migration_info' => $migrationInfo,
1475 );
1476
1477 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
1478 $result['main_details']['other_type_block_ids'] = $typeBlockIds['main'];
1479 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
1480 $result['other_details']['other_type_block_ids'] = $typeBlockIds['other'];
1481
1482 return $result;
1483 }
1484
1485 /**
1486 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1487 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1488 * A superset of moveContactBelongings() function.
1489 *
1490 * @todo
1491 * Websites do not have a location type. This needs to be supported:
1492 * Add move_type_website_1, etc.
1493 *
1494 * @param int $mainId
1495 * Main contact with whom merge has to happen.
1496 * @param int $otherId
1497 * Duplicate contact which would be deleted after merge operation.
1498 *
1499 * @param $migrationInfo
1500 *
1501 * @return bool
1502 */
1503 public static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
1504 if (empty($migrationInfo)) {
1505 return FALSE;
1506 }
1507
1508 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1509 $relTables = CRM_Dedupe_Merger::relTables();
1510 $moveTables = $locBlocks = $tableOperations = array();
1511 foreach ($migrationInfo as $key => $value) {
1512 if ($value == $qfZeroBug) {
1513 $value = '0';
1514 }
1515 if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) ||
1516 substr($key, 0, 12) == 'move_custom_') &&
1517 $value != NULL
1518 ) {
1519 $submitted[substr($key, 5)] = $value;
1520 }
1521 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1522 $locField = explode('_', $key);
1523 $fieldName = $locField[2];
1524 $fieldCount = $locField[3];
1525 // Ignore operation for websites
1526 $operation = 0;
1527 if ($fieldName != 'website') {
1528 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
1529 }
1530 // default operation is overwrite.
1531 if (!$operation) {
1532 $operation = 2;
1533 }
1534 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1535
1536 // Ignore 'locTypeId' for websites
1537 if ($fieldName != 'website') {
1538 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
1539 }
1540 }
1541 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1542 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1543 if (array_key_exists('operation', $migrationInfo)) {
1544 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1545 if (array_key_exists($key, $migrationInfo['operation'])) {
1546 $tableOperations[$table] = $migrationInfo['operation'][$key];
1547 }
1548 }
1549 }
1550 }
1551 }
1552
1553 // **** Do location related migration.
1554 // @todo Handle OpenID (not currently in API).
1555 if (!empty($locBlocks)) {
1556
1557 $locationBlocks = array(
1558 'address' => 'Address',
1559 'email' => 'Email',
1560 'im' => 'IM',
1561 'phone' => 'Phone',
1562 'website' => 'Website',
1563 );
1564
1565 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
1566 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
1567
1568 foreach ($locBlocks as $name => $block) {
1569 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1570 continue;
1571 }
1572 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name];
1573 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1574 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1575
1576 foreach ($block as $blkCount => $values) {
1577 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
1578 $operation = CRM_Utils_Array::value('operation', $values, 2);
1579 $otherBlockId = CRM_Utils_Array::value($blkCount, $migrationInfo['other_details']['loc_block_ids'][$name]);
1580
1581 // keep 1-1 mapping for address - loc type.
1582 $idKey = $blkCount;
1583 if (
1584 $name != 'website'
1585 && array_key_exists($name, $locationBlocks)
1586 ) {
1587 $idKey = $locTypeId;
1588 }
1589
1590 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
1591 $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
1592 }
1593
1594 if (!$otherBlockId) {
1595 continue;
1596 }
1597
1598 // for the block which belongs to other-contact, link the location block to main-contact
1599 $otherBlockDAO = new $daoName();
1600 $otherBlockDAO->id = $otherBlockId;
1601 $otherBlockDAO->contact_id = $mainId;
1602 $otherBlockDAO->location_type_id = $locTypeId;
1603
1604 // Get typeTypeIDs for fields that have them
1605 if ($name == 'im') {
1606 $typeTypeId = $migrationInfo['type'][$name][$idKey]['typeTypeId'];
1607 $otherBlockDAO->provider_id = $typeTypeId;
1608 }
1609 elseif ($name == 'phone') {
1610 $typeTypeId = $migrationInfo['type'][$name][$idKey]['typeTypeId'];
1611 $otherBlockDAO->phone_type_id = $typeTypeId;
1612 }
1613 elseif ($name == 'website') {
1614 $typeTypeId = $migrationInfo['type'][$name][$idKey]['typeTypeId'];
1615 $otherBlockDAO->website_type_id = $typeTypeId;
1616 // No location ID, more special handling
1617 $otherBlockDAO->location_type_id = NULL;
1618 $mainBlockId = CRM_Utils_Array::value($typeTypeId, $migrationInfo['main_details']['other_type_block_ids'][$name]);
1619 }
1620
1621 // if main contact already has primary & billing, set the flags to 0.
1622 if ($primaryDAOId) {
1623 $otherBlockDAO->is_primary = 0;
1624 }
1625 if ($billingDAOId) {
1626 $otherBlockDAO->is_billing = 0;
1627 }
1628
1629 // overwrite - need to delete block which belongs to main-contact.
1630 if (isset($mainBlockId) && $mainBlockId && ($operation == 2)) {
1631 $deleteDAO = new $daoName();
1632 $deleteDAO->id = $mainBlockId;
1633 $deleteDAO->find(TRUE);
1634
1635 // if we about to delete a primary / billing block, set the flags for new block
1636 // that we going to assign to main-contact
1637 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1638 $otherBlockDAO->is_primary = 1;
1639 }
1640 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1641 $otherBlockDAO->is_billing = 1;
1642 }
1643
1644 $deleteDAO->delete();
1645 $deleteDAO->free();
1646 }
1647
1648 $otherBlockDAO->update();
1649 $otherBlockDAO->free();
1650 }
1651 }
1652 }
1653
1654 // **** Do tables related migrations
1655 if (!empty($moveTables)) {
1656 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1657 unset($moveTables, $tableOperations);
1658 }
1659
1660 // **** Do contact related migrations
1661 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
1662
1663 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1664 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1665 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1666 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
1667 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
1668 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1669 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1670 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1671 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1672
1673 // fix custom fields so they're edible by createProfileContact()
1674 static $treeCache = array();
1675 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1676 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'],
1677 CRM_Core_DAO::$_nullObject, NULL, -1
1678 );
1679 }
1680 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1681
1682 $cFields = array();
1683 foreach ($cgTree as $key => $group) {
1684 if (!isset($group['fields'])) {
1685 continue;
1686 }
1687 foreach ($group['fields'] as $fid => $field) {
1688 $cFields[$fid]['attributes'] = $field;
1689 }
1690 }
1691
1692 if (!isset($submitted)) {
1693 $submitted = array();
1694 }
1695 foreach ($submitted as $key => $value) {
1696 if (substr($key, 0, 7) == 'custom_') {
1697 $fid = (int) substr($key, 7);
1698 if (empty($cFields[$fid])) {
1699 continue;
1700 }
1701 $htmlType = $cFields[$fid]['attributes']['html_type'];
1702 switch ($htmlType) {
1703 case 'File':
1704 $customFiles[] = $fid;
1705 unset($submitted["custom_$fid"]);
1706 break;
1707
1708 case 'Select Country':
1709 case 'Select State/Province':
1710 $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
1711 break;
1712
1713 case 'CheckBox':
1714 case 'AdvMulti-Select':
1715 case 'Multi-Select':
1716 case 'Multi-Select Country':
1717 case 'Multi-Select State/Province':
1718 // Merge values from both contacts for multivalue fields, CRM-4385
1719 // get the existing custom values from db.
1720 $customParams = array('entityID' => $mainId, $key => TRUE);
1721 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
1722 if (!empty($customfieldValues[$key])) {
1723 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1724 if (is_array($existingValue) && !empty($existingValue)) {
1725 $mergeValue = $submmtedCustomValue = array();
1726 if ($value) {
1727 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1728 }
1729
1730 //hack to remove null and duplicate values from array.
1731 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1732 if ($v != '' && !in_array($v, $mergeValue)) {
1733 $mergeValue[] = $v;
1734 }
1735 }
1736
1737 //keep state and country as array format.
1738 //for checkbox and m-select format w/ VALUE_SEPARATOR
1739 if (in_array($htmlType, array(
1740 'CheckBox',
1741 'Multi-Select',
1742 'AdvMulti-Select',
1743 ))) {
1744 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
1745 $mergeValue
1746 ) . CRM_Core_DAO::VALUE_SEPARATOR;
1747 }
1748 else {
1749 $submitted[$key] = $mergeValue;
1750 }
1751 }
1752 }
1753 elseif (in_array($htmlType, array(
1754 'Multi-Select Country',
1755 'Multi-Select State/Province',
1756 ))) {
1757 //we require submitted values should be in array format
1758 if ($value) {
1759 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1760 //hack to remove null values from array.
1761 $mergeValue = array();
1762 foreach ($mergeValueArray as $k => $v) {
1763 if ($v != '') {
1764 $mergeValue[] = $v;
1765 }
1766 }
1767 $submitted[$key] = $mergeValue;
1768 }
1769 }
1770 break;
1771
1772 default:
1773 break;
1774 }
1775 }
1776 }
1777
1778 // **** Do file custom fields related migrations
1779 // FIXME: move this someplace else (one of the BAOs) after discussing
1780 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
1781 // like, delete a file...
1782
1783 if (!isset($customFiles)) {
1784 $customFiles = array();
1785 }
1786 foreach ($customFiles as $customId) {
1787 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1788
1789 // get the contact_id -> file_id mapping
1790 $fileIds = array();
1791 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
1792 $dao = CRM_Core_DAO::executeQuery($sql);
1793 while ($dao->fetch()) {
1794 $fileIds[$dao->entity_id] = $dao->file_id;
1795 }
1796 $dao->free();
1797
1798 // delete the main contact's file
1799 if (!empty($fileIds[$mainId])) {
1800 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
1801 }
1802
1803 // move the other contact's file to main contact
1804 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
1805 if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
1806 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
1807 }
1808 else {
1809 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1810 }
1811 CRM_Core_DAO::executeQuery($sql);
1812
1813 if (CRM_Core_DAO::singleValueQuery("
1814 SELECT id
1815 FROM civicrm_entity_file
1816 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1817 ) {
1818 $sql = "
1819 UPDATE civicrm_entity_file
1820 SET entity_id = {$mainId}
1821 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1822 }
1823 else {
1824 $sql = "
1825 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1826 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1827 }
1828 CRM_Core_DAO::executeQuery($sql);
1829 }
1830
1831 // move view only custom fields CRM-5362
1832 $viewOnlyCustomFields = array();
1833 foreach ($submitted as $key => $value) {
1834 $fid = (int) substr($key, 7);
1835 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
1836 $viewOnlyCustomFields[$key] = $value;
1837 }
1838 }
1839
1840 // special case to set values for view only, CRM-5362
1841 if (!empty($viewOnlyCustomFields)) {
1842 $viewOnlyCustomFields['entityID'] = $mainId;
1843 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1844 }
1845
1846 // **** Delete other contact & update prev-next caching
1847 $otherParams = array(
1848 'contact_id' => $otherId,
1849 'id' => $otherId,
1850 'version' => 3,
1851 );
1852 if (CRM_Core_Permission::check('merge duplicate contacts') &&
1853 CRM_Core_Permission::check('delete contacts')
1854 ) {
1855 // if ext id is submitted then set it null for contact to be deleted
1856 if (!empty($submitted['external_identifier'])) {
1857 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1858 CRM_Core_DAO::executeQuery($query);
1859 }
1860
1861 civicrm_api('contact', 'delete', $otherParams);
1862 CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
1863 }
1864 // FIXME: else part
1865 /* else { */
1866
1867 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1868
1869 /* } */
1870
1871 // CRM-15681 merge sub_types
1872 if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
1873 if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
1874 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1875 }
1876 else {
1877 $submitted['contact_sub_type'] = $other_sub_types;
1878 }
1879 }
1880
1881 // **** Update contact related info for the main contact
1882 if (!empty($submitted)) {
1883 $submitted['contact_id'] = $mainId;
1884
1885 //update current employer field
1886 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1887 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1888 $submitted['current_employer'] = $submitted['current_employer_id'];
1889 }
1890 else {
1891 $submitted['current_employer'] = '';
1892 }
1893 unset($submitted['current_employer_id']);
1894 }
1895
1896 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1897 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1898 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1899 }
1900 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1901 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1902 }
1903
1904 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
1905 unset($submitted);
1906 }
1907
1908 CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
1909
1910 return TRUE;
1911 }
1912
1913 /**
1914 * @return array
1915 * Array of field names which will be compared, so everything except ID.
1916 */
1917 public static function getContactFields() {
1918 $contactFields = CRM_Contact_DAO_Contact::fields();
1919 $invalidFields = array(
1920 'api_key',
1921 'contact_is_deleted',
1922 'created_date',
1923 'display_name',
1924 'hash',
1925 'id',
1926 'modified_date',
1927 'primary_contact_id',
1928 'sort_name',
1929 'user_unique_id',
1930 );
1931 foreach ($contactFields as $field => $value) {
1932 if (in_array($field, $invalidFields)) {
1933 unset($contactFields[$field]);
1934 }
1935 }
1936 return array_keys($contactFields);
1937 }
1938
1939 /**
1940 * Added for CRM-12695
1941 * Based on the contactID provided
1942 * add/update membership(s) to related contacts
1943 *
1944 * @param int $contactID
1945 */
1946 public static function addMembershipToRealtedContacts($contactID) {
1947 $dao = new CRM_Member_DAO_Membership();
1948 $dao->contact_id = $contactID;
1949 $dao->is_test = 0;
1950 $dao->find();
1951
1952 //checks membership of contact itself
1953 while ($dao->fetch()) {
1954 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1955 if ($relationshipTypeId) {
1956 $membershipParams = array(
1957 'id' => $dao->id,
1958 'contact_id' => $dao->contact_id,
1959 'membership_type_id' => $dao->membership_type_id,
1960 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1961 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1962 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1963 'source' => $dao->source,
1964 'status_id' => $dao->status_id,
1965 );
1966 // create/update membership(s) for related contact(s)
1967 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1968 } // end of if relationshipTypeId
1969 }
1970 }
1971
1972 }