Fix for list of main location blocks, for use in JS
[civicrm-core.git] / CRM / Dedupe / Merger.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
32 */
33class CRM_Dedupe_Merger {
6a488035 34
e0ef6999 35 /**
4f1f1f2a
CW
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
e0ef6999
EM
39 * @return array
40 */
00be9182 41 public static function relTables() {
6a488035
TO
42 static $relTables;
43
12d73bba 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
6a488035
TO
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') {
b8feed6e 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';
6a488035
TO
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'),
91da6cd5 89 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
6a488035
TO
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
76c53278
CW
154 $relTables += self::getMultiValueCustomSets('relTables');
155
6a488035
TO
156 // Allow hook_civicrm_merge() to adjust $relTables
157 CRM_Utils_Hook::merge('relTables', $relTables);
158 }
159 return $relTables;
160 }
161
162 /**
fe482240 163 * Returns the related tables groups for which a contact has any info entered.
ad37ac8e 164 *
165 * @param int $cid
166 *
167 * @return array
6a488035 168 */
00be9182 169 public static function getActiveRelTables($cid) {
6a488035
TO
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 /**
e4f8c98c 200 * Return tables and their fields referencing civicrm_contact.contact_id explicitly
6a488035 201 */
00be9182 202 public static function cidRefs() {
6a488035
TO
203 static $cidRefs;
204 if (!$cidRefs) {
e4f8c98c 205 $sql = "
206SELECT
207 table_name,
208 column_name
209FROM information_schema.key_column_usage
210WHERE
211 referenced_table_schema = database() AND
212 referenced_table_name = 'civicrm_contact' AND
213 referenced_column_name = 'id';
214 ";
6a488035
TO
215 $dao = CRM_Core_DAO::executeQuery($sql);
216 while ($dao->fetch()) {
217 $cidRefs[$dao->table_name][] = $dao->column_name;
218 }
64b3569d 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';
6a488035
TO
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 */
00be9182 233 public static function eidRefs() {
6a488035
TO
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'),
6a488035
TO
245 );
246
247 // Allow hook_civicrm_merge() to adjust $eidRefs
248 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
249 }
250 return $eidRefs;
251 }
252
9da04f20 253 /**
fe482240 254 * Return tables using locations.
9da04f20 255 */
00be9182 256 public static function locTables() {
9da04f20
AS
257 static $locTables;
258 if (!$locTables) {
481a74f4 259 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
9da04f20
AS
260
261 // Allow hook_civicrm_merge() to adjust $locTables
262 CRM_Utils_Hook::merge('locTables', $locTables);
263 }
264 return $locTables;
265 }
266
76c53278
CW
267 /**
268 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
98997235
TO
269 * @param string $request
270 * 'relTables' or 'cidRefs'.
76c53278
CW
271 * @see CRM-13836
272 */
00be9182 273 public static function getMultiValueCustomSets($request) {
76c53278
CW
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 ));
22e263ad 285 foreach ($result['values'] as $custom) {
76c53278
CW
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
6a488035
TO
298 /**
299 * Tables which require custom processing should declare functions to call here.
300 * Doing so will override normal processing.
301 */
00be9182 302 public static function cpTables() {
6a488035
TO
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 /**
100fef9d 317 * Return payment related table.
6a488035 318 */
00be9182 319 public static function paymentTables() {
6a488035
TO
320 static $tables;
321 if (!$tables) {
322 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
323 }
6a488035
TO
324 return $tables;
325 }
326
327 /**
100fef9d 328 * Return payment update Query.
54957108 329 *
330 * @param string $tableName
331 * @param int $mainContactId
332 * @param int $otherContactId
333 *
334 * @return array
6a488035 335 */
00be9182 336 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
6a488035
TO
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
351INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
352INNER 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
360INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
361INNER 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
369INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
370INNER 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
e0ef6999 379 /**
100fef9d
CW
380 * @param int $mainId
381 * @param int $otherId
382 * @param string $tableName
e0ef6999
EM
383 * @param array $tableOperations
384 * @param string $mode
385 *
386 * @return array
387 */
00be9182 388 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
6a488035
TO
389 $sqls = array();
390 if (!$tableName || !$mainId || !$otherId) {
391 return $sqls;
392 }
393
6a488035
TO
394 switch ($tableName) {
395 case 'civicrm_membership':
d58a19a1
TO
396 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
397 break;
398 }
399 if ($mode == 'add') {
400 $sqls[] = "
6a488035
TO
401DELETE 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} ";
d58a19a1
TO
405 }
406 if ($mode == 'payment') {
407 $sqls[] = "
6a488035
TO
408DELETE contribution.* FROM civicrm_contribution contribution
409INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
410INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
411 AND membership1.contact_id = {$mainId}
412INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
413 AND membership2.contact_id = {$otherId}";
d58a19a1
TO
414 }
415 break;
6a488035
TO
416
417 case 'civicrm_uf_match':
418 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
b44e3f84 419 // failing to meet intended result. Therefore we introduce this additional query:
6a488035
TO
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 *
54957108 431 * @param int $mainId
432 * @param int $otherId
433 * @param bool $tables
434 * @param array $tableOperations
6a488035 435 */
00be9182 436 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
6a488035
TO
437 $cidRefs = self::cidRefs();
438 $eidRefs = self::eidRefs();
439 $cpTables = self::cpTables();
440 $paymentTables = self::paymentTables();
ada104d5 441 $membershipMerge = FALSE; // CRM-12695
6a488035
TO
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()
9da04f20 450 // also don't affect tables in locTables() CRM-15658
6a488035 451 $relTables = self::relTables();
9da04f20 452 $handled = self::locTables();
6a488035
TO
453 foreach ($relTables as $params) {
454 $handled = array_merge($handled, $params['tables']);
455 }
456 $affected = array_diff($affected, $handled);
ada104d5
AW
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 }
6a488035
TO
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 }
b3fdbf3d 487
6a488035
TO
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)) {
6a488035
TO
494 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
495 $sqls = array_merge($sqls, $paymentSqls);
71560cf3
C
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 }
6a488035
TO
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 }
ada104d5
AW
526 // CRM-12695
527 if ($membershipMerge) {
528 // call to function adding membership to related contacts
529 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
530 }
6a488035
TO
531 $transaction->commit();
532 }
533
534 /**
4eea8606 535 * Load all non-empty fields for the contacts
b3fdbf3d 536 *
98997235
TO
537 * @param array $main
538 * Contact details.
539 * @param array $other
540 * Contact details.
6a488035 541 *
77b97be7 542 * @return array
6a488035 543 */
4eea8606 544 public static function retrieveFields($main, $other) {
6a488035
TO
545 $result = array(
546 'contact' => array(),
547 'custom' => array(),
548 );
16254ae1 549 foreach (self::getContactFields() as $validField) {
eb61dc07
J
550 // CRM-17556 Get all non-empty fields, to make comparison easier
551 if (!empty($main[$validField]) || !empty($other[$validField])) {
6a488035
TO
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) {
76c53278
CW
560 // Exclude multi-value fields CRM-13836
561 if (strpos($key, '_')) {
562 continue;
563 }
6a488035
TO
564 $key1 = CRM_Utils_Array::value($key, $mainEvs);
565 $key2 = CRM_Utils_Array::value($key, $otherEvs);
eb61dc07 566 // CRM-17556 Get all non-empty fields, to make comparison easier
08ef1f91 567 if (!empty($key1) || !empty($key2)) {
6a488035
TO
568 $result['custom'][] = $key;
569 }
570 }
571 return $result;
572 }
573
574 /**
100fef9d 575 * Batch merge a set of contacts based on rule-group and group.
6a488035 576 *
98997235
TO
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.
6a488035
TO
583 * A 'safe' value skips the merge if there are any un-resolved conflicts.
584 * Does a force merge otherwise.
c301f76e 585 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
98997235 586 * Wether to let api decide which contact to retain and which to delete.
f931b74c 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.
6a488035 589 *
77b97be7 590 * @return array|bool
6a488035 591 */
63ef778e 592 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $batchLimit = 1, $isSelected = 2) {
6a488035
TO
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
63ef778e 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;
6a488035
TO
607
608 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where);
63ef778e 609 if (empty($dupePairs) && !$redirectForPerformance && $isSelected == 2) {
6a488035
TO
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
f931b74c 624 public static function updateMergeStats($cacheKeyString, $result = array()) {
63ef778e 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
f931b74c 659 public static function resetMergeStats($cacheKeyString) {
63ef778e 660 return CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
661 }
662
f931b74c 663 public static function getMergeStats($cacheKeyString) {
63ef778e 664 $stats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
665 if (!empty($stats)) {
666 $stats = $stats[0];
667 }
668 return $stats;
669 }
670
f931b74c 671 public static function getMergeStatsMsg($cacheKeyString) {
63ef778e 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
6a488035 683 /**
100fef9d 684 * Merge given set of contacts. Performs core operation.
6a488035 685 *
98997235
TO
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.
6a488035 690 * Generally used with batch-merge.
98997235
TO
691 * @param string $mode
692 * Helps decide how to behave when there are conflicts.
6a488035
TO
693 * A 'safe' value skips the merge if there are any un-resolved conflicts.
694 * Does a force merge otherwise (aggressive mode).
c301f76e 695 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
98997235 696 * Wether to let api decide which contact to retain and which to delete.
6a488035
TO
697 *
698 *
77b97be7
EM
699 * @param bool $redirectForPerformance
700 *
701 * @return array|bool
6a488035 702 */
00be9182 703 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
353ffa53 704 $autoFlip = TRUE, $redirectForPerformance = FALSE
6a488035
TO
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) {
1cf05c3e 716 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
6a488035
TO
717 $mainId = $dupes['dstID'];
718 $otherId = $dupes['srcID'];
602789b5
DS
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)) {
6a488035
TO
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.
721248d4 732 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId);
6a488035
TO
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
63ef778e 743 $conflicts = array();
744 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
6a488035 745 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo);
c940014d 746 $resultStats['merged'][] = array('main_id' => $mainId, 'other_id' => $otherId);
6a488035
TO
747 }
748 else {
c940014d 749 $resultStats['skipped'][] = array('main_id' => $mainId, 'other_id' => $otherId);
6a488035
TO
750 }
751
0971143c 752 // store any conflicts
63ef778e 753 if (!empty($conflicts)) {
fd630ef9 754 foreach ($conflicts as $key => $dnc) {
755 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
756 }
63ef778e 757 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
f931b74c 758 }
759 else {
63ef778e 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 }
6a488035
TO
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 }
63ef778e 781
782 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
6a488035
TO
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 *
98997235
TO
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.
13919cf8
J
798 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
799 * - Does a force merge otherwise (aggressive mode).
6a488035 800 *
ad37ac8e 801 * @param array $conflicts
802 *
77b97be7 803 * @return bool
6a488035 804 */
63ef778e 805 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
0971143c 806
6a488035
TO
807 $migrationData = array(
808 'old_migration_info' => $migrationInfo,
809 'mode' => $mode,
810 );
eb61dc07 811
b2b0530a 812 $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
813
814 foreach ($migrationInfo as $key => $val) {
815 if ($val === "null") {
0971143c 816 // Rule: Never overwrite with an empty value (in any mode)
6a488035
TO
817 unset($migrationInfo[$key]);
818 continue;
819 }
16254ae1 820 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
6a488035 821 substr($key, 0, 12) == 'move_custom_'
353ffa53
TO
822 ) and $val != NULL
823 ) {
0971143c
J
824 // Rule: If both main-contact, and other-contact have a field with a
825 // different value, then let $mode decide if to merge it or not
4eea8606
J
826 if (
827 !empty($migrationInfo['rows'][$key]['main'])
828 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
829 ) {
fd630ef9 830
831 // note it down & lets wait for response from the hook.
832 // For no response $mode will decide if to skip this merge
833 $conflicts[$key] = NULL;
6a488035
TO
834 }
835 }
836 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
837 $locField = explode('_', $key);
838 $fieldName = $locField[2];
839 $fieldCount = $locField[3];
840
53e45f60 841 // Rule: resolve address conflict if any
6a488035 842 if ($fieldName == 'address') {
abb422f9 843 $mainNewLocTypeId = $migrationInfo['location_blocks'][$fieldName][$fieldCount]['locTypeId'];
d342c43c 844 if (!empty($migrationInfo['main_loc_block']) &&
53e45f60 845 array_key_exists("main_address_{$mainNewLocTypeId}", $migrationInfo['main_loc_block'])) {
6a488035 846 // main loc already has some address for the loc-type. Its a overwrite situation.
6a488035
TO
847 // look for next available loc-type
848 $newTypeId = NULL;
849 foreach ($allLocationTypes as $typeId => $typeLabel) {
53e45f60 850 if (!array_key_exists("main_address_{$typeId}", $migrationInfo['main_loc_block'])) {
6a488035
TO
851 $newTypeId = $typeId;
852 }
853 }
854 if ($newTypeId) {
855 // try insert address at new available loc-type
abb422f9 856 $migrationInfo['location_blocks'][$fieldName][$fieldCount]['locTypeId'] = $newTypeId;
6a488035 857 }
fd630ef9 858 else {
6a488035 859 // note it down & lets wait for response from the hook.
fd630ef9 860 // For no response $mode will decide if to skip this merge
6a488035
TO
861 $conflicts[$key] = NULL;
862 }
6a488035
TO
863 }
864 }
865 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
866 // for loc blocks other than address like email, phone .. if values are same no point in merging
867 // and adding redundant value
868 unset($migrationInfo[$key]);
869 }
870 }
871 }
872
873 // A hook to implement other algorithms for choosing which contact to bias to when
874 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
875 // merge happens with new values filled in here. For a particular field / row not to be merged
876 // field should be unset from fields_in_conflict.
877 $migrationData['fields_in_conflict'] = $conflicts;
fd630ef9 878 $migrationData['merge_mode'] = $mode;
6a488035
TO
879 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
880 $conflicts = $migrationData['fields_in_conflict'];
63ef778e 881 // allow hook to override / manipulate migrationInfo as well
882 $migrationInfo = $migrationData['old_migration_info'];
6a488035
TO
883
884 if (!empty($conflicts)) {
885 foreach ($conflicts as $key => $val) {
886 if ($val === NULL and $mode == 'safe') {
63ef778e 887 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
6a488035
TO
888 return TRUE;
889 }
890 else {
891 // copy over the resolved values
892 $migrationInfo[$key] = $val;
893 }
894 }
fd630ef9 895 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
896 if (array_key_exists('skip_merge', $migrationData)) {
897 return (bool) $migrationData['skip_merge'];
898 }
6a488035
TO
899 }
900 return FALSE;
901 }
902
903 /**
904 * A function to build an array of information required by merge function and the merge UI.
905 *
98997235
TO
906 * @param int $mainId
907 * Main contact with whom merge has to happen.
908 * @param int $otherId
909 * Duplicate contact which would be deleted after merge operation.
6a488035 910 *
77b97be7 911 * @return array|bool|int
53e45f60 912 * 'main_loc_block' => Stores all location blocks associated with the 'main' contact
6a488035 913 */
00be9182 914 public static function getRowsElementsAndInfo($mainId, $otherId) {
6a488035 915 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
53e45f60 916
087f00ec
J
917 $listOptions = array(
918 'location_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'),
919 'phone_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'),
920 'provider_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'),
921 'website_type_id' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'),
922 'gender_id' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
923 );
65a35632 924
6a488035
TO
925 // Fetch contacts
926 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
353ffa53
TO
927 $params = array(
928 'contact_id' => $cid,
929 'version' => 3,
c301f76e 930 'return' => array_merge(array('display_name'), self::getContactFields()),
353ffa53 931 );
6a488035
TO
932 $result = civicrm_api('contact', 'get', $params);
933
934 if (empty($result['values'][$cid]['contact_type'])) {
935 return FALSE;
936 }
937 $$moniker = $result['values'][$cid];
938 }
939
940 static $fields = array();
941 if (empty($fields)) {
942 $fields = CRM_Contact_DAO_Contact::fields();
943 CRM_Core_DAO::freeResult();
944 }
945
946 // FIXME: there must be a better way
947 foreach (array('main', 'other') as $moniker) {
948 $contact = &$$moniker;
949 $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
950 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
951 $specialValues[$moniker] = array(
952 'preferred_communication_method' => $value,
0e357872 953 'communication_style_id' => $value,
6a488035
TO
954 );
955
9b873358 956 if (!empty($contact['preferred_communication_method'])) {
d58a19a1
TO
957 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
958 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
6a488035
TO
959 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
960 }
961 $names = array(
c301f76e 962 'preferred_communication_method' => array(
963 'newName' => 'preferred_communication_method_display',
964 'groupName' => 'preferred_communication_method',
965 ),
6a488035
TO
966 );
967 CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
a14df814 968
0e357872
C
969 if (!empty($contact['communication_style'])) {
970 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
971 }
6a488035
TO
972 }
973
974 static $optionValueFields = array();
975 if (empty($optionValueFields)) {
976 $optionValueFields = CRM_Core_OptionValue::getFields();
977 }
978 foreach ($optionValueFields as $field => $params) {
979 $fields[$field]['title'] = $params['title'];
980 }
981
4eea8606 982 $compareFields = self::retrieveFields($main, $other);
6a488035
TO
983
984 $rows = $elements = $relTableElements = $migrationInfo = array();
985
4eea8606 986 foreach ($compareFields['contact'] as $field) {
4d5f18cc 987 if ($field == 'contact_sub_type') {
988 // CRM-15681 don't display sub-types in UI
989 continue;
990 }
6a488035
TO
991 foreach (array('main', 'other') as $moniker) {
992 $contact = &$$moniker;
993 $value = CRM_Utils_Array::value($field, $contact);
994 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
995 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
996 }
997 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
a7488080 998 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
6a488035
TO
999 if ($value) {
1000 $value = str_replace('-', '', $value);
1001 $label = CRM_Utils_Date::customFormat($label);
1002 }
1003 else {
1004 $value = "null";
1005 }
1006 }
a7488080 1007 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
6a488035
TO
1008 if ($label === '0') {
1009 $label = ts('[ ]');
1010 }
1011 if ($label === '1') {
1012 $label = ts('[x]');
1013 }
00f3da2e
BS
1014 }
1015 elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
1016 $label = CRM_Utils_Array::value('individual_prefix', $contact);
6a488035
TO
1017 $value = CRM_Utils_Array::value('prefix_id', $contact);
1018 $field = 'prefix_id';
00f3da2e
BS
1019 }
1020 elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
1021 $label = CRM_Utils_Array::value('individual_suffix', $contact);
6a488035
TO
1022 $value = CRM_Utils_Array::value('suffix_id', $contact);
1023 $field = 'suffix_id';
1024 }
4f88c9cf 1025 elseif ($field == 'gender_id' && !empty($value)) {
087f00ec 1026 $label = $listOptions['gender_id'][$value];
4f88c9cf
C
1027 }
1028 elseif ($field == 'current_employer_id' && !empty($value)) {
1029 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
1030 }
6a488035
TO
1031 $rows["move_$field"][$moniker] = $label;
1032 if ($moniker == 'other') {
7154d2a4
BS
1033 //CRM-14334
1034 if ($value === NULL || $value == '') {
6a488035
TO
1035 $value = 'null';
1036 }
1037 if ($value === 0 or $value === '0') {
1038 $value = $qfZeroBug;
1039 }
8cc574cf 1040 if (is_array($value) && empty($value[1])) {
6a488035
TO
1041 $value[1] = NULL;
1042 }
13919cf8
J
1043
1044 // Display a checkbox to migrate, only if the values are different
1045 if ($value != $main[$field]) {
1046 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1047 }
1048
6a488035
TO
1049 $migrationInfo["move_$field"] = $value;
1050 }
1051 }
1052 $rows["move_$field"]['title'] = $fields[$field]['title'];
1053 }
1054
eb61dc07
J
1055 // Handle location blocks.
1056 // @todo OpenID not in API yet, so is not supported here.
65a35632 1057
087f00ec 1058 // Set up useful information about the location blocks
13919cf8 1059 $locationBlocks = array(
087f00ec
J
1060 'address' => array(
1061 'label' => 'Address',
1062 'displayField' => 'display',
1063 'sortString' => 'location_type_id',
1064 'hasLocation' => TRUE,
1065 'hasType' => FALSE,
1066 ),
1067 'email' => array(
1068 'label' => 'Email',
1069 'displayField' => 'email',
1070 'sortString' => 'location_type_id',
1071 'hasLocation' => TRUE,
1072 'hasType' => FALSE,
1073 ),
1074 'im' => array(
1075 'label' => 'IM',
1076 'displayField' => 'name',
1077 'sortString' => 'location_type_id,provider_id',
1078 'hasLocation' => TRUE,
1079 'hasType' => 'provider_id',
1080 ),
1081 'phone' => array(
1082 'label' => 'Phone',
1083 'displayField' => 'phone',
1084 'sortString' => 'location_type_id,phone_type_id',
1085 'hasLocation' => TRUE,
1086 'hasType' => 'phone_type_id',
1087 ),
1088 'website' => array(
1089 'label' => 'Website',
1090 'displayField' => 'url',
1091 'sortString' => 'website_type_id',
1092 'hasLocation' => FALSE,
1093 'hasType' => 'website_type_id',
1094 ),
1095 );
1096
1097 $locations = array(
1098 'main' => array(),
1099 'other' => array(),
13919cf8 1100 );
087f00ec
J
1101 $mainLocBlock = $locBlockIds = array();
1102 $locBlockIds['main'] = $locBlockIds['other'] = array();
1103 $typeBlockIds['main'] = $typeBlockIds['other'] = array();
1104
1105 // @todo This could probably be defined and used earlier
1106 $mergeTargets = array(
1107 'main' => $mainId,
1108 'other' => $otherId,
1109 );
1110
087f00ec 1111 foreach ($locationBlocks as $blockName => $blockInfo) {
6a488035 1112
087f00ec
J
1113 // Collect existing fields from both 'main' and 'other' contacts first
1114 // This allows us to match up location/types when building the table rows
1115 foreach ($mergeTargets as $moniker => $cid) {
6a488035 1116 $cnt = 1;
b932e89e
J
1117 $searchParams = array(
1118 'version' => 3,
1119 'contact_id' => $cid,
087f00ec
J
1120 // CRM-17556 Order by field-specific criteria
1121 'options' => array(
1122 'sort' => $blockInfo['sortString'],
1123 ),
b932e89e 1124 );
b932e89e 1125 $values = civicrm_api($blockName, 'get', $searchParams);
087f00ec
J
1126 if ($values['count']) {
1127 $cnt = 0;
1128 foreach ($values['values'] as $index => $value) {
1129 $locations[$moniker][$blockName][$cnt] = $value;
1130 // Fix address display
eb61dc07 1131 if ($blockName == 'address') {
087f00ec
J
1132 CRM_Core_BAO_Address::fixAddress($value);
1133 $display = CRM_Utils_Address::format($value);
eb61dc07 1134 $locations[$moniker][$blockName][$cnt]['display'] = $display;
6a488035 1135 }
abb422f9
J
1136
1137 // Add any 'main' contact block values to an array for the JS
1138 if ($moniker == 'main') {
1139 if ($blockInfo['hasType']) {
1140 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id'] . "_" . $value[$blockInfo['hasType']] = $value[$blockInfo['displayField']];
1141 }
1142 else {
1143 $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id'] = $value[$blockInfo['displayField']];
1144 }
1145 }
1146
087f00ec 1147 $cnt++;
6a488035
TO
1148 }
1149 }
1150 }
65a35632 1151
087f00ec
J
1152 // Now, build the table rows appropriately, based off the information on
1153 // the 'other' contact
1154 if (!empty($locations['other'])) {
1155 foreach ($locations['other'] as $count => $value) {
65a35632 1156
087f00ec 1157 $displayValue = $value[$blockInfo['displayField']];
65a35632 1158
087f00ec
J
1159 // Add this value to the table rows
1160 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
65a35632 1161
087f00ec
J
1162 // CRM-17556 Only display 'main' contact value if it's the same location + type
1163 // Look it up from main values...
65a35632 1164
087f00ec
J
1165 $lookupLocation = FALSE;
1166 if ($blockInfo['hasLocation']) {
1167 $lookupLocation = $value['location_type_id'];
1168 }
65a35632 1169
087f00ec
J
1170 $lookupType = FALSE;
1171 if ($blockInfo['hasType']) {
1172 $lookupType = $value[$blockInfo['hasType']];
1173 }
65a35632 1174
087f00ec
J
1175 if (!empty($locations['main'][$blockName])) {
1176 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1177 // No location/type, or matching location and type
1178 if (
1179 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
1180 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
1181 ) {
1182 // Set this value against the 'other' contact value
1183 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1184 break;
1185 }
eb61dc07 1186 }
087f00ec 1187 }
65a35632 1188
087f00ec
J
1189 // Add checkbox to migrate data from 'other' to 'main'
1190 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
65a35632 1191
087f00ec
J
1192 // Flag up this field to skipMerge function (@todo: do we need to?)
1193 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
65a35632 1194
087f00ec
J
1195 // Setup variables
1196 $thisTypeId = FALSE;
1197 $thisLocId = FALSE;
65a35632 1198
087f00ec
J
1199 // Provide a select drop-down for the location's location type
1200 // eg: Home, Work...
65a35632 1201
087f00ec 1202 $js = NULL;
65a35632 1203
087f00ec
J
1204 if ($blockInfo['hasLocation']) {
1205
1206 // JS lookup 'main' contact's location (if there are any)
1207 if (!empty($locations['main'][$blockName])) {
1208 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'locTypeId' );");
1209 }
1210
1211 $thisLocId = $value['location_type_id'];
1212
1213 // Put this field's location type at the top of the list
1214 $tmpIdList = $listOptions['location_type_id'];
1215 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1216 unset($tmpIdList[$thisLocId]);
1217
1218 // Add the element
eb61dc07
J
1219 $elements[] = array(
1220 'select',
abb422f9 1221 "location[$blockName][$count][locTypeId]",
eb61dc07 1222 NULL,
087f00ec 1223 $defaultLocId + $tmpIdList,
eb61dc07
J
1224 $js,
1225 );
087f00ec
J
1226
1227 // Add the relevant information to the $migrationInfo
1228 // Keep location-type-id same as that of other-contact
1229 // @todo Check this logic out
1230 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
abb422f9
J
1231 if ($blockName != 'address') {
1232 $elements[] = array('advcheckbox', "location[{$blockName}][$count][operation]", NULL, ts('add new'));
087f00ec 1233 // always use add operation
abb422f9 1234 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
087f00ec
J
1235 }
1236
1237 }
1238
1239 // Provide a select drop-down for the location's type/provider
1240 // eg websites: Google+, Facebook...
1241
1242 // CRM-17556 Set up JS lookup of 'main' contact's value by type
1243 $js = NULL;
1244
1245 if ($blockInfo['hasType']) {
1246
1247 // JS lookup 'main' contact's location (if there are any)
1248 if (!empty($locations['main'][$blockName])) {
abb422f9 1249 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'typeTypeId' );");
087f00ec
J
1250 }
1251
1252 $thisTypeId = $value[$blockInfo['hasType']];
1253
1254 // Put this field's location type at the top of the list
1255 $tmpIdList = $listOptions[$blockInfo['hasType']];
1256 $defaultTypeId = array($thisTypeId => $tmpIdList[$thisTypeId]);
1257 unset($tmpIdList[$thisTypeId]);
1258
1259 // Add the element
65a35632
J
1260 $elements[] = array(
1261 'select',
abb422f9 1262 "type[$blockName][$count][typeTypeId]",
65a35632 1263 NULL,
087f00ec 1264 $defaultTypeId + $tmpIdList,
65a35632
J
1265 $js,
1266 );
65a35632 1267
087f00ec 1268 // Add the information to the migrationInfo (@todo Why?)
abb422f9 1269 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $typeTypeId;
65a35632 1270
65a35632 1271 }
087f00ec
J
1272
1273 // Set the label for this row
1274 // @todo Reformat for website, empty brackets are lazy and ugly
abb422f9 1275 $rows["move_location_{$blockName}_$count"]['title'] = ts('%1 %2 (%3) (%4)',
087f00ec
J
1276 array(
1277 1 => $blockInfo['label'],
1278 2 => $count,
1279 3 => $thisLocId ? $listOptions['location_type_id'][$thisLocId] : '';
1280 4 => $thisTypeId ? $listOptions[$blockInfo['hasType']][$thisTypeId] : '';
3bc32133 1281 ));
087f00ec 1282
3bc32133 1283 // End loop through 'other' locations of this type
6a488035 1284 }
65a35632 1285
3bc32133 1286 // End if 'other' location for this type exists
6a488035 1287 }
087f00ec 1288
3bc32133 1289 // End loop through each location block entity
6a488035
TO
1290 }
1291
087f00ec
J
1292 // @todo NEW REFACOTRING DONE UP TO HERE
1293
6a488035
TO
1294 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1295 $config = CRM_Core_Config::singleton();
1296 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1297 $mainUser = NULL;
1298 if ($mainUfId) {
1299 // d6 compatible
1300 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1301 $mainUser = user_load($mainUfId);
1302 }
1303 elseif ($config->userFramework == 'Joomla') {
1304 $mainUser = JFactory::getUser($mainUfId);
1305 }
1306 }
1307 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1308 $otherUser = NULL;
1309 if ($otherUfId) {
1310 // d6 compatible
1311 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1312 $otherUser = user_load($otherUfId);
1313 }
1314 elseif ($config->userFramework == 'Joomla') {
1315 $otherUser = JFactory::getUser($otherUfId);
1316 }
1317 }
1318
1319 $relTables = CRM_Dedupe_Merger::relTables();
1320 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1321 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1322 foreach ($relTables as $name => $null) {
1323 if (!in_array($name, $activeRelTables) &&
1324 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1325 ) {
1326 unset($relTables[$name]);
1327 continue;
1328 }
1329
1330 $relTableElements[] = array('checkbox', "move_$name");
1331 $migrationInfo["move_$name"] = 1;
1332
1333 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1334 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1335 if ($name == 'rel_table_users') {
1336 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1337 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1338 $find = array('$ufid', '$ufname');
1339 if ($mainUser) {
1340 $replace = array($mainUfId, $mainUser->name);
1341 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1342 }
1343 if ($otherUser) {
1344 $replace = array($otherUfId, $otherUser->name);
1345 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1346 }
1347 }
1348 if ($name == 'rel_table_memberships') {
1349 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1350 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1351 }
1352 }
1353 foreach ($relTables as $name => $null) {
1354 $relTables["move_$name"] = $relTables[$name];
1355 unset($relTables[$name]);
1356 }
1357
1358 // handle custom fields
1359 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1,
1360 CRM_Utils_Array::value('contact_sub_type', $main)
1361 );
1362 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1,
1363 CRM_Utils_Array::value('contact_sub_type', $other)
1364 );
1365 CRM_Core_DAO::freeResult();
1366
1367 foreach ($otherTree as $gid => $group) {
1368 $foundField = FALSE;
1369 if (!isset($group['fields'])) {
1370 continue;
1371 }
1372
1373 foreach ($group['fields'] as $fid => $field) {
4eea8606 1374 if (in_array($fid, $compareFields['custom'])) {
6a488035
TO
1375 if (!$foundField) {
1376 $rows["custom_group_$gid"]['title'] = $group['title'];
1377 $foundField = TRUE;
1378 }
a7488080 1379 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
6a488035
TO
1380 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1381 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1382 $field, TRUE
1383 );
1384 }
1385 }
1386 $value = "null";
a7488080 1387 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
6a488035
TO
1388 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1389 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values,
1390 $field, TRUE
1391 );
1392 if ($values['data'] === 0 || $values['data'] === '0') {
1393 $values['data'] = $qfZeroBug;
d58a19a1 1394 }
6a488035 1395 $value = ($values['data']) ? $values['data'] : $value;
d58a19a1 1396 }
6a488035
TO
1397 }
1398 $rows["move_custom_$fid"]['title'] = $field['label'];
1399
1400 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1401 $migrationInfo["move_custom_$fid"] = $value;
1402 }
1403 }
1404 }
abb422f9 1405
6a488035
TO
1406 $result = array(
1407 'rows' => $rows,
1408 'elements' => $elements,
1409 'rel_table_elements' => $relTableElements,
1410 'main_loc_block' => $mainLocBlock,
1411 'rel_tables' => $relTables,
1412 'main_details' => $main,
1413 'other_details' => $other,
1414 'migration_info' => $migrationInfo,
1415 );
1416
1417 $result['main_details']['loc_block_ids'] = $locBlockIds['main'];
08ef1f91 1418 $result['main_details']['other_type_block_ids'] = $typeBlockIds['main'];
6a488035 1419 $result['other_details']['loc_block_ids'] = $locBlockIds['other'];
08ef1f91 1420 $result['other_details']['other_type_block_ids'] = $typeBlockIds['other'];
6a488035
TO
1421
1422 return $result;
1423 }
1424
1425 /**
1426 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1427 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1428 * A superset of moveContactBelongings() function.
1429 *
eb61dc07
J
1430 * @todo
1431 * Websites do not have a location type. This needs to be supported:
1432 * Add move_type_website_1, etc.
1433 *
98997235
TO
1434 * @param int $mainId
1435 * Main contact with whom merge has to happen.
1436 * @param int $otherId
1437 * Duplicate contact which would be deleted after merge operation.
77b97be7
EM
1438 *
1439 * @param $migrationInfo
6a488035 1440 *
77b97be7 1441 * @return bool
6a488035 1442 */
00be9182 1443 public static function moveAllBelongings($mainId, $otherId, $migrationInfo) {
6a488035
TO
1444 if (empty($migrationInfo)) {
1445 return FALSE;
1446 }
1447
1448 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1449 $relTables = CRM_Dedupe_Merger::relTables();
1450 $moveTables = $locBlocks = $tableOperations = array();
1451 foreach ($migrationInfo as $key => $value) {
1452 if ($value == $qfZeroBug) {
1453 $value = '0';
1454 }
7154d2a4 1455 if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) ||
353ffa53 1456 substr($key, 0, 12) == 'move_custom_') &&
7154d2a4
BS
1457 $value != NULL
1458 ) {
6a488035
TO
1459 $submitted[substr($key, 5)] = $value;
1460 }
1461 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1462 $locField = explode('_', $key);
1463 $fieldName = $locField[2];
1464 $fieldCount = $locField[3];
6832d4a9
J
1465 // Ignore operation for websites
1466 $operation = 0;
1467 if ($fieldName != 'website') {
abb422f9 1468 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
6832d4a9 1469 }
6a488035
TO
1470 // default operation is overwrite.
1471 if (!$operation) {
1472 $operation = 2;
1473 }
6a488035 1474 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
0971143c 1475
6832d4a9
J
1476 // Ignore 'locTypeId' for websites
1477 if ($fieldName != 'website') {
abb422f9 1478 $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
6832d4a9 1479 }
6a488035
TO
1480 }
1481 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1482 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1483 if (array_key_exists('operation', $migrationInfo)) {
1484 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1485 if (array_key_exists($key, $migrationInfo['operation'])) {
1486 $tableOperations[$table] = $migrationInfo['operation'][$key];
1487 }
1488 }
1489 }
1490 }
1491 }
1492
eb61dc07 1493 // **** Do location related migration.
eb61dc07 1494 // @todo Handle OpenID (not currently in API).
6a488035 1495 if (!empty($locBlocks)) {
13919cf8
J
1496
1497 $locationBlocks = array(
1498 'address' => 'Address',
6a488035 1499 'email' => 'Email',
6a488035 1500 'im' => 'IM',
13919cf8 1501 'phone' => 'Phone',
08ef1f91 1502 'website' => 'Website',
6a488035
TO
1503 );
1504
1505 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
1506 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
1507
1508 foreach ($locBlocks as $name => $block) {
1509 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1510 continue;
1511 }
13919cf8 1512 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name];
6a488035
TO
1513 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1514 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1515
1516 foreach ($block as $blkCount => $values) {
1517 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
1518 $operation = CRM_Utils_Array::value('operation', $values, 2);
6832d4a9 1519 $otherBlockId = CRM_Utils_Array::value($blkCount, $migrationInfo['other_details']['loc_block_ids'][$name]);
6a488035
TO
1520
1521 // keep 1-1 mapping for address - loc type.
1522 $idKey = $blkCount;
6832d4a9
J
1523 if (
1524 $name != 'website'
13919cf8 1525 && array_key_exists($name, $locationBlocks)
6832d4a9 1526 ) {
6a488035
TO
1527 $idKey = $locTypeId;
1528 }
1529
1530 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
d58a19a1 1531 $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
6a488035
TO
1532 }
1533
1534 if (!$otherBlockId) {
1535 continue;
1536 }
1537
08ef1f91 1538 // for the block which belongs to other-contact, link the location block to main-contact
6a488035
TO
1539 $otherBlockDAO = new $daoName();
1540 $otherBlockDAO->id = $otherBlockId;
1541 $otherBlockDAO->contact_id = $mainId;
1542 $otherBlockDAO->location_type_id = $locTypeId;
1543
eb61dc07 1544 // Get typeTypeIDs for fields that have them
08ef1f91 1545 if ($name == 'im') {
abb422f9 1546 $typeTypeId = $migrationInfo['location_blocks'][$name][$idKey]['typeTypeId'];
08ef1f91
R
1547 $otherBlockDAO->provider_id = $typeTypeId;
1548 }
1549 elseif ($name == 'phone') {
abb422f9 1550 $typeTypeId = $migrationInfo['location_blocks'][$name][$idKey]['typeTypeId'];
08ef1f91
R
1551 $otherBlockDAO->phone_type_id = $typeTypeId;
1552 }
1553 elseif ($name == 'website') {
abb422f9 1554 $typeTypeId = $migrationInfo['location_blocks'][$name][$idKey]['typeTypeId'];
08ef1f91 1555 $otherBlockDAO->website_type_id = $typeTypeId;
6832d4a9
J
1556 // No location ID, more special handling
1557 $otherBlockDAO->location_type_id = NULL;
1558 $mainBlockId = CRM_Utils_Array::value($typeTypeId, $migrationInfo['main_details']['other_type_block_ids'][$name]);
08ef1f91
R
1559 }
1560
6a488035
TO
1561 // if main contact already has primary & billing, set the flags to 0.
1562 if ($primaryDAOId) {
1563 $otherBlockDAO->is_primary = 0;
1564 }
1565 if ($billingDAOId) {
1566 $otherBlockDAO->is_billing = 0;
1567 }
1568
1569 // overwrite - need to delete block which belongs to main-contact.
0999c6c0 1570 if (isset($mainBlockId) && $mainBlockId && ($operation == 2)) {
6a488035
TO
1571 $deleteDAO = new $daoName();
1572 $deleteDAO->id = $mainBlockId;
1573 $deleteDAO->find(TRUE);
1574
1575 // if we about to delete a primary / billing block, set the flags for new block
1576 // that we going to assign to main-contact
1577 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1578 $otherBlockDAO->is_primary = 1;
1579 }
1580 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1581 $otherBlockDAO->is_billing = 1;
1582 }
1583
1584 $deleteDAO->delete();
1585 $deleteDAO->free();
1586 }
1587
1588 $otherBlockDAO->update();
1589 $otherBlockDAO->free();
1590 }
1591 }
1592 }
1593
1594 // **** Do tables related migrations
1595 if (!empty($moveTables)) {
1596 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1597 unset($moveTables, $tableOperations);
1598 }
1599
1600 // **** Do contact related migrations
1601 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
1602
1603 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1604 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1605 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1606 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
aa62b355 1607 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
6a488035
TO
1608 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1609 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1610 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1611 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1612
1613 // fix custom fields so they're edible by createProfileContact()
1614 static $treeCache = array();
1615 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1616 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'],
1617 CRM_Core_DAO::$_nullObject, NULL, -1
1618 );
1619 }
1620 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1621
1622 $cFields = array();
1623 foreach ($cgTree as $key => $group) {
1624 if (!isset($group['fields'])) {
1625 continue;
1626 }
1627 foreach ($group['fields'] as $fid => $field) {
1628 $cFields[$fid]['attributes'] = $field;
1629 }
1630 }
1631
1632 if (!isset($submitted)) {
1633 $submitted = array();
1634 }
1635 foreach ($submitted as $key => $value) {
1636 if (substr($key, 0, 7) == 'custom_') {
1637 $fid = (int) substr($key, 7);
0e357872
C
1638 if (empty($cFields[$fid])) {
1639 continue;
1640 }
6a488035
TO
1641 $htmlType = $cFields[$fid]['attributes']['html_type'];
1642 switch ($htmlType) {
1643 case 'File':
1644 $customFiles[] = $fid;
1645 unset($submitted["custom_$fid"]);
1646 break;
1647
1648 case 'Select Country':
1649 case 'Select State/Province':
1650 $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
1651 break;
1652
1653 case 'CheckBox':
1654 case 'AdvMulti-Select':
1655 case 'Multi-Select':
1656 case 'Multi-Select Country':
1657 case 'Multi-Select State/Province':
1658 // Merge values from both contacts for multivalue fields, CRM-4385
1659 // get the existing custom values from db.
1660 $customParams = array('entityID' => $mainId, $key => TRUE);
1661 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
a7488080 1662 if (!empty($customfieldValues[$key])) {
6a488035
TO
1663 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1664 if (is_array($existingValue) && !empty($existingValue)) {
1665 $mergeValue = $submmtedCustomValue = array();
1666 if ($value) {
1667 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1668 }
1669
1670 //hack to remove null and duplicate values from array.
1671 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1672 if ($v != '' && !in_array($v, $mergeValue)) {
1673 $mergeValue[] = $v;
1674 }
1675 }
1676
1677 //keep state and country as array format.
1678 //for checkbox and m-select format w/ VALUE_SEPARATOR
1679 if (in_array($htmlType, array(
353ffa53
TO
1680 'CheckBox',
1681 'Multi-Select',
c301f76e 1682 'AdvMulti-Select',
353ffa53 1683 ))) {
6a488035 1684 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
353ffa53
TO
1685 $mergeValue
1686 ) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
1687 }
1688 else {
1689 $submitted[$key] = $mergeValue;
1690 }
1691 }
1692 }
1693 elseif (in_array($htmlType, array(
353ffa53 1694 'Multi-Select Country',
c301f76e 1695 'Multi-Select State/Province',
353ffa53 1696 ))) {
6a488035
TO
1697 //we require submitted values should be in array format
1698 if ($value) {
1699 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1700 //hack to remove null values from array.
1701 $mergeValue = array();
1702 foreach ($mergeValueArray as $k => $v) {
1703 if ($v != '') {
1704 $mergeValue[] = $v;
1705 }
1706 }
1707 $submitted[$key] = $mergeValue;
1708 }
1709 }
1710 break;
1711
1712 default:
1713 break;
1714 }
1715 }
1716 }
1717
1718 // **** Do file custom fields related migrations
1719 // FIXME: move this someplace else (one of the BAOs) after discussing
b3fdbf3d 1720 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
6a488035
TO
1721 // like, delete a file...
1722
1723 if (!isset($customFiles)) {
1724 $customFiles = array();
1725 }
1726 foreach ($customFiles as $customId) {
1727 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1728
1729 // get the contact_id -> file_id mapping
1730 $fileIds = array();
1731 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
9d2678f4 1732 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
1733 while ($dao->fetch()) {
1734 $fileIds[$dao->entity_id] = $dao->file_id;
1735 }
1736 $dao->free();
1737
1738 // delete the main contact's file
1739 if (!empty($fileIds[$mainId])) {
b3fdbf3d 1740 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
6a488035
TO
1741 }
1742
1743 // move the other contact's file to main contact
1744 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
481a74f4 1745 if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
d58a19a1 1746 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
6a488035
TO
1747 }
1748 else {
1749 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1750 }
9d2678f4 1751 CRM_Core_DAO::executeQuery($sql);
6a488035 1752
481a74f4 1753 if (CRM_Core_DAO::singleValueQuery("
6a488035
TO
1754 SELECT id
1755 FROM civicrm_entity_file
353ffa53
TO
1756 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1757 ) {
6a488035
TO
1758 $sql = "
1759 UPDATE civicrm_entity_file
1760 SET entity_id = {$mainId}
1761 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1762 }
1763 else {
1764 $sql = "
1765 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1766 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1767 }
9d2678f4 1768 CRM_Core_DAO::executeQuery($sql);
6a488035
TO
1769 }
1770
1771 // move view only custom fields CRM-5362
1772 $viewOnlyCustomFields = array();
1773 foreach ($submitted as $key => $value) {
1774 $fid = (int) substr($key, 7);
8cc574cf 1775 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
6a488035
TO
1776 $viewOnlyCustomFields[$key] = $value;
1777 }
1778 }
1779
1780 // special case to set values for view only, CRM-5362
1781 if (!empty($viewOnlyCustomFields)) {
1782 $viewOnlyCustomFields['entityID'] = $mainId;
1783 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1784 }
1785
1786 // **** Delete other contact & update prev-next caching
1787 $otherParams = array(
1788 'contact_id' => $otherId,
1789 'id' => $otherId,
1790 'version' => 3,
1791 );
1792 if (CRM_Core_Permission::check('merge duplicate contacts') &&
1793 CRM_Core_Permission::check('delete contacts')
1794 ) {
1795 // if ext id is submitted then set it null for contact to be deleted
a7488080 1796 if (!empty($submitted['external_identifier'])) {
6a488035
TO
1797 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1798 CRM_Core_DAO::executeQuery($query);
1799 }
1800
1801 civicrm_api('contact', 'delete', $otherParams);
1802 CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
1803 }
1804 // FIXME: else part
1805 /* else { */
1806
1807 /* CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
1808
1809 /* } */
1810
4d5f18cc 1811 // CRM-15681 merge sub_types
1812 if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
1813 if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
481a74f4 1814 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
0db6c3e1
TO
1815 }
1816 else {
4d5f18cc 1817 $submitted['contact_sub_type'] = $other_sub_types;
1818 }
1819 }
1820
6a488035
TO
1821 // **** Update contact related info for the main contact
1822 if (!empty($submitted)) {
1823 $submitted['contact_id'] = $mainId;
1824
1825 //update current employer field
1826 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1827 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1828 $submitted['current_employer'] = $submitted['current_employer_id'];
0db6c3e1
TO
1829 }
1830 else {
6a488035
TO
1831 $submitted['current_employer'] = '';
1832 }
1833 unset($submitted['current_employer_id']);
1834 }
1835
00f3da2e 1836 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
481a74f4 1837 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
00f3da2e
BS
1838 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1839 }
481a74f4 1840 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
00f3da2e
BS
1841 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1842 }
1843
6a488035
TO
1844 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
1845 unset($submitted);
1846 }
1847
61bc2c0f
CW
1848 CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
1849
6a488035
TO
1850 return TRUE;
1851 }
16254ae1
ARW
1852
1853 /**
a6c01b45 1854 * @return array
16b10e64 1855 * Array of field names which will be compared, so everything except ID.
16254ae1 1856 */
00be9182 1857 public static function getContactFields() {
16254ae1 1858 $contactFields = CRM_Contact_DAO_Contact::fields();
353ffa53
TO
1859 $invalidFields = array(
1860 'api_key',
1861 'contact_is_deleted',
1862 'created_date',
1863 'display_name',
1864 'hash',
1865 'id',
1866 'modified_date',
1867 'primary_contact_id',
1868 'sort_name',
c301f76e 1869 'user_unique_id',
353ffa53 1870 );
bdd7870e
RN
1871 foreach ($contactFields as $field => $value) {
1872 if (in_array($field, $invalidFields)) {
1873 unset($contactFields[$field]);
1874 }
1875 }
16254ae1
ARW
1876 return array_keys($contactFields);
1877 }
ada104d5
AW
1878
1879 /**
1880 * Added for CRM-12695
c301f76e 1881 * Based on the contactID provided
ada104d5
AW
1882 * add/update membership(s) to related contacts
1883 *
c301f76e 1884 * @param int $contactID
ada104d5 1885 */
00be9182 1886 public static function addMembershipToRealtedContacts($contactID) {
ada104d5
AW
1887 $dao = new CRM_Member_DAO_Membership();
1888 $dao->contact_id = $contactID;
1889 $dao->is_test = 0;
1890 $dao->find();
1891
1892 //checks membership of contact itself
1893 while ($dao->fetch()) {
1894 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1895 if ($relationshipTypeId) {
1896 $membershipParams = array(
1897 'id' => $dao->id,
1898 'contact_id' => $dao->contact_id,
1899 'membership_type_id' => $dao->membership_type_id,
1900 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1901 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1902 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1903 'source' => $dao->source,
21dfd5f5 1904 'status_id' => $dao->status_id,
ada104d5
AW
1905 );
1906 // create/update membership(s) for related contact(s)
1907 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1908 } // end of if relationshipTypeId
1909 }
1910 }
96025800 1911
6a488035 1912}