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