Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
6 | | This work is published under the GNU AGPLv3 license with some | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
6a488035 | 9 | +--------------------------------------------------------------------+ |
d25dd0ee | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
13 | * | |
14 | * @package CRM | |
ca5cec67 | 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
16 | */ |
17 | class CRM_Dedupe_Merger { | |
6a488035 | 18 | |
e0ef6999 | 19 | /** |
4f1f1f2a CW |
20 | * FIXME: consider creating a common structure with cidRefs() and eidRefs() |
21 | * FIXME: the sub-pages references by the URLs should | |
22 | * be loaded dynamically on the merge form instead | |
e0ef6999 EM |
23 | * @return array |
24 | */ | |
00be9182 | 25 | public static function relTables() { |
6a488035 | 26 | |
641a8cb5 | 27 | if (!isset(Civi::$statics[__CLASS__]['relTables'])) { |
12d73bba | 28 | |
641a8cb5 J |
29 | // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below |
30 | // if the url can't be retrieved. A more standardised way to retrieve them is. | |
31 | // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id & | |
32 | // we may need a different function when it is not known. | |
33 | $title = $userRecordUrl = ''; | |
34 | ||
35 | $config = CRM_Core_Config::singleton(); | |
36 | if ($config->userSystem->is_drupal) { | |
37 | $userRecordUrl = CRM_Utils_System::url('user/%ufid'); | |
2c16165a | 38 | $title = ts('%1 User: %2; user id: %3', [ |
39 | 1 => $config->userFramework, | |
40 | 2 => '$ufname', | |
41 | 3 => '$ufid', | |
42 | ]); | |
641a8cb5 J |
43 | } |
44 | elseif ($config->userFramework == 'Joomla') { | |
45 | $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'; | |
2c16165a | 46 | $title = ts('%1 User: %2; user id: %3', [ |
47 | 1 => $config->userFramework, | |
48 | 2 => '$ufname', | |
49 | 3 => '$ufid', | |
50 | ]); | |
641a8cb5 | 51 | } |
6a488035 | 52 | |
2c16165a | 53 | $relTables = [ |
54 | 'rel_table_contributions' => [ | |
6a488035 | 55 | 'title' => ts('Contributions'), |
2c16165a | 56 | 'tables' => [ |
57 | 'civicrm_contribution', | |
58 | 'civicrm_contribution_recur', | |
59 | 'civicrm_contribution_soft', | |
60 | ], | |
6a488035 | 61 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'), |
2c16165a | 62 | ], |
63 | 'rel_table_contribution_page' => [ | |
6a488035 | 64 | 'title' => ts('Contribution Pages'), |
2c16165a | 65 | 'tables' => ['civicrm_contribution_page'], |
6a488035 | 66 | 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'), |
2c16165a | 67 | ], |
68 | 'rel_table_memberships' => [ | |
6a488035 | 69 | 'title' => ts('Memberships'), |
2c16165a | 70 | 'tables' => [ |
71 | 'civicrm_membership', | |
72 | 'civicrm_membership_log', | |
73 | 'civicrm_membership_type', | |
74 | ], | |
6a488035 | 75 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'), |
2c16165a | 76 | ], |
77 | 'rel_table_participants' => [ | |
6a488035 | 78 | 'title' => ts('Participants'), |
2c16165a | 79 | 'tables' => ['civicrm_participant'], |
6a488035 | 80 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'), |
2c16165a | 81 | ], |
82 | 'rel_table_events' => [ | |
6a488035 | 83 | 'title' => ts('Events'), |
2c16165a | 84 | 'tables' => ['civicrm_event'], |
6a488035 | 85 | 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'), |
2c16165a | 86 | ], |
87 | 'rel_table_activities' => [ | |
6a488035 | 88 | 'title' => ts('Activities'), |
2c16165a | 89 | 'tables' => ['civicrm_activity', 'civicrm_activity_contact'], |
6a488035 | 90 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'), |
2c16165a | 91 | ], |
92 | 'rel_table_relationships' => [ | |
6a488035 | 93 | 'title' => ts('Relationships'), |
2c16165a | 94 | 'tables' => ['civicrm_relationship'], |
6a488035 | 95 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'), |
2c16165a | 96 | ], |
97 | 'rel_table_custom_groups' => [ | |
6a488035 | 98 | 'title' => ts('Custom Groups'), |
2c16165a | 99 | 'tables' => ['civicrm_custom_group'], |
6a488035 | 100 | 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'), |
2c16165a | 101 | ], |
102 | 'rel_table_uf_groups' => [ | |
6a488035 | 103 | 'title' => ts('Profiles'), |
2c16165a | 104 | 'tables' => ['civicrm_uf_group'], |
6a488035 | 105 | 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'), |
2c16165a | 106 | ], |
107 | 'rel_table_groups' => [ | |
6a488035 | 108 | 'title' => ts('Groups'), |
2c16165a | 109 | 'tables' => ['civicrm_group_contact'], |
6a488035 | 110 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'), |
2c16165a | 111 | ], |
112 | 'rel_table_notes' => [ | |
6a488035 | 113 | 'title' => ts('Notes'), |
2c16165a | 114 | 'tables' => ['civicrm_note'], |
6a488035 | 115 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'), |
2c16165a | 116 | ], |
117 | 'rel_table_tags' => [ | |
6a488035 | 118 | 'title' => ts('Tags'), |
2c16165a | 119 | 'tables' => ['civicrm_entity_tag'], |
6a488035 | 120 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'), |
2c16165a | 121 | ], |
122 | 'rel_table_mailings' => [ | |
6a488035 | 123 | 'title' => ts('Mailings'), |
2c16165a | 124 | 'tables' => [ |
125 | 'civicrm_mailing', | |
126 | 'civicrm_mailing_event_queue', | |
127 | 'civicrm_mailing_event_subscribe', | |
128 | ], | |
f521f375 | 129 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'), |
2c16165a | 130 | ], |
131 | 'rel_table_cases' => [ | |
6a488035 | 132 | 'title' => ts('Cases'), |
2c16165a | 133 | 'tables' => ['civicrm_case_contact'], |
6a488035 | 134 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'), |
2c16165a | 135 | ], |
136 | 'rel_table_grants' => [ | |
6a488035 | 137 | 'title' => ts('Grants'), |
2c16165a | 138 | 'tables' => ['civicrm_grant'], |
6a488035 | 139 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'), |
2c16165a | 140 | ], |
141 | 'rel_table_pcp' => [ | |
6a488035 | 142 | 'title' => ts('PCPs'), |
2c16165a | 143 | 'tables' => ['civicrm_pcp'], |
6a488035 | 144 | 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'), |
2c16165a | 145 | ], |
146 | 'rel_table_pledges' => [ | |
6a488035 | 147 | 'title' => ts('Pledges'), |
2c16165a | 148 | 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'], |
6a488035 | 149 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'), |
2c16165a | 150 | ], |
151 | 'rel_table_users' => [ | |
6a488035 | 152 | 'title' => $title, |
2c16165a | 153 | 'tables' => ['civicrm_uf_match'], |
6a488035 | 154 | 'url' => $userRecordUrl, |
2c16165a | 155 | ], |
156 | ]; | |
6a488035 | 157 | |
76c53278 CW |
158 | $relTables += self::getMultiValueCustomSets('relTables'); |
159 | ||
6a488035 TO |
160 | // Allow hook_civicrm_merge() to adjust $relTables |
161 | CRM_Utils_Hook::merge('relTables', $relTables); | |
641a8cb5 J |
162 | |
163 | // Cache the results in a static variable | |
164 | Civi::$statics[__CLASS__]['relTables'] = $relTables; | |
6a488035 | 165 | } |
641a8cb5 J |
166 | |
167 | return Civi::$statics[__CLASS__]['relTables']; | |
6a488035 TO |
168 | } |
169 | ||
170 | /** | |
fe482240 | 171 | * Returns the related tables groups for which a contact has any info entered. |
ad37ac8e | 172 | * |
173 | * @param int $cid | |
174 | * | |
175 | * @return array | |
6a488035 | 176 | */ |
00be9182 | 177 | public static function getActiveRelTables($cid) { |
6a488035 | 178 | $cid = (int) $cid; |
2c16165a | 179 | $groups = []; |
6a488035 TO |
180 | |
181 | $relTables = self::relTables(); | |
182 | $cidRefs = self::cidRefs(); | |
183 | $eidRefs = self::eidRefs(); | |
184 | foreach ($relTables as $group => $params) { | |
2c16165a | 185 | $sqls = []; |
6a488035 TO |
186 | foreach ($params['tables'] as $table) { |
187 | if (isset($cidRefs[$table])) { | |
188 | foreach ($cidRefs[$table] as $field) { | |
189 | $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid"; | |
190 | } | |
191 | } | |
192 | if (isset($eidRefs[$table])) { | |
193 | foreach ($eidRefs[$table] as $entityTable => $entityId) { | |
194 | $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'"; | |
195 | } | |
196 | } | |
197 | foreach ($sqls as $sql) { | |
198 | if (CRM_Core_DAO::singleValueQuery($sql) > 0) { | |
199 | $groups[] = $group; | |
200 | } | |
201 | } | |
202 | } | |
203 | } | |
204 | return array_unique($groups); | |
205 | } | |
206 | ||
207 | /** | |
3ae0ae3d | 208 | * Get array tables and fields that reference civicrm_contact.id. |
209 | * | |
e3e87c73 | 210 | * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call. |
211 | * The entityTypes hook is the recommended way to add tables to this result. | |
3ae0ae3d | 212 | * |
e3e87c73 | 213 | * I thought about adding another hook to alter tableReferences but decided it was unclear if there |
214 | * are use cases not covered by entityTables and instead we should wait & see. | |
6a488035 | 215 | */ |
00be9182 | 216 | public static function cidRefs() { |
e31c3de1 | 217 | if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) { |
218 | return \Civi::$statics[__CLASS__]['contact_references']; | |
219 | } | |
64b3569d | 220 | |
e3e87c73 | 221 | $contactReferences = $coreReferences = CRM_Core_DAO::getReferencesToContactTable(); |
6a488035 | 222 | |
e31c3de1 | 223 | CRM_Utils_Hook::merge('cidRefs', $contactReferences); |
e3e87c73 | 224 | if ($contactReferences !== $coreReferences) { |
2c16165a | 225 | Civi::log() |
226 | ->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", ['civi.tag' => 'deprecated']); | |
e3e87c73 | 227 | } |
e31c3de1 | 228 | \Civi::$statics[__CLASS__]['contact_references'] = $contactReferences; |
229 | return \Civi::$statics[__CLASS__]['contact_references']; | |
6a488035 TO |
230 | } |
231 | ||
232 | /** | |
233 | * Return tables and their fields referencing civicrm_contact.contact_id with entity_id | |
234 | */ | |
00be9182 | 235 | public static function eidRefs() { |
6a488035 TO |
236 | static $eidRefs; |
237 | if (!$eidRefs) { | |
238 | // FIXME: this should be generated dynamically from the schema | |
239 | // tables that reference contacts with entity_{id,table} | |
2c16165a | 240 | $eidRefs = [ |
241 | 'civicrm_acl' => ['entity_table' => 'entity_id'], | |
242 | 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'], | |
243 | 'civicrm_entity_file' => ['entity_table' => 'entity_id'], | |
244 | 'civicrm_log' => ['entity_table' => 'entity_id'], | |
245 | 'civicrm_mailing_group' => ['entity_table' => 'entity_id'], | |
246 | 'civicrm_note' => ['entity_table' => 'entity_id'], | |
247 | ]; | |
6a488035 TO |
248 | |
249 | // Allow hook_civicrm_merge() to adjust $eidRefs | |
250 | CRM_Utils_Hook::merge('eidRefs', $eidRefs); | |
251 | } | |
252 | return $eidRefs; | |
253 | } | |
254 | ||
9da04f20 | 255 | /** |
fe482240 | 256 | * Return tables using locations. |
9da04f20 | 257 | */ |
00be9182 | 258 | public static function locTables() { |
9da04f20 AS |
259 | static $locTables; |
260 | if (!$locTables) { | |
2c16165a | 261 | $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone']; |
9da04f20 AS |
262 | |
263 | // Allow hook_civicrm_merge() to adjust $locTables | |
264 | CRM_Utils_Hook::merge('locTables', $locTables); | |
265 | } | |
266 | return $locTables; | |
267 | } | |
268 | ||
76c53278 CW |
269 | /** |
270 | * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc. | |
98997235 TO |
271 | * @param string $request |
272 | * 'relTables' or 'cidRefs'. | |
641a8cb5 | 273 | * @return array |
76c53278 CW |
274 | * @see CRM-13836 |
275 | */ | |
00be9182 | 276 | public static function getMultiValueCustomSets($request) { |
641a8cb5 J |
277 | |
278 | if (!isset(Civi::$statics[__CLASS__]['multiValueCustomSets'])) { | |
2c16165a | 279 | $data = [ |
280 | 'relTables' => [], | |
281 | 'cidRefs' => [], | |
282 | ]; | |
283 | $result = civicrm_api3('custom_group', 'get', [ | |
76c53278 | 284 | 'is_multiple' => 1, |
2c16165a | 285 | 'extends' => [ |
286 | 'IN' => [ | |
287 | 'Individual', | |
288 | 'Organization', | |
289 | 'Household', | |
290 | 'Contact', | |
291 | ], | |
292 | ], | |
293 | 'return' => ['id', 'title', 'table_name', 'style'], | |
294 | ]); | |
22e263ad | 295 | foreach ($result['values'] as $custom) { |
2c16165a | 296 | $data['cidRefs'][$custom['table_name']] = ['entity_id']; |
76c53278 | 297 | $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : ''; |
2c16165a | 298 | $data['relTables']['rel_table_custom_' . $custom['id']] = [ |
76c53278 | 299 | 'title' => $custom['title'], |
2c16165a | 300 | 'tables' => [$custom['table_name']], |
76c53278 | 301 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix), |
2c16165a | 302 | ]; |
76c53278 | 303 | } |
641a8cb5 J |
304 | |
305 | // Store the result in a static variable cache | |
306 | Civi::$statics[__CLASS__]['multiValueCustomSets'] = $data; | |
76c53278 | 307 | } |
641a8cb5 J |
308 | |
309 | return Civi::$statics[__CLASS__]['multiValueCustomSets'][$request]; | |
76c53278 CW |
310 | } |
311 | ||
6a488035 TO |
312 | /** |
313 | * Tables which require custom processing should declare functions to call here. | |
314 | * Doing so will override normal processing. | |
315 | */ | |
00be9182 | 316 | public static function cpTables() { |
6a488035 TO |
317 | static $tables; |
318 | if (!$tables) { | |
2c16165a | 319 | $tables = [ |
320 | 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'], | |
321 | 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'], | |
6a488035 | 322 | // Empty array == do nothing - this table is handled by mergeGroupContact |
2c16165a | 323 | 'civicrm_subscription_history' => [], |
324 | 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'], | |
325 | 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'], | |
326 | ]; | |
6a488035 TO |
327 | } |
328 | return $tables; | |
329 | } | |
330 | ||
331 | /** | |
100fef9d | 332 | * Return payment related table. |
6a488035 | 333 | */ |
00be9182 | 334 | public static function paymentTables() { |
6a488035 TO |
335 | static $tables; |
336 | if (!$tables) { | |
2c16165a | 337 | $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant']; |
6a488035 | 338 | } |
6a488035 TO |
339 | return $tables; |
340 | } | |
341 | ||
342 | /** | |
100fef9d | 343 | * Return payment update Query. |
54957108 | 344 | * |
345 | * @param string $tableName | |
346 | * @param int $mainContactId | |
347 | * @param int $otherContactId | |
348 | * | |
349 | * @return array | |
6a488035 | 350 | */ |
00be9182 | 351 | public static function paymentSql($tableName, $mainContactId, $otherContactId) { |
2c16165a | 352 | $sqls = []; |
6a488035 TO |
353 | if (!$tableName || !$mainContactId || !$otherContactId) { |
354 | return $sqls; | |
355 | } | |
356 | ||
357 | $paymentTables = self::paymentTables(); | |
358 | if (!in_array($tableName, $paymentTables)) { | |
359 | return $sqls; | |
360 | } | |
361 | ||
362 | switch ($tableName) { | |
363 | case 'civicrm_pledge': | |
364 | $sqls[] = " | |
365 | UPDATE IGNORE civicrm_contribution contribution | |
366 | INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id ) | |
367 | INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id ) | |
368 | SET contribution.contact_id = $mainContactId | |
369 | WHERE pledge.contact_id = $otherContactId"; | |
370 | break; | |
371 | ||
372 | case 'civicrm_membership': | |
373 | $sqls[] = " | |
374 | UPDATE IGNORE civicrm_contribution contribution | |
375 | INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id ) | |
376 | INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id ) | |
377 | SET contribution.contact_id = $mainContactId | |
378 | WHERE membership.contact_id = $otherContactId"; | |
379 | break; | |
380 | ||
381 | case 'civicrm_participant': | |
382 | $sqls[] = " | |
383 | UPDATE IGNORE civicrm_contribution contribution | |
384 | INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id ) | |
385 | INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id ) | |
386 | SET contribution.contact_id = $mainContactId | |
387 | WHERE participant.contact_id = $otherContactId"; | |
388 | break; | |
389 | } | |
390 | ||
391 | return $sqls; | |
392 | } | |
393 | ||
e0ef6999 | 394 | /** |
100fef9d CW |
395 | * @param int $mainId |
396 | * @param int $otherId | |
397 | * @param string $tableName | |
e0ef6999 EM |
398 | * @param array $tableOperations |
399 | * @param string $mode | |
400 | * | |
401 | * @return array | |
402 | */ | |
2c16165a | 403 | public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') { |
404 | $sqls = []; | |
6a488035 TO |
405 | if (!$tableName || !$mainId || !$otherId) { |
406 | return $sqls; | |
407 | } | |
408 | ||
6a488035 TO |
409 | switch ($tableName) { |
410 | case 'civicrm_membership': | |
d58a19a1 TO |
411 | if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) { |
412 | break; | |
413 | } | |
414 | if ($mode == 'add') { | |
415 | $sqls[] = " | |
6a488035 TO |
416 | DELETE membership1.* FROM civicrm_membership membership1 |
417 | INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id | |
418 | AND membership1.contact_id = {$mainId} | |
419 | AND membership2.contact_id = {$otherId} "; | |
d58a19a1 TO |
420 | } |
421 | if ($mode == 'payment') { | |
422 | $sqls[] = " | |
6a488035 TO |
423 | DELETE contribution.* FROM civicrm_contribution contribution |
424 | INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id | |
425 | INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id | |
426 | AND membership1.contact_id = {$mainId} | |
427 | INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id | |
428 | AND membership2.contact_id = {$otherId}"; | |
d58a19a1 TO |
429 | } |
430 | break; | |
6a488035 TO |
431 | |
432 | case 'civicrm_uf_match': | |
433 | // normal queries won't work for uf_match since that will lead to violation of unique constraint, | |
b44e3f84 | 434 | // failing to meet intended result. Therefore we introduce this additional query: |
6a488035 TO |
435 | $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}"; |
436 | break; | |
437 | } | |
438 | ||
439 | return $sqls; | |
440 | } | |
441 | ||
4099a9c5 AP |
442 | /** |
443 | * Based on the provided two contact_ids and a set of tables, remove the | |
444 | * belongings of the other contact and of their relations. | |
445 | * | |
446 | * @param int $otherID | |
447 | * @param bool $tables | |
448 | */ | |
449 | public static function removeContactBelongings($otherID, $tables) { | |
450 | // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact. | |
451 | if (in_array("civicrm_membership", $tables)) { | |
452 | $membershipIDs = CRM_Utils_Array::collect('id', | |
453 | CRM_Utils_Array::value('values', | |
2c16165a | 454 | civicrm_api3("Membership", "get", [ |
518fa0ee SL |
455 | "contact_id" => $otherID, |
456 | "return" => "id", | |
457 | ]) | |
e122e55d TO |
458 | ) |
459 | ); | |
4099a9c5 AP |
460 | |
461 | if (!empty($membershipIDs)) { | |
2c16165a | 462 | civicrm_api3("Membership", "get", [ |
463 | 'owner_membership_id' => ['IN' => $membershipIDs], | |
464 | 'api.Membership.delete' => ['id' => '$value.id'], | |
465 | ]); | |
4099a9c5 AP |
466 | } |
467 | } | |
468 | } | |
469 | ||
6a488035 TO |
470 | /** |
471 | * Based on the provided two contact_ids and a set of tables, move the | |
472 | * belongings of the other contact to the main one. | |
473 | * | |
54957108 | 474 | * @param int $mainId |
475 | * @param int $otherId | |
476 | * @param bool $tables | |
477 | * @param array $tableOperations | |
b35800bd | 478 | * @param array $customTableToCopyFrom |
6a488035 | 479 | */ |
2c16165a | 480 | public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = [], $customTableToCopyFrom = NULL) { |
6a488035 TO |
481 | $cidRefs = self::cidRefs(); |
482 | $eidRefs = self::eidRefs(); | |
483 | $cpTables = self::cpTables(); | |
484 | $paymentTables = self::paymentTables(); | |
485 | ||
b35800bd | 486 | // getting all custom tables |
2c16165a | 487 | $customTables = []; |
ae2346d4 | 488 | if ($customTableToCopyFrom !== NULL) { |
e3e87c73 | 489 | // @todo this duplicates cidRefs? |
490 | CRM_Core_DAO::appendCustomTablesExtendingContacts($customTables); | |
4c7e5001 | 491 | CRM_Core_DAO::appendCustomContactReferenceFields($customTables); |
674920ca | 492 | $customTables = array_keys($customTables); |
6a488035 | 493 | } |
674920ca ES |
494 | |
495 | $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs)); | |
0556db5d CR |
496 | |
497 | // if there aren't any specific tables, don't affect the ones handled by relTables() | |
498 | // also don't affect tables in locTables() CRM-15658 | |
499 | $relTables = self::relTables(); | |
500 | $handled = self::locTables(); | |
501 | ||
502 | foreach ($relTables as $params) { | |
503 | $handled = array_merge($handled, $params['tables']); | |
6a488035 | 504 | } |
0556db5d | 505 | $affected = array_diff($affected, $handled); |
e3159b07 | 506 | $affected = array_unique(array_merge($affected, $tables)); |
6a488035 TO |
507 | |
508 | $mainId = (int) $mainId; | |
509 | $otherId = (int) $otherId; | |
06f4969c | 510 | $multi_value_tables = array_keys(CRM_Dedupe_Merger::getMultiValueCustomSets('cidRefs')); |
6a488035 | 511 | |
2c16165a | 512 | $sqls = []; |
6a488035 | 513 | foreach ($affected as $table) { |
06f4969c | 514 | // skipping non selected single-value custom table's value migration |
515 | if (!in_array($table, $multi_value_tables)) { | |
516 | if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) { | |
4c7e5001 PF |
517 | if (isset($cidRefs[$table]) && ($delCol = array_search('entity_id', $cidRefs[$table])) !== FALSE) { |
518 | // remove entity_id from the field list | |
519 | unset($cidRefs[$table][$delCol]); | |
520 | } | |
06f4969c | 521 | } |
b35800bd | 522 | } |
674920ca | 523 | |
6a488035 TO |
524 | // Call custom processing function for objects that require it |
525 | if (isset($cpTables[$table])) { | |
526 | foreach ($cpTables[$table] as $className => $fnName) { | |
43d4ad93 | 527 | $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations); |
6a488035 TO |
528 | } |
529 | // Skip normal processing | |
530 | continue; | |
531 | } | |
b3fdbf3d | 532 | |
6a488035 TO |
533 | // use UPDATE IGNORE + DELETE query pair to skip on situations when |
534 | // there's a UNIQUE restriction on ($field, some_other_field) pair | |
535 | if (isset($cidRefs[$table])) { | |
536 | foreach ($cidRefs[$table] as $field) { | |
537 | // carry related contributions CRM-5359 | |
538 | if (in_array($table, $paymentTables)) { | |
6a488035 TO |
539 | $paymentSqls = self::paymentSql($table, $mainId, $otherId); |
540 | $sqls = array_merge($sqls, $paymentSqls); | |
71560cf3 C |
541 | |
542 | if (!empty($tables) && !in_array('civicrm_contribution', $tables)) { | |
543 | $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment'); | |
544 | $sqls = array_merge($sqls, $payOprSqls); | |
545 | } | |
6a488035 TO |
546 | } |
547 | ||
548 | $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations); | |
549 | $sqls = array_merge($sqls, $preOperationSqls); | |
550 | ||
4c7e5001 PF |
551 | if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self::customRecordExists($mainId, $table, $field) && $field == 'entity_id') { |
552 | // this is the entity_id column of a custom field group where: | |
553 | // - the custom table should be copied as indicated by $customTableToCopyFrom | |
554 | // e.g. because a field in the group was selected in a form | |
555 | // - AND no record exists yet for the $mainId contact | |
556 | // we only do this for column "entity_id" as we wouldn't want to | |
557 | // run this INSERT for ContactReference fields | |
ae2346d4 CR |
558 | $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)"; |
559 | } | |
6a488035 TO |
560 | $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId"; |
561 | $sqls[] = "DELETE FROM $table WHERE $field = $otherId"; | |
562 | } | |
563 | } | |
ae2346d4 | 564 | |
6a488035 TO |
565 | if (isset($eidRefs[$table])) { |
566 | foreach ($eidRefs[$table] as $entityTable => $entityId) { | |
567 | $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'"; | |
568 | $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'"; | |
569 | } | |
570 | } | |
571 | } | |
572 | ||
573 | // Allow hook_civicrm_merge() to add SQL statements for the merge operation. | |
574 | CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables); | |
575 | ||
6a488035 | 576 | foreach ($sqls as $sql) { |
2c16165a | 577 | CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE); |
6a488035 | 578 | } |
0556db5d | 579 | CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId); |
6a488035 TO |
580 | } |
581 | ||
4f751978 CR |
582 | /** |
583 | * Given a contact ID, will check if a record exists in given table. | |
584 | * | |
585 | * @param $contactID | |
586 | * @param $table | |
587 | * @param $idField | |
588 | * Field where the contact's ID is stored in the table | |
589 | * | |
590 | * @return bool | |
591 | * True if a record is found for the given contact ID, false otherwise | |
592 | */ | |
ae2346d4 CR |
593 | private static function customRecordExists($contactID, $table, $idField) { |
594 | $sql = " | |
595 | SELECT COUNT(*) AS count | |
596 | FROM $table | |
597 | WHERE $idField = $contactID | |
598 | "; | |
599 | $dbResult = CRM_Core_DAO::executeQuery($sql); | |
600 | $dbResult->fetch(); | |
601 | ||
602 | if ($dbResult->count > 0) { | |
ee3b1d86 | 603 | return TRUE; |
ae2346d4 CR |
604 | } |
605 | ||
ee3b1d86 | 606 | return FALSE; |
ae2346d4 CR |
607 | } |
608 | ||
6a488035 | 609 | /** |
4eea8606 | 610 | * Load all non-empty fields for the contacts |
b3fdbf3d | 611 | * |
98997235 TO |
612 | * @param array $main |
613 | * Contact details. | |
614 | * @param array $other | |
615 | * Contact details. | |
6a488035 | 616 | * |
77b97be7 | 617 | * @return array |
6a488035 | 618 | */ |
4eea8606 | 619 | public static function retrieveFields($main, $other) { |
2c16165a | 620 | $result = [ |
621 | 'contact' => [], | |
622 | 'custom' => [], | |
623 | ]; | |
16254ae1 | 624 | foreach (self::getContactFields() as $validField) { |
eb61dc07 J |
625 | // CRM-17556 Get all non-empty fields, to make comparison easier |
626 | if (!empty($main[$validField]) || !empty($other[$validField])) { | |
6a488035 TO |
627 | $result['contact'][] = $validField; |
628 | } | |
629 | } | |
630 | ||
631 | $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']); | |
632 | $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']); | |
633 | $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs))); | |
634 | foreach ($keys as $key) { | |
76c53278 CW |
635 | // Exclude multi-value fields CRM-13836 |
636 | if (strpos($key, '_')) { | |
637 | continue; | |
638 | } | |
6a488035 TO |
639 | $key1 = CRM_Utils_Array::value($key, $mainEvs); |
640 | $key2 = CRM_Utils_Array::value($key, $otherEvs); | |
26b7ff28 | 641 | // We wish to retain '0' as it has a different meaning than NULL on a checkbox. |
642 | // However I can't think of a case where an empty string is more meaningful than null | |
643 | // or where it would be FALSE or something else nullish. | |
644 | $valuesToIgnore = [NULL, '', []]; | |
645 | if (!in_array($key1, $valuesToIgnore, TRUE) || !in_array($key2, $valuesToIgnore, TRUE)) { | |
6a488035 TO |
646 | $result['custom'][] = $key; |
647 | } | |
648 | } | |
649 | return $result; | |
650 | } | |
651 | ||
652 | /** | |
100fef9d | 653 | * Batch merge a set of contacts based on rule-group and group. |
6a488035 | 654 | * |
98997235 TO |
655 | * @param int $rgid |
656 | * Rule group id. | |
657 | * @param int $gid | |
658 | * Group id. | |
659 | * @param string $mode | |
660 | * Helps decide how to behave when there are conflicts. | |
15a793bb EM |
661 | * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive' |
662 | * mode does a force merge. | |
f931b74c | 663 | * @param int $batchLimit number of merges to carry out in one batch. |
664 | * @param int $isSelected if records with is_selected column needs to be processed. | |
bb22928b | 665 | * Note the option of '2' is only used in conjunction with $redirectForPerformance |
b5a6c6c5 | 666 | * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered |
667 | * out in favour of explicitly passing in $reloadCacheIfEmpty | |
6a488035 | 668 | * |
e23e26ec | 669 | * @param array $criteria |
670 | * Criteria to use in the filter. | |
671 | * | |
3058f4d9 | 672 | * @param bool $checkPermissions |
673 | * Respect logged in user permissions. | |
bb22928b | 674 | * @param bool|NULL $reloadCacheIfEmpty |
675 | * If not set explicitly this is calculated but it is preferred that it be set | |
676 | * per comments on isSelected above. | |
3058f4d9 | 677 | * |
997a03fe | 678 | * @param int $searchLimit |
679 | * Limit on number of contacts to search for duplicates for. | |
680 | * This means that if the limit is 1000 then only duplicates for the first 1000 contacts | |
681 | * matching criteria will be found and batchMerged (the number of merges could be less than or greater than 100) | |
682 | * | |
77b97be7 | 683 | * @return array|bool |
997a03fe | 684 | * |
685 | * @throws \CRM_Core_Exception | |
686 | * @throws \CiviCRM_API3_Exception | |
6a488035 | 687 | */ |
997a03fe | 688 | public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL, $searchLimit = 0) { |
63ef778e | 689 | $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE; |
418ffc5b | 690 | if ($mode === 'aggressive' && $checkPermissions && !CRM_Core_Permission::check('force merge duplicate contacts')) { |
691 | throw new CRM_Core_Exception(ts('Insufficient permissions for aggressive mode batch merge')); | |
692 | } | |
bb22928b | 693 | if (!isset($reloadCacheIfEmpty)) { |
694 | $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2); | |
695 | } | |
696 | if ($isSelected !== 0 && $isSelected !== 1) { | |
697 | // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value. | |
698 | $isSelected = NULL; | |
699 | } | |
e3c42269 | 700 | $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode == 'aggressive'), $criteria, $checkPermissions, $searchLimit); |
6a488035 | 701 | |
2c16165a | 702 | $cacheParams = [ |
997a03fe | 703 | 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions, $searchLimit), |
2988f5c7 | 704 | // @todo stop passing these parameters in & instead calculate them in the merge function based |
705 | // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected. | |
706 | 'join' => self::getJoinOnDedupeTable(), | |
ed3c1599 | 707 | 'where' => self::getWhereString($isSelected), |
708 | 'limit' => (int) $batchLimit, | |
2c16165a | 709 | ]; |
d238756a | 710 | return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions); |
6a488035 TO |
711 | } |
712 | ||
2ae26001 | 713 | /** |
714 | * Get the string to join the prevnext cache to the dedupe table. | |
715 | * | |
716 | * @return string | |
717 | * The join string to join prevnext cache on the dedupe table. | |
718 | */ | |
719 | public static function getJoinOnDedupeTable() { | |
720 | return " | |
721 | LEFT JOIN civicrm_dedupe_exception de | |
722 | ON ( | |
723 | pn.entity_id1 = de.contact_id1 | |
724 | AND pn.entity_id2 = de.contact_id2 ) | |
725 | "; | |
726 | } | |
727 | ||
2988f5c7 | 728 | /** |
729 | * Get where string for dedupe join. | |
730 | * | |
2988f5c7 | 731 | * @param bool $isSelected |
732 | * | |
733 | * @return string | |
734 | */ | |
ed3c1599 | 735 | protected static function getWhereString($isSelected) { |
2988f5c7 | 736 | $where = "de.id IS NULL"; |
737 | if ($isSelected === 0 || $isSelected === 1) { | |
738 | $where .= " AND pn.is_selected = {$isSelected}"; | |
739 | } | |
2988f5c7 | 740 | return $where; |
741 | } | |
742 | ||
bc854509 | 743 | /** |
744 | * Update the statistics for the merge set. | |
745 | * | |
746 | * @param string $cacheKeyString | |
747 | * @param array $result | |
748 | */ | |
2c16165a | 749 | public static function updateMergeStats($cacheKeyString, $result = []) { |
63ef778e | 750 | // gather latest stats |
2c16165a | 751 | $merged = count($result['merged']); |
63ef778e | 752 | $skipped = count($result['skipped']); |
753 | ||
754 | if ($merged <= 0 && $skipped <= 0) { | |
755 | return; | |
756 | } | |
757 | ||
758 | // get previous stats | |
e13fa54b | 759 | $previousStats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString); |
63ef778e | 760 | if (!empty($previousStats)) { |
e13fa54b | 761 | if ($previousStats['merged']) { |
762 | $merged = $merged + $previousStats['merged']; | |
63ef778e | 763 | } |
e13fa54b | 764 | if ($previousStats['skipped']) { |
765 | $skipped = $skipped + $previousStats['skipped']; | |
63ef778e | 766 | } |
767 | } | |
768 | ||
769 | // delete old stats | |
770 | CRM_Dedupe_Merger::resetMergeStats($cacheKeyString); | |
771 | ||
772 | // store the updated stats | |
2c16165a | 773 | $data = [ |
774 | 'merged' => $merged, | |
63ef778e | 775 | 'skipped' => $skipped, |
2c16165a | 776 | ]; |
63ef778e | 777 | $data = CRM_Core_DAO::escapeString(serialize($data)); |
778 | ||
e1c519d7 | 779 | CRM_Core_BAO_PrevNextCache::setItem('civicrm_contact', 0, 0, $cacheKeyString . '_stats', $data); |
63ef778e | 780 | } |
781 | ||
ae6455b2 | 782 | /** |
783 | * Delete information about merges for the given string. | |
784 | * | |
785 | * @param $cacheKeyString | |
786 | */ | |
f931b74c | 787 | public static function resetMergeStats($cacheKeyString) { |
ae6455b2 | 788 | CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats"); |
63ef778e | 789 | } |
790 | ||
bc854509 | 791 | /** |
792 | * Get merge outcome statistics. | |
793 | * | |
794 | * @param string $cacheKeyString | |
795 | * | |
796 | * @return array | |
797 | * Array of how many were merged and how many were skipped. | |
e13fa54b | 798 | * |
799 | * @throws \CiviCRM_API3_Exception | |
bc854509 | 800 | */ |
f931b74c | 801 | public static function getMergeStats($cacheKeyString) { |
e13fa54b | 802 | $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values']; |
63ef778e | 803 | if (!empty($stats)) { |
e13fa54b | 804 | return $stats[0]['data']; |
63ef778e | 805 | } |
e13fa54b | 806 | return []; |
63ef778e | 807 | } |
808 | ||
bc854509 | 809 | /** |
810 | * Get merge statistics message. | |
811 | * | |
3743fd3d | 812 | * @param array $stats |
bc854509 | 813 | * |
814 | * @return string | |
815 | */ | |
3743fd3d CW |
816 | public static function getMergeStatsMsg($stats) { |
817 | $msg = ''; | |
63ef778e | 818 | if (!empty($stats['merged'])) { |
2c16165a | 819 | $msg = '<p>' . ts('One contact merged.', [ |
518fa0ee SL |
820 | 'count' => $stats['merged'], |
821 | 'plural' => '%count contacts merged.', | |
822 | ]) . '</p>'; | |
63ef778e | 823 | } |
824 | if (!empty($stats['skipped'])) { | |
2c16165a | 825 | $msg .= '<p>' . ts('One contact was skipped.', [ |
518fa0ee SL |
826 | 'count' => $stats['skipped'], |
827 | 'plural' => '%count contacts were skipped.', | |
828 | ]) . '</p>'; | |
63ef778e | 829 | } |
830 | return $msg; | |
831 | } | |
832 | ||
6a488035 | 833 | /** |
100fef9d | 834 | * Merge given set of contacts. Performs core operation. |
6a488035 | 835 | * |
98997235 TO |
836 | * @param array $dupePairs |
837 | * Set of pair of contacts for whom merge is to be done. | |
838 | * @param array $cacheParams | |
839 | * Prev-next-cache params based on which next pair of contacts are computed. | |
6a488035 | 840 | * Generally used with batch-merge. |
98997235 TO |
841 | * @param string $mode |
842 | * Helps decide how to behave when there are conflicts. | |
6a488035 TO |
843 | * A 'safe' value skips the merge if there are any un-resolved conflicts. |
844 | * Does a force merge otherwise (aggressive mode). | |
6a488035 | 845 | * |
77b97be7 | 846 | * @param bool $redirectForPerformance |
3058f4d9 | 847 | * Redirect to a url for batch processing. |
848 | * | |
849 | * @param bool $checkPermissions | |
850 | * Respect logged in user permissions. | |
77b97be7 EM |
851 | * |
852 | * @return array|bool | |
b068bfde | 853 | * |
854 | * @throws \API_Exception | |
855 | * @throws \CRM_Core_Exception | |
856 | * @throws \CiviCRM_API3_Exception | |
6a488035 | 857 | */ |
2c16165a | 858 | public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe', |
859 | $redirectForPerformance = FALSE, $checkPermissions = TRUE | |
6a488035 TO |
860 | ) { |
861 | $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams); | |
2c16165a | 862 | $resultStats = ['merged' => [], 'skipped' => []]; |
6a488035 TO |
863 | |
864 | // we don't want dupe caching to get reset after every-merge, and therefore set the | |
0626851e | 865 | CRM_Core_Config::setPermitCacheFlushMode(FALSE); |
2c16165a | 866 | $deletedContacts = []; |
6a488035 TO |
867 | |
868 | while (!empty($dupePairs)) { | |
78272750 | 869 | foreach ($dupePairs as $index => $dupes) { |
870 | if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) { | |
871 | unset($dupePairs[$index]); | |
872 | continue; | |
873 | } | |
b068bfde | 874 | if (($result = self::dedupePair($dupes, $mode, $checkPermissions, $cacheKeyString)) === FALSE) { |
875 | unset($dupePairs[$index]); | |
876 | continue; | |
877 | } | |
878 | if (!empty($result['merged'])) { | |
879 | $deletedContacts[] = $result['merged'][0]['other_id']; | |
880 | $resultStats['merged'][] = ($result['merged'][0]); | |
881 | } | |
882 | else { | |
883 | $resultStats['skipped'][] = ($result['skipped'][0]); | |
6a488035 | 884 | } |
6a488035 TO |
885 | } |
886 | ||
887 | if ($cacheKeyString && !$redirectForPerformance) { | |
888 | // retrieve next pair of dupes | |
2988f5c7 | 889 | // @todo call getDuplicatePairs. |
6a488035 TO |
890 | $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, |
891 | $cacheParams['join'], | |
66eceb0b | 892 | $cacheParams['where'], |
893 | 0, | |
ed3c1599 | 894 | $cacheParams['limit'], |
2c16165a | 895 | [], |
66eceb0b | 896 | '', |
897 | FALSE | |
6a488035 TO |
898 | ); |
899 | } | |
900 | else { | |
901 | // do not proceed. Terminate the loop | |
902 | unset($dupePairs); | |
903 | } | |
904 | } | |
63ef778e | 905 | |
906 | CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats); | |
6a488035 TO |
907 | return $resultStats; |
908 | } | |
909 | ||
910 | /** | |
911 | * A function which uses various rules / algorithms for choosing which contact to bias to | |
912 | * when there's a conflict (to handle "gotchas"). Plus the safest route to merge. | |
913 | * | |
98997235 TO |
914 | * @param int $mainId |
915 | * Main contact with whom merge has to happen. | |
916 | * @param int $otherId | |
917 | * Duplicate contact which would be deleted after merge operation. | |
918 | * @param array $migrationInfo | |
919 | * Array of information about which elements to merge. | |
920 | * @param string $mode | |
921 | * Helps decide how to behave when there are conflicts. | |
13919cf8 J |
922 | * - A 'safe' value skips the merge if there are any un-resolved conflicts. |
923 | * - Does a force merge otherwise (aggressive mode). | |
6a488035 | 924 | * |
ad37ac8e | 925 | * @param array $conflicts |
a2abc387 | 926 | * An empty array to be filed with conflict information. |
ad37ac8e | 927 | * |
77b97be7 | 928 | * @return bool |
ffa59d18 | 929 | * |
930 | * @throws \CRM_Core_Exception | |
931 | * @throws \CiviCRM_API3_Exception | |
932 | * @throws \API_Exception | |
6a488035 | 933 | */ |
2c16165a | 934 | public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) { |
0971143c | 935 | |
a2abc387 | 936 | $conflicts = self::getConflicts($migrationInfo, $mainId, $otherId, $mode); |
d73a022b | 937 | // A hook could have set skip_merge in order to alter merge behaviour. |
938 | // This is a something we might ideally deprecate since they really 'should' | |
939 | // mess with the conflicts array instead. | |
940 | return (bool) ($migrationData['skip_merge'] ?? !empty($conflicts)); | |
6a488035 TO |
941 | } |
942 | ||
d48ad2c0 | 943 | /** |
944 | * Compare 2 addresses to see if they are the same. | |
945 | * | |
946 | * @param array $mainAddress | |
947 | * @param array $comparisonAddress | |
948 | * | |
949 | * @return bool | |
950 | */ | |
518fa0ee | 951 | public static function locationIsSame($mainAddress, $comparisonAddress) { |
ffa59d18 | 952 | $keysToIgnore = self::ignoredFields(); |
d48ad2c0 | 953 | foreach ($comparisonAddress as $field => $value) { |
954 | if (in_array($field, $keysToIgnore)) { | |
955 | continue; | |
956 | } | |
00443529 | 957 | if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) { |
d48ad2c0 | 958 | return FALSE; |
959 | } | |
960 | } | |
961 | return TRUE; | |
962 | } | |
963 | ||
34917198 J |
964 | /** |
965 | * A function to build an array of information about location blocks that is | |
966 | * required when merging location fields | |
967 | * | |
968 | * @return array | |
969 | */ | |
970 | public static function getLocationBlockInfo() { | |
2c16165a | 971 | $locationBlocks = [ |
972 | 'address' => [ | |
34917198 J |
973 | 'label' => 'Address', |
974 | 'displayField' => 'display', | |
975 | 'sortString' => 'location_type_id', | |
976 | 'hasLocation' => TRUE, | |
977 | 'hasType' => FALSE, | |
2c16165a | 978 | ], |
979 | 'email' => [ | |
34917198 | 980 | 'label' => 'Email', |
2a7e1ddc | 981 | 'displayField' => 'display', |
34917198 J |
982 | 'sortString' => 'location_type_id', |
983 | 'hasLocation' => TRUE, | |
984 | 'hasType' => FALSE, | |
2c16165a | 985 | ], |
986 | 'im' => [ | |
34917198 J |
987 | 'label' => 'IM', |
988 | 'displayField' => 'name', | |
989 | 'sortString' => 'location_type_id,provider_id', | |
990 | 'hasLocation' => TRUE, | |
991 | 'hasType' => 'provider_id', | |
2c16165a | 992 | ], |
993 | 'phone' => [ | |
34917198 J |
994 | 'label' => 'Phone', |
995 | 'displayField' => 'phone', | |
996 | 'sortString' => 'location_type_id,phone_type_id', | |
997 | 'hasLocation' => TRUE, | |
998 | 'hasType' => 'phone_type_id', | |
2c16165a | 999 | ], |
1000 | 'website' => [ | |
34917198 J |
1001 | 'label' => 'Website', |
1002 | 'displayField' => 'url', | |
1003 | 'sortString' => 'website_type_id', | |
1004 | 'hasLocation' => FALSE, | |
1005 | 'hasType' => 'website_type_id', | |
2c16165a | 1006 | ], |
1007 | ]; | |
34917198 J |
1008 | return $locationBlocks; |
1009 | } | |
1010 | ||
6a488035 TO |
1011 | /** |
1012 | * A function to build an array of information required by merge function and the merge UI. | |
1013 | * | |
98997235 TO |
1014 | * @param int $mainId |
1015 | * Main contact with whom merge has to happen. | |
1016 | * @param int $otherId | |
1017 | * Duplicate contact which would be deleted after merge operation. | |
201057c0 | 1018 | * @param bool $checkPermissions |
1019 | * Should the logged in user's permissions be ignore. Setting this to false is | |
1020 | * highly risky as it could cause data to be lost due to conflicts not showing up. | |
1021 | * OTOH there is a risk a merger might view custom data they do not have permission to. | |
1022 | * Hence for now only making this really explicit and making it reflect perms in | |
1023 | * an api call. | |
1024 | * | |
1025 | * @todo review permissions issue! | |
6a488035 | 1026 | * |
77b97be7 | 1027 | * @return array|bool|int |
1e3e0eed J |
1028 | * |
1029 | * rows => An array of arrays, each is row of merge information for the table | |
1030 | * Format: move_fieldname, eg: move_contact_type | |
1031 | * main => Value associated with the main contact | |
1032 | * other => Value associated with the other contact | |
1033 | * title => The title of the field to display in the merge table | |
1034 | * | |
1035 | * elements => An array of form elements for the merge UI | |
1036 | * | |
1037 | * rel_table_elements => An array of form elements for the merge UI for | |
1038 | * entities related to the contact (eg: checkbox to move 'mailings') | |
1039 | * | |
1e3e0eed J |
1040 | * rel_tables => Stores the tables that have related entities for the contact |
1041 | * for example mailings, groups | |
1042 | * | |
1043 | * main_details => An array of core contact field values, eg: first_name, etc. | |
1044 | * location_blocks => An array of location block data for the main contact | |
1045 | * stored as the 'result' of an API call. | |
1046 | * eg: main_details['location_blocks']['address'][0]['id'] | |
1047 | * eg: main_details['location_blocks']['email'][1]['id'] | |
1048 | * | |
1049 | * other_details => As above, but for the 'other' contact | |
1050 | * | |
1051 | * migration_info => Stores the 'default' merge actions for each field which | |
1052 | * is used when programatically merging contacts. It contains instructions | |
1053 | * to move all fields from the 'other' contact to the 'main' contact, as | |
1054 | * though the form had been submitted with those options. | |
1055 | * | |
3058f4d9 | 1056 | * @throws \CRM_Core_Exception |
1057 | * @throws \CiviCRM_API3_Exception | |
1058 | * @throws \Exception | |
6a488035 | 1059 | */ |
201057c0 | 1060 | public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) { |
6a488035 | 1061 | $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; |
74a6069d | 1062 | $fields = self::getMergeFieldsMetadata(); |
6a488035 | 1063 | |
fcc3d8ee | 1064 | $main = self::getMergeContactDetails($mainId); |
1065 | $other = self::getMergeContactDetails($otherId); | |
6a488035 | 1066 | |
4eea8606 | 1067 | $compareFields = self::retrieveFields($main, $other); |
6a488035 | 1068 | |
2c16165a | 1069 | $rows = $elements = $relTableElements = $migrationInfo = []; |
6a488035 | 1070 | |
4eea8606 | 1071 | foreach ($compareFields['contact'] as $field) { |
4d5f18cc | 1072 | if ($field == 'contact_sub_type') { |
1073 | // CRM-15681 don't display sub-types in UI | |
1074 | continue; | |
1075 | } | |
1ce87307 | 1076 | $rows["move_$field"] = [ |
1077 | 'main' => self::getFieldValueAndLabel($field, $main)['label'], | |
1078 | 'other' => self::getFieldValueAndLabel($field, $other)['label'], | |
1079 | 'title' => $fields[$field]['title'], | |
1080 | ]; | |
2fd72602 | 1081 | |
bdc6e6ee | 1082 | $value = self::getFieldValueAndLabel($field, $other)['value']; |
1083 | //CRM-14334 | |
1084 | if ($value === NULL || $value == '') { | |
1085 | $value = 'null'; | |
1086 | } | |
1087 | if ($value === 0 or $value === '0') { | |
1088 | $value = $qfZeroBug; | |
1089 | } | |
1090 | if (is_array($value) && empty($value[1])) { | |
1091 | $value[1] = NULL; | |
1092 | } | |
13919cf8 | 1093 | |
bdc6e6ee | 1094 | // Display a checkbox to migrate, only if the values are different |
1095 | if ($value != $main[$field]) { | |
1096 | $elements[] = [ | |
3d1d395a | 1097 | 0 => 'advcheckbox', |
1098 | 1 => "move_$field", | |
1099 | 2 => NULL, | |
1100 | 3 => NULL, | |
1101 | 4 => NULL, | |
1102 | 5 => $value, | |
1103 | 'is_checked' => (!isset($main[$field]) || $main[$field] === ''), | |
bdc6e6ee | 1104 | ]; |
1105 | } | |
13919cf8 | 1106 | |
bdc6e6ee | 1107 | $migrationInfo["move_$field"] = $value; |
6a488035 TO |
1108 | } |
1109 | ||
eb61dc07 J |
1110 | // Handle location blocks. |
1111 | // @todo OpenID not in API yet, so is not supported here. | |
65a35632 | 1112 | |
087f00ec | 1113 | // Set up useful information about the location blocks |
34917198 | 1114 | $locationBlocks = self::getLocationBlockInfo(); |
087f00ec | 1115 | |
1a90ac89 | 1116 | $locations = ['main' => [], 'other' => []]; |
6a488035 | 1117 | |
087f00ec | 1118 | foreach ($locationBlocks as $blockName => $blockInfo) { |
6a488035 | 1119 | |
087f00ec J |
1120 | // Collect existing fields from both 'main' and 'other' contacts first |
1121 | // This allows us to match up location/types when building the table rows | |
1a90ac89 | 1122 | $locations['main'][$blockName] = self::buildLocationBlockForContact($mainId, $blockInfo, $blockName); |
1123 | $locations['other'][$blockName] = self::buildLocationBlockForContact($otherId, $blockInfo, $blockName); | |
6a488035 | 1124 | |
087f00ec J |
1125 | // Now, build the table rows appropriately, based off the information on |
1126 | // the 'other' contact | |
34917198 J |
1127 | if (!empty($locations['other']) && !empty($locations['other'][$blockName])) { |
1128 | foreach ($locations['other'][$blockName] as $count => $value) { | |
6a488035 | 1129 | |
087f00ec | 1130 | $displayValue = $value[$blockInfo['displayField']]; |
65a35632 | 1131 | |
087f00ec J |
1132 | // Add this value to the table rows |
1133 | $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue; | |
65a35632 | 1134 | |
087f00ec J |
1135 | // CRM-17556 Only display 'main' contact value if it's the same location + type |
1136 | // Look it up from main values... | |
65a35632 | 1137 | |
087f00ec J |
1138 | $lookupLocation = FALSE; |
1139 | if ($blockInfo['hasLocation']) { | |
1140 | $lookupLocation = $value['location_type_id']; | |
1141 | } | |
65a35632 | 1142 | |
087f00ec J |
1143 | $lookupType = FALSE; |
1144 | if ($blockInfo['hasType']) { | |
13cc4cac | 1145 | $lookupType = CRM_Utils_Array::value($blockInfo['hasType'], $value); |
087f00ec | 1146 | } |
65a35632 | 1147 | |
34917198 J |
1148 | // Hold ID of main contact's matching block |
1149 | $mainContactBlockId = 0; | |
1150 | ||
087f00ec J |
1151 | if (!empty($locations['main'][$blockName])) { |
1152 | foreach ($locations['main'][$blockName] as $mainValueCheck) { | |
1153 | // No location/type, or matching location and type | |
1154 | if ( | |
1155 | (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id']) | |
1156 | && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']]) | |
1157 | ) { | |
34917198 | 1158 | // Set this value as the default against the 'other' contact value |
087f00ec | 1159 | $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']]; |
041d6d6b | 1160 | $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary']; |
86b14b59 | 1161 | $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName; |
34917198 | 1162 | $mainContactBlockId = $mainValueCheck['id']; |
087f00ec J |
1163 | break; |
1164 | } | |
6a488035 | 1165 | } |
087f00ec | 1166 | } |
65a35632 | 1167 | |
087f00ec | 1168 | // Add checkbox to migrate data from 'other' to 'main' |
2c16165a | 1169 | $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"]; |
65a35632 | 1170 | |
abd0b852 | 1171 | // Add checkbox to set the 'other' location as primary |
2c16165a | 1172 | $elements[] = [ |
1173 | 'advcheckbox', | |
1174 | "location_blocks[$blockName][$count][set_other_primary]", | |
1175 | NULL, | |
1176 | ts('Set as primary'), | |
1177 | ]; | |
abd0b852 | 1178 | |
087f00ec J |
1179 | // Flag up this field to skipMerge function (@todo: do we need to?) |
1180 | $migrationInfo["move_location_{$blockName}_{$count}"] = 1; | |
65a35632 | 1181 | |
34917198 | 1182 | // Add a hidden field to store the ID of the target main contact block |
2c16165a | 1183 | $elements[] = [ |
1184 | 'hidden', | |
1185 | "location_blocks[$blockName][$count][mainContactBlockId]", | |
1186 | $mainContactBlockId, | |
1187 | ]; | |
34917198 | 1188 | |
087f00ec J |
1189 | // Setup variables |
1190 | $thisTypeId = FALSE; | |
1191 | $thisLocId = FALSE; | |
65a35632 | 1192 | |
087f00ec J |
1193 | // Provide a select drop-down for the location's location type |
1194 | // eg: Home, Work... | |
65a35632 | 1195 | |
087f00ec J |
1196 | if ($blockInfo['hasLocation']) { |
1197 | ||
5b28be84 | 1198 | // Load the location options for this entity |
2c16165a | 1199 | $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']); |
5b28be84 | 1200 | |
087f00ec J |
1201 | $thisLocId = $value['location_type_id']; |
1202 | ||
1203 | // Put this field's location type at the top of the list | |
5b28be84 | 1204 | $tmpIdList = $locationOptions['values']; |
2c16165a | 1205 | $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]]; |
087f00ec J |
1206 | unset($tmpIdList[$thisLocId]); |
1207 | ||
1208 | // Add the element | |
2c16165a | 1209 | $elements[] = [ |
eb61dc07 | 1210 | 'select', |
972947a7 | 1211 | "location_blocks[$blockName][$count][locTypeId]", |
eb61dc07 | 1212 | NULL, |
087f00ec | 1213 | $defaultLocId + $tmpIdList, |
2c16165a | 1214 | ]; |
087f00ec J |
1215 | |
1216 | // Add the relevant information to the $migrationInfo | |
1217 | // Keep location-type-id same as that of other-contact | |
1218 | // @todo Check this logic out | |
1219 | $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId; | |
abb422f9 | 1220 | if ($blockName != 'address') { |
2c16165a | 1221 | $elements[] = [ |
1222 | 'advcheckbox', | |
1223 | "location_blocks[{$blockName}][$count][operation]", | |
1224 | NULL, | |
1225 | ts('Add new'), | |
1226 | ]; | |
087f00ec | 1227 | // always use add operation |
abb422f9 | 1228 | $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1; |
6a488035 | 1229 | } |
087f00ec | 1230 | |
6a488035 | 1231 | } |
6a488035 | 1232 | |
087f00ec J |
1233 | // Provide a select drop-down for the location's type/provider |
1234 | // eg websites: Google+, Facebook... | |
1235 | ||
087f00ec J |
1236 | if ($blockInfo['hasType']) { |
1237 | ||
5b28be84 | 1238 | // Load the type options for this entity |
2c16165a | 1239 | $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]); |
5b28be84 | 1240 | |
13cc4cac | 1241 | $thisTypeId = CRM_Utils_Array::value($blockInfo['hasType'], $value); |
087f00ec J |
1242 | |
1243 | // Put this field's location type at the top of the list | |
5b28be84 | 1244 | $tmpIdList = $typeOptions['values']; |
2c16165a | 1245 | $defaultTypeId = [$thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList)]; |
087f00ec J |
1246 | unset($tmpIdList[$thisTypeId]); |
1247 | ||
1248 | // Add the element | |
2c16165a | 1249 | $elements[] = [ |
65a35632 | 1250 | 'select', |
972947a7 | 1251 | "location_blocks[$blockName][$count][typeTypeId]", |
65a35632 | 1252 | NULL, |
087f00ec | 1253 | $defaultTypeId + $tmpIdList, |
2c16165a | 1254 | ]; |
65a35632 | 1255 | |
1e3e0eed | 1256 | // Add the information to the migrationInfo |
34917198 | 1257 | $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId; |
65a35632 | 1258 | |
6a488035 | 1259 | } |
087f00ec J |
1260 | |
1261 | // Set the label for this row | |
34917198 J |
1262 | $rowTitle = $blockInfo['label'] . ' ' . ($count + 1); |
1263 | if (!empty($thisLocId)) { | |
5b28be84 | 1264 | $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')'; |
6a488035 | 1265 | } |
34917198 | 1266 | if (!empty($thisTypeId)) { |
5b28be84 | 1267 | $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')'; |
34917198 J |
1268 | } |
1269 | $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle; | |
65a35632 | 1270 | |
34917198 | 1271 | } // End loop through 'other' locations of this type |
087f00ec | 1272 | |
34917198 | 1273 | } // End if 'other' location for this type exists |
6a488035 | 1274 | |
34917198 | 1275 | } // End loop through each location block entity |
6a488035 TO |
1276 | |
1277 | // add the related tables and unset the ones that don't sport any of the duplicate contact's info | |
1278 | $config = CRM_Core_Config::singleton(); | |
1279 | $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId); | |
1280 | $mainUser = NULL; | |
1281 | if ($mainUfId) { | |
1282 | // d6 compatible | |
1283 | if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { | |
1284 | $mainUser = user_load($mainUfId); | |
1285 | } | |
1286 | elseif ($config->userFramework == 'Joomla') { | |
1287 | $mainUser = JFactory::getUser($mainUfId); | |
1288 | } | |
1289 | } | |
1290 | $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId); | |
1291 | $otherUser = NULL; | |
1292 | if ($otherUfId) { | |
1293 | // d6 compatible | |
1294 | if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { | |
1295 | $otherUser = user_load($otherUfId); | |
1296 | } | |
1297 | elseif ($config->userFramework == 'Joomla') { | |
1298 | $otherUser = JFactory::getUser($otherUfId); | |
1299 | } | |
1300 | } | |
1301 | ||
9287a0b7 | 1302 | $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId); |
1303 | $relTables = $mergeHandler->getTablesRelatedToTheMergePair(); | |
6a488035 | 1304 | foreach ($relTables as $name => $null) { |
2c16165a | 1305 | $relTableElements[] = ['checkbox', "move_$name"]; |
6a488035 TO |
1306 | $migrationInfo["move_$name"] = 1; |
1307 | ||
1308 | $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']); | |
1309 | $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']); | |
1310 | if ($name == 'rel_table_users') { | |
1311 | $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']); | |
1312 | $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']); | |
2c16165a | 1313 | $find = ['$ufid', '$ufname']; |
6a488035 | 1314 | if ($mainUser) { |
2c16165a | 1315 | $replace = [$mainUfId, $mainUser->name]; |
6a488035 TO |
1316 | $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']); |
1317 | } | |
1318 | if ($otherUser) { | |
2c16165a | 1319 | $replace = [$otherUfId, $otherUser->name]; |
6a488035 TO |
1320 | $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']); |
1321 | } | |
1322 | } | |
1323 | if ($name == 'rel_table_memberships') { | |
7d84a47d JP |
1324 | //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact. |
1325 | $attributes = ['checked' => 'checked']; | |
1326 | $otherContactMemberships = CRM_Member_BAO_Membership::getAllContactMembership($otherId); | |
1327 | foreach ($otherContactMemberships as $membership) { | |
1328 | $mainMembership = CRM_Member_BAO_Membership::getContactMembership($mainId, $membership['membership_type_id'], FALSE); | |
1329 | if ($mainMembership) { | |
1330 | $attributes = []; | |
1331 | } | |
1332 | } | |
2c16165a | 1333 | $elements[] = [ |
1334 | 'checkbox', | |
1335 | "operation[move_{$name}][add]", | |
1336 | NULL, | |
1337 | ts('add new'), | |
1338 | $attributes, | |
1339 | ]; | |
6a488035 TO |
1340 | $migrationInfo["operation"]["move_{$name}"]['add'] = 1; |
1341 | } | |
1342 | } | |
1343 | foreach ($relTables as $name => $null) { | |
1344 | $relTables["move_$name"] = $relTables[$name]; | |
1345 | unset($relTables[$name]); | |
1346 | } | |
1347 | ||
1348 | // handle custom fields | |
201057c0 | 1349 | $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1, |
1350 | CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions | |
6a488035 | 1351 | ); |
0b330e6d | 1352 | $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1, |
201057c0 | 1353 | CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions |
6a488035 | 1354 | ); |
6a488035 TO |
1355 | |
1356 | foreach ($otherTree as $gid => $group) { | |
1357 | $foundField = FALSE; | |
1358 | if (!isset($group['fields'])) { | |
1359 | continue; | |
1360 | } | |
1361 | ||
1362 | foreach ($group['fields'] as $fid => $field) { | |
4eea8606 | 1363 | if (in_array($fid, $compareFields['custom'])) { |
6a488035 TO |
1364 | if (!$foundField) { |
1365 | $rows["custom_group_$gid"]['title'] = $group['title']; | |
1366 | $foundField = TRUE; | |
1367 | } | |
a7488080 | 1368 | if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) { |
6a488035 | 1369 | foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { |
51a3717f | 1370 | $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid); |
6a488035 TO |
1371 | } |
1372 | } | |
1373 | $value = "null"; | |
a7488080 | 1374 | if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) { |
6a488035 | 1375 | foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { |
51a3717f | 1376 | $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid); |
6a488035 TO |
1377 | if ($values['data'] === 0 || $values['data'] === '0') { |
1378 | $values['data'] = $qfZeroBug; | |
d58a19a1 | 1379 | } |
6a488035 | 1380 | $value = ($values['data']) ? $values['data'] : $value; |
d58a19a1 | 1381 | } |
6a488035 TO |
1382 | } |
1383 | $rows["move_custom_$fid"]['title'] = $field['label']; | |
1384 | ||
2c16165a | 1385 | $elements[] = [ |
1386 | 'advcheckbox', | |
1387 | "move_custom_$fid", | |
1388 | NULL, | |
1389 | NULL, | |
1390 | NULL, | |
1391 | $value, | |
1392 | ]; | |
6a488035 TO |
1393 | $migrationInfo["move_custom_$fid"] = $value; |
1394 | } | |
1395 | } | |
1396 | } | |
abb422f9 | 1397 | |
2c16165a | 1398 | $result = [ |
6a488035 TO |
1399 | 'rows' => $rows, |
1400 | 'elements' => $elements, | |
1401 | 'rel_table_elements' => $relTableElements, | |
6a488035 TO |
1402 | 'rel_tables' => $relTables, |
1403 | 'main_details' => $main, | |
1404 | 'other_details' => $other, | |
1405 | 'migration_info' => $migrationInfo, | |
2c16165a | 1406 | ]; |
6a488035 | 1407 | |
34917198 J |
1408 | $result['main_details']['location_blocks'] = $locations['main']; |
1409 | $result['other_details']['location_blocks'] = $locations['other']; | |
6a488035 TO |
1410 | |
1411 | return $result; | |
1412 | } | |
1413 | ||
1414 | /** | |
1415 | * Based on the provided two contact_ids and a set of tables, move the belongings of the | |
1416 | * other contact to the main one - be it Location / CustomFields or Contact .. related info. | |
1417 | * A superset of moveContactBelongings() function. | |
1418 | * | |
98997235 TO |
1419 | * @param int $mainId |
1420 | * Main contact with whom merge has to happen. | |
1421 | * @param int $otherId | |
1422 | * Duplicate contact which would be deleted after merge operation. | |
77b97be7 | 1423 | * |
1600a9c0 | 1424 | * @param array $migrationInfo |
6a488035 | 1425 | * |
3058f4d9 | 1426 | * @param bool $checkPermissions |
1427 | * Respect logged in user permissions. | |
1428 | * | |
77b97be7 | 1429 | * @return bool |
1600a9c0 | 1430 | * @throws \CiviCRM_API3_Exception |
6a488035 | 1431 | */ |
3058f4d9 | 1432 | public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) { |
6a488035 TO |
1433 | if (empty($migrationInfo)) { |
1434 | return FALSE; | |
1435 | } | |
119664d6 | 1436 | // Encapsulate in a transaction to avoid half-merges. |
1437 | $transaction = new CRM_Core_Transaction(); | |
6a488035 | 1438 | |
1acd98ec | 1439 | $contactType = $migrationInfo['main_details']['contact_type']; |
6a488035 | 1440 | $relTables = CRM_Dedupe_Merger::relTables(); |
35e0e03e | 1441 | $submittedCustomFields = $moveTables = $tableOperations = $removeTables = []; |
ae2346d4 | 1442 | |
54ed517e | 1443 | self::swapOutFieldsAffectedByQFZeroBug($migrationInfo); |
6a488035 | 1444 | foreach ($migrationInfo as $key => $value) { |
08b00099 CR |
1445 | |
1446 | if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) { | |
6a488035 | 1447 | $submitted[substr($key, 5)] = $value; |
ae2346d4 | 1448 | $submittedCustomFields[] = substr($key, 12); |
6a488035 | 1449 | } |
08b00099 | 1450 | elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) { |
6a488035 TO |
1451 | $submitted[substr($key, 5)] = $value; |
1452 | } | |
6a488035 TO |
1453 | elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') { |
1454 | $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']); | |
1455 | if (array_key_exists('operation', $migrationInfo)) { | |
1456 | foreach ($relTables[substr($key, 5)]['tables'] as $table) { | |
1457 | if (array_key_exists($key, $migrationInfo['operation'])) { | |
1458 | $tableOperations[$table] = $migrationInfo['operation'][$key]; | |
1459 | } | |
1460 | } | |
1461 | } | |
1462 | } | |
4099a9c5 AP |
1463 | elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') { |
1464 | $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']); | |
1465 | } | |
6a488035 | 1466 | } |
35e0e03e | 1467 | self::mergeLocations($mainId, $otherId, $migrationInfo); |
6a488035 | 1468 | |
6a488035 | 1469 | // **** Do contact related migrations |
ae2346d4 | 1470 | $customTablesToCopyValues = self::getAffectedCustomTables($submittedCustomFields); |
1600a9c0 | 1471 | // @todo - move all custom field processing to the move class & eventually have an |
1472 | // overridable DAO class for it. | |
1473 | $customFieldBAO = new CRM_Core_BAO_CustomField(); | |
1474 | $customFieldBAO->move($otherId, $mainId, $submittedCustomFields); | |
0556db5d CR |
1475 | CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues); |
1476 | unset($moveTables, $tableOperations); | |
6a488035 | 1477 | |
4099a9c5 AP |
1478 | // **** Do table related removals |
1479 | if (!empty($removeTables)) { | |
1480 | // **** CRM-20421 | |
1481 | CRM_Dedupe_Merger::removeContactBelongings($otherId, $removeTables); | |
2c16165a | 1482 | $removeTables = []; |
4099a9c5 AP |
1483 | } |
1484 | ||
6a488035 | 1485 | // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact() |
2c16165a | 1486 | $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender']; |
1487 | $names['individual_prefix'] = [ | |
1488 | 'newName' => 'prefix_id', | |
1489 | 'groupName' => 'individual_prefix', | |
1490 | ]; | |
1491 | $names['individual_suffix'] = [ | |
1492 | 'newName' => 'suffix_id', | |
1493 | 'groupName' => 'individual_suffix', | |
1494 | ]; | |
1495 | $names['communication_style'] = [ | |
1496 | 'newName' => 'communication_style_id', | |
1497 | 'groupName' => 'communication_style', | |
1498 | ]; | |
1499 | $names['addressee'] = [ | |
1500 | 'newName' => 'addressee_id', | |
1501 | 'groupName' => 'addressee', | |
1502 | ]; | |
1503 | $names['email_greeting'] = [ | |
1504 | 'newName' => 'email_greeting_id', | |
1505 | 'groupName' => 'email_greeting', | |
1506 | ]; | |
1507 | $names['postal_greeting'] = [ | |
1508 | 'newName' => 'postal_greeting_id', | |
1509 | 'groupName' => 'postal_greeting', | |
1510 | ]; | |
6a488035 | 1511 | CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE); |
6a488035 | 1512 | // fix custom fields so they're edible by createProfileContact() |
f941d73a | 1513 | $cFields = self::getCustomFieldMetadata($contactType); |
6a488035 TO |
1514 | |
1515 | if (!isset($submitted)) { | |
2c16165a | 1516 | $submitted = []; |
6a488035 TO |
1517 | } |
1518 | foreach ($submitted as $key => $value) { | |
1600a9c0 | 1519 | list($cFields, $submitted) = self::processCustomFields($mainId, $key, $cFields, $submitted, $value); |
6a488035 TO |
1520 | } |
1521 | ||
6a488035 | 1522 | // move view only custom fields CRM-5362 |
2c16165a | 1523 | $viewOnlyCustomFields = []; |
6a488035 | 1524 | foreach ($submitted as $key => $value) { |
ca38a45b | 1525 | $fid = CRM_Core_BAO_CustomField::getKeyID($key); |
1526 | if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view']) | |
1527 | ) { | |
6a488035 TO |
1528 | $viewOnlyCustomFields[$key] = $value; |
1529 | } | |
1530 | } | |
6a488035 TO |
1531 | // special case to set values for view only, CRM-5362 |
1532 | if (!empty($viewOnlyCustomFields)) { | |
1533 | $viewOnlyCustomFields['entityID'] = $mainId; | |
1534 | CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields); | |
1535 | } | |
1536 | ||
1f0138dd SL |
1537 | // dev/core#996 Ensure that the earliest created date is stored against the kept contact id |
1538 | $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [ | |
1539 | 'id' => $mainId, | |
1540 | 'return' => ['created_date'], | |
1541 | ])['created_date']; | |
1542 | $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [ | |
1543 | 'id' => $otherId, | |
1544 | 'return' => ['created_date'], | |
1545 | ])['created_date']; | |
1546 | if ($otherCreatedDate < $mainCreatedDate) { | |
1547 | CRM_Core_DAO::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [ | |
1548 | 1 => [$otherCreatedDate, 'String'], | |
1549 | 2 => [$mainId, 'Positive'], | |
1550 | ]); | |
1551 | } | |
1552 | ||
3058f4d9 | 1553 | if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') && |
2c16165a | 1554 | CRM_Core_Permission::check('delete contacts')) |
6a488035 TO |
1555 | ) { |
1556 | // if ext id is submitted then set it null for contact to be deleted | |
a7488080 | 1557 | if (!empty($submitted['external_identifier'])) { |
6a488035 TO |
1558 | $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}"; |
1559 | CRM_Core_DAO::executeQuery($query); | |
1560 | } | |
2c16165a | 1561 | civicrm_api3('contact', 'delete', ['id' => $otherId]); |
6a488035 | 1562 | } |
6a488035 | 1563 | |
4d5f18cc | 1564 | // CRM-15681 merge sub_types |
35522279 J |
1565 | if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) { |
1566 | if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) { | |
481a74f4 | 1567 | $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types)); |
0db6c3e1 TO |
1568 | } |
1569 | else { | |
4d5f18cc | 1570 | $submitted['contact_sub_type'] = $other_sub_types; |
1571 | } | |
1572 | } | |
1573 | ||
6a488035 TO |
1574 | // **** Update contact related info for the main contact |
1575 | if (!empty($submitted)) { | |
1576 | $submitted['contact_id'] = $mainId; | |
1577 | ||
1578 | //update current employer field | |
1579 | if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) { | |
1580 | if (!CRM_Utils_System::isNull($currentEmloyerId)) { | |
1581 | $submitted['current_employer'] = $submitted['current_employer_id']; | |
0db6c3e1 TO |
1582 | } |
1583 | else { | |
6a488035 TO |
1584 | $submitted['current_employer'] = ''; |
1585 | } | |
1586 | unset($submitted['current_employer_id']); | |
1587 | } | |
1588 | ||
00f3da2e | 1589 | //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name |
481a74f4 | 1590 | if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) { |
00f3da2e BS |
1591 | $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id']; |
1592 | } | |
481a74f4 | 1593 | if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) { |
00f3da2e BS |
1594 | $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id']; |
1595 | } | |
9b0e7e51 | 1596 | $null = []; |
1597 | CRM_Contact_BAO_Contact::createProfileContact($submitted, $null, $mainId); | |
6a488035 | 1598 | } |
119664d6 | 1599 | $transaction->commit(); |
1273d77c | 1600 | CRM_Utils_Hook::post('merge', 'Contact', $mainId); |
f00283b5 | 1601 | self::createMergeActivities($mainId, $otherId); |
5ea06a7b | 1602 | |
6a488035 TO |
1603 | return TRUE; |
1604 | } | |
16254ae1 | 1605 | |
ae2346d4 CR |
1606 | /** |
1607 | * Builds an Array of Custom tables for given custom field ID's. | |
1608 | * | |
1609 | * @param $customFieldIDs | |
1610 | * | |
1611 | * @return array | |
1612 | * Array of custom table names | |
1613 | */ | |
1614 | private static function getAffectedCustomTables($customFieldIDs) { | |
2c16165a | 1615 | $customTableToCopyValues = []; |
ae2346d4 CR |
1616 | |
1617 | foreach ($customFieldIDs as $fieldID) { | |
1618 | if (!empty($fieldID)) { | |
2c16165a | 1619 | $customField = civicrm_api3('custom_field', 'getsingle', [ |
08b00099 CR |
1620 | 'id' => $fieldID, |
1621 | 'is_active' => TRUE, | |
2c16165a | 1622 | ]); |
08b00099 | 1623 | if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) { |
2c16165a | 1624 | $customGroup = civicrm_api3('custom_group', 'getsingle', [ |
08b00099 | 1625 | 'id' => $customField['custom_group_id'], |
ae2346d4 | 1626 | 'is_active' => TRUE, |
2c16165a | 1627 | ]); |
ae2346d4 CR |
1628 | |
1629 | if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) { | |
1630 | $customTableToCopyValues[] = $customGroup['table_name']; | |
1631 | } | |
1632 | } | |
1633 | } | |
1634 | } | |
1635 | ||
1636 | return $customTableToCopyValues; | |
1637 | } | |
1638 | ||
16254ae1 | 1639 | /** |
f00283b5 | 1640 | * Get fields in the contact table suitable for merging. |
1641 | * | |
a6c01b45 | 1642 | * @return array |
f00283b5 | 1643 | * Array of field names to be potentially merged. |
16254ae1 | 1644 | */ |
00be9182 | 1645 | public static function getContactFields() { |
16254ae1 | 1646 | $contactFields = CRM_Contact_DAO_Contact::fields(); |
2c16165a | 1647 | $invalidFields = [ |
353ffa53 | 1648 | 'api_key', |
353ffa53 TO |
1649 | 'created_date', |
1650 | 'display_name', | |
1651 | 'hash', | |
1652 | 'id', | |
1653 | 'modified_date', | |
1654 | 'primary_contact_id', | |
1655 | 'sort_name', | |
c301f76e | 1656 | 'user_unique_id', |
2c16165a | 1657 | ]; |
bdd7870e RN |
1658 | foreach ($contactFields as $field => $value) { |
1659 | if (in_array($field, $invalidFields)) { | |
1660 | unset($contactFields[$field]); | |
1661 | } | |
1662 | } | |
16254ae1 ARW |
1663 | return array_keys($contactFields); |
1664 | } | |
ada104d5 AW |
1665 | |
1666 | /** | |
1667 | * Added for CRM-12695 | |
c301f76e | 1668 | * Based on the contactID provided |
ada104d5 AW |
1669 | * add/update membership(s) to related contacts |
1670 | * | |
c301f76e | 1671 | * @param int $contactID |
ada104d5 | 1672 | */ |
00be9182 | 1673 | public static function addMembershipToRealtedContacts($contactID) { |
ada104d5 AW |
1674 | $dao = new CRM_Member_DAO_Membership(); |
1675 | $dao->contact_id = $contactID; | |
1676 | $dao->is_test = 0; | |
1677 | $dao->find(); | |
1678 | ||
1679 | //checks membership of contact itself | |
1680 | while ($dao->fetch()) { | |
1681 | $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id'); | |
1682 | if ($relationshipTypeId) { | |
2c16165a | 1683 | $membershipParams = [ |
ada104d5 AW |
1684 | 'id' => $dao->id, |
1685 | 'contact_id' => $dao->contact_id, | |
1686 | 'membership_type_id' => $dao->membership_type_id, | |
1687 | 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date), | |
1688 | 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date), | |
1689 | 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date), | |
1690 | 'source' => $dao->source, | |
21dfd5f5 | 1691 | 'status_id' => $dao->status_id, |
2c16165a | 1692 | ]; |
ada104d5 AW |
1693 | // create/update membership(s) for related contact(s) |
1694 | CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao); | |
1695 | } // end of if relationshipTypeId | |
1696 | } | |
1697 | } | |
96025800 | 1698 | |
f00283b5 | 1699 | /** |
1700 | * Create activities tracking the merge on affected contacts. | |
1701 | * | |
1702 | * @param int $mainId | |
1703 | * @param int $otherId | |
1704 | * | |
1705 | * @throws \CiviCRM_API3_Exception | |
1706 | */ | |
1707 | public static function createMergeActivities($mainId, $otherId) { | |
2c16165a | 1708 | $params = [ |
f00283b5 | 1709 | 1 => $otherId, |
1710 | 2 => $mainId, | |
2c16165a | 1711 | ]; |
1712 | $activity = civicrm_api3('activity', 'create', [ | |
dc33398e | 1713 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : |
518fa0ee | 1714 | $mainId, |
f00283b5 | 1715 | 'subject' => ts('Contact ID %1 has been merged and deleted.', $params), |
1716 | 'target_contact_id' => $mainId, | |
1717 | 'activity_type_id' => 'Contact Merged', | |
1718 | 'status_id' => 'Completed', | |
2c16165a | 1719 | ]); |
1720 | if (civicrm_api3('Setting', 'getvalue', [ | |
1721 | 'name' => 'contact_undelete', | |
1722 | 'group' => 'CiviCRM Preferences', | |
1723 | ])) { | |
1724 | civicrm_api3('activity', 'create', [ | |
dc33398e | 1725 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : |
518fa0ee | 1726 | $otherId, |
4d834a99 | 1727 | 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params), |
1728 | 'target_contact_id' => $otherId, | |
1729 | 'activity_type_id' => 'Contact Deleted by Merge', | |
1730 | 'parent_id' => $activity['id'], | |
1731 | 'status_id' => 'Completed', | |
2c16165a | 1732 | ]); |
4d834a99 | 1733 | } |
f00283b5 | 1734 | } |
1735 | ||
2988f5c7 | 1736 | /** |
1737 | * Get Duplicate Pairs based on a rule for a group. | |
1738 | * | |
1739 | * @param int $rule_group_id | |
1740 | * @param int $group_id | |
1741 | * @param bool $reloadCacheIfEmpty | |
917acf6f | 1742 | * Should the cache be reloaded if empty - this must be false when in a dedupe action! |
2988f5c7 | 1743 | * @param int $batchLimit |
1744 | * @param bool $isSelected | |
5721d85e | 1745 | * Limit to selected pairs. |
66eceb0b | 1746 | * @param bool $includeConflicts |
e23e26ec | 1747 | * @param array $criteria |
1748 | * Additional criteria to narrow down the merge group. | |
2988f5c7 | 1749 | * |
3058f4d9 | 1750 | * @param bool $checkPermissions |
1751 | * Respect logged in user permissions. | |
1752 | * | |
21a95d83 | 1753 | * @param int $searchLimit |
1754 | * Limit to searching for matches against this many contacts. | |
1755 | * | |
c41f68a5 | 1756 | * @param int $isForceNewSearch |
1757 | * Should a new search be forced, bypassing any cache retrieval. | |
1758 | * | |
2988f5c7 | 1759 | * @return array |
518fa0ee | 1760 | * Array of matches meeting the criteria. |
9c5fe572 | 1761 | * |
1762 | * @throws \CRM_Core_Exception | |
1763 | * @throws \CiviCRM_API3_Exception | |
2988f5c7 | 1764 | */ |
c41f68a5 | 1765 | public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0, $isForceNewSearch = 0) { |
1766 | $dupePairs = $isForceNewSearch ? [] : self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit); | |
2988f5c7 | 1767 | if (empty($dupePairs) && $reloadCacheIfEmpty) { |
1768 | // If we haven't found any dupes, probably cache is empty. | |
66eceb0b | 1769 | // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any |
1770 | // until we have done some processing. | |
e1e24a57 | 1771 | CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit); |
997a03fe | 1772 | return self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions, $searchLimit); |
2988f5c7 | 1773 | } |
1774 | return $dupePairs; | |
1775 | } | |
1776 | ||
2ae26001 | 1777 | /** |
1778 | * Get the cache key string for the merge action. | |
1779 | * | |
1780 | * @param int $rule_group_id | |
1781 | * @param int $group_id | |
e23e26ec | 1782 | * @param array $criteria |
1783 | * Additional criteria to narrow down the merge group. | |
1784 | * Currently we are only supporting the key 'contact' within it. | |
3058f4d9 | 1785 | * @param bool $checkPermissions |
1786 | * Respect the users permissions. | |
997a03fe | 1787 | * @param int $searchLimit |
1788 | * Number of contacts to seek dupes for (we need this because if | |
1789 | * we change it the results won't be refreshed otherwise. Changing the limit | |
1790 | * from 100 to 1000 SHOULD result in a new dedupe search). | |
3058f4d9 | 1791 | * |
2ae26001 | 1792 | * @return string |
1793 | */ | |
997a03fe | 1794 | public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit) { |
2ae26001 | 1795 | $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id); |
9d2f6d53 | 1796 | $cacheKeyString = "merge_{$contactType}"; |
2ae26001 | 1797 | $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0'; |
1798 | $cacheKeyString .= $group_id ? "_{$group_id}" : '_0'; | |
997a03fe | 1799 | $cacheKeyString .= '_' . (int) $searchLimit; |
629dd4f3 | 1800 | $cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0'; |
3058f4d9 | 1801 | if ($checkPermissions) { |
1802 | $contactID = CRM_Core_Session::getLoggedInContactID(); | |
1803 | if (!$contactID) { | |
1804 | // Distinguish between no permission check & no logged in user. | |
1805 | $contactID = 'null'; | |
1806 | } | |
1807 | $cacheKeyString .= '_' . $contactID; | |
1808 | } | |
1809 | else { | |
1810 | $cacheKeyString .= '_0'; | |
1811 | } | |
2ae26001 | 1812 | return $cacheKeyString; |
1813 | } | |
1814 | ||
74a6069d | 1815 | /** |
1816 | * Get the metadata for the merge fields. | |
1817 | * | |
1818 | * This is basically the contact metadata, augmented with fields to | |
1819 | * represent email greeting, postal greeting & addressee. | |
1820 | * | |
1821 | * @return array | |
1822 | */ | |
1823 | public static function getMergeFieldsMetadata() { | |
1824 | if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) { | |
1825 | return \Civi::$statics[__CLASS__]['merge_fields_metadata']; | |
1826 | } | |
1827 | $fields = CRM_Contact_DAO_Contact::fields(); | |
2c16165a | 1828 | static $optionValueFields = []; |
74a6069d | 1829 | if (empty($optionValueFields)) { |
1830 | $optionValueFields = CRM_Core_OptionValue::getFields(); | |
1831 | } | |
1832 | foreach ($optionValueFields as $field => $params) { | |
1833 | $fields[$field]['title'] = $params['title']; | |
1834 | } | |
1835 | \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields; | |
1836 | return \Civi::$statics[__CLASS__]['merge_fields_metadata']; | |
1837 | } | |
1838 | ||
1839 | /** | |
1840 | * Get the details of the contact to be merged. | |
1841 | * | |
1842 | * @param int $contact_id | |
74a6069d | 1843 | * |
1844 | * @return array | |
1845 | * | |
1846 | * @throws CRM_Core_Exception | |
1847 | */ | |
fcc3d8ee | 1848 | public static function getMergeContactDetails($contact_id) { |
2c16165a | 1849 | $params = [ |
74a6069d | 1850 | 'contact_id' => $contact_id, |
1851 | 'version' => 3, | |
2c16165a | 1852 | 'return' => array_merge(['display_name'], self::getContactFields()), |
1853 | ]; | |
74a6069d | 1854 | $result = civicrm_api('contact', 'get', $params); |
1855 | ||
1856 | // CRM-18480: Cancel the process if the contact is already deleted | |
1857 | if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) { | |
2c16165a | 1858 | throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [ |
fcc3d8ee | 1859 | 1 => $contact_id, |
2c16165a | 1860 | ])); |
74a6069d | 1861 | } |
1862 | ||
1863 | return $result['values'][$contact_id]; | |
1864 | } | |
1865 | ||
92a77772 | 1866 | /** |
1867 | * Merge location. | |
1868 | * | |
1869 | * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts. | |
1870 | * | |
1871 | * The data is in the format received from the merge form (which is a fairly confusing format). | |
1872 | * | |
1873 | * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook | |
1874 | * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have | |
1875 | * been calculated and before saving because | |
1876 | * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile | |
1877 | * - passing to a hook right before save means calculations only have to be done once | |
1878 | * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just | |
1879 | * ugly. | |
1880 | * | |
1881 | * The use of the new hook is tested, including the fact it is called before contributions are merged, as this | |
16d4e0b7 | 1882 | * is likely to be significant data in merge hooks. |
92a77772 | 1883 | * |
1884 | * @param int $mainId | |
1885 | * @param int $otherId | |
92a77772 | 1886 | * |
1887 | * @param array $migrationInfo | |
1888 | * Migration info for the merge. This is passed to the hook as informational only. | |
1889 | */ | |
35e0e03e | 1890 | public static function mergeLocations($mainId, $otherId, $migrationInfo) { |
1891 | foreach ($migrationInfo as $key => $value) { | |
1892 | $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL); | |
1893 | if (!$isLocationField) { | |
1894 | continue; | |
1895 | } | |
92a77772 | 1896 | $locField = explode('_', $key); |
1897 | $fieldName = $locField[2]; | |
1898 | $fieldCount = $locField[3]; | |
1899 | ||
1900 | // Set up the operation type (add/overwrite) | |
1901 | // Ignore operation for websites | |
1902 | // @todo Tidy this up | |
1903 | $operation = 0; | |
1904 | if ($fieldName != 'website') { | |
1905 | $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]); | |
1906 | } | |
1907 | // default operation is overwrite. | |
1908 | if (!$operation) { | |
1909 | $operation = 2; | |
1910 | } | |
1911 | $locBlocks[$fieldName][$fieldCount]['operation'] = $operation; | |
1912 | } | |
2c16165a | 1913 | $blocksDAO = []; |
92a77772 | 1914 | |
1915 | // @todo Handle OpenID (not currently in API). | |
1916 | if (!empty($locBlocks)) { | |
1917 | $locationBlocks = self::getLocationBlockInfo(); | |
1918 | ||
2c16165a | 1919 | $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_primary' => 1]); |
1920 | $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_billing' => 1]); | |
92a77772 | 1921 | |
1922 | foreach ($locBlocks as $name => $block) { | |
2c16165a | 1923 | $blocksDAO[$name] = ['delete' => [], 'update' => []]; |
92a77772 | 1924 | if (!is_array($block) || CRM_Utils_System::isNull($block)) { |
1925 | continue; | |
1926 | } | |
1927 | $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label']; | |
abd0b852 | 1928 | $changePrimary = FALSE; |
92a77772 | 1929 | $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL; |
1930 | $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL; | |
1931 | ||
1932 | foreach ($block as $blkCount => $values) { | |
1933 | $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]); | |
1934 | $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0); | |
1935 | if (!$otherBlockId) { | |
1936 | continue; | |
1937 | } | |
1938 | ||
1939 | // For the block which belongs to other-contact, link the location block to main-contact | |
1940 | $otherBlockDAO = new $daoName(); | |
1941 | $otherBlockDAO->contact_id = $mainId; | |
1942 | ||
1943 | // Get the ID of this block on the 'other' contact, otherwise skip | |
1944 | $otherBlockDAO->id = $otherBlockId; | |
1945 | ||
1946 | // Add/update location and type information from the form, if applicable | |
1947 | if ($locationBlocks[$name]['hasLocation']) { | |
1948 | $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]); | |
1949 | $otherBlockDAO->location_type_id = $locTypeId; | |
1950 | } | |
1951 | if ($locationBlocks[$name]['hasType']) { | |
1952 | $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]); | |
1953 | $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId; | |
1954 | } | |
1955 | ||
abd0b852 J |
1956 | // If we're deliberately setting this as primary then add the flag |
1957 | // and remove it from the current primary location (if there is one). | |
1958 | // But only once for each entity. | |
1959 | $set_primary = CRM_Utils_Array::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]); | |
9e848fc4 | 1960 | if (!$changePrimary && $set_primary == "1") { |
abd0b852 J |
1961 | $otherBlockDAO->is_primary = 1; |
1962 | if ($primaryDAOId) { | |
1963 | $removePrimaryDAO = new $daoName(); | |
1964 | $removePrimaryDAO->id = $primaryDAOId; | |
1965 | $removePrimaryDAO->is_primary = 0; | |
1966 | $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO; | |
1967 | } | |
1968 | $changePrimary = TRUE; | |
1969 | } | |
1970 | // Otherwise, if main contact already has primary, set it to 0. | |
1971 | elseif ($primaryDAOId) { | |
92a77772 | 1972 | $otherBlockDAO->is_primary = 0; |
1973 | } | |
abd0b852 J |
1974 | |
1975 | // If the main contact already has a billing location, set this to 0. | |
92a77772 | 1976 | if ($billingDAOId) { |
1977 | $otherBlockDAO->is_billing = 0; | |
1978 | } | |
1979 | ||
1980 | $operation = CRM_Utils_Array::value('operation', $values, 2); | |
1981 | // overwrite - need to delete block which belongs to main-contact. | |
1982 | if (!empty($mainBlockId) && ($operation == 2)) { | |
1983 | $deleteDAO = new $daoName(); | |
1984 | $deleteDAO->id = $mainBlockId; | |
1985 | $deleteDAO->find(TRUE); | |
1986 | ||
1987 | // if we about to delete a primary / billing block, set the flags for new block | |
1988 | // that we going to assign to main-contact | |
1989 | if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) { | |
1990 | $otherBlockDAO->is_primary = 1; | |
1991 | } | |
1992 | if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) { | |
1993 | $otherBlockDAO->is_billing = 1; | |
1994 | } | |
1995 | $blocksDAO[$name]['delete'][$deleteDAO->id] = $deleteDAO; | |
1996 | } | |
1997 | $blocksDAO[$name]['update'][$otherBlockDAO->id] = $otherBlockDAO; | |
1998 | } | |
1999 | } | |
2000 | } | |
2001 | ||
2002 | CRM_Utils_Hook::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo); | |
2003 | foreach ($blocksDAO as $blockDAOs) { | |
2004 | if (!empty($blockDAOs['update'])) { | |
2005 | foreach ($blockDAOs['update'] as $blockDAO) { | |
2006 | $blockDAO->save(); | |
2007 | } | |
2008 | } | |
2009 | if (!empty($blockDAOs['delete'])) { | |
2010 | foreach ($blockDAOs['delete'] as $blockDAO) { | |
2011 | $blockDAO->delete(); | |
2012 | } | |
2013 | } | |
2014 | } | |
2015 | } | |
2016 | ||
e4e1db4b | 2017 | /** |
2018 | * Dedupe a pair of contacts. | |
2019 | * | |
b068bfde | 2020 | * @param array $dupes |
e4e1db4b | 2021 | * @param string $mode |
2022 | * @param bool $checkPermissions | |
e4e1db4b | 2023 | * @param string $cacheKeyString |
37cd9336 | 2024 | * |
b068bfde | 2025 | * @return bool|array |
37cd9336 | 2026 | * @throws \CRM_Core_Exception |
2027 | * @throws \CiviCRM_API3_Exception | |
ffa59d18 | 2028 | * @throws \API_Exception |
e4e1db4b | 2029 | */ |
b068bfde | 2030 | protected static function dedupePair($dupes, $mode = 'safe', $checkPermissions = TRUE, $cacheKeyString = NULL) { |
2031 | CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']); | |
2032 | $mainId = $dupes['dstID']; | |
2033 | $otherId = $dupes['srcID']; | |
2034 | $resultStats = []; | |
2035 | ||
2036 | if (!$mainId || !$otherId) { | |
2037 | // return error | |
2038 | return FALSE; | |
2039 | } | |
aefc291e | 2040 | $migrationInfo = []; |
2c16165a | 2041 | $conflicts = []; |
e4e1db4b | 2042 | if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) { |
2043 | CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions); | |
2c16165a | 2044 | $resultStats['merged'][] = [ |
e4e1db4b | 2045 | 'main_id' => $mainId, |
2046 | 'other_id' => $otherId, | |
2c16165a | 2047 | ]; |
e4e1db4b | 2048 | } |
2049 | else { | |
2c16165a | 2050 | $resultStats['skipped'][] = [ |
e4e1db4b | 2051 | 'main_id' => $mainId, |
2052 | 'other_id' => $otherId, | |
2c16165a | 2053 | ]; |
e4e1db4b | 2054 | } |
2055 | ||
2056 | // store any conflicts | |
2057 | if (!empty($conflicts)) { | |
ffa59d18 | 2058 | CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode); |
e4e1db4b | 2059 | } |
2060 | else { | |
c131d228 | 2061 | CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString); |
e4e1db4b | 2062 | } |
b068bfde | 2063 | return $resultStats; |
e4e1db4b | 2064 | } |
2065 | ||
54ed517e | 2066 | /** |
2067 | * Replace the pseudo QFKey with zero if it is present. | |
2068 | * | |
2069 | * @todo - on the slim chance this is still relevant it should be moved to the form layer. | |
2070 | * | |
2071 | * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA | |
2072 | * can still help. | |
2073 | * | |
2074 | * @param array $migrationInfo | |
2075 | */ | |
2076 | protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) { | |
2077 | $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; | |
2078 | foreach ($migrationInfo as $key => &$value) { | |
2079 | if ($value == $qfZeroBug) { | |
2080 | $value = '0'; | |
2081 | } | |
2082 | } | |
2083 | } | |
2084 | ||
830ee2be | 2085 | /** |
2086 | * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose. | |
2087 | * | |
1600a9c0 | 2088 | * Update this function formats fields in preparation for them to be submitted to the |
2089 | * 'ProfileContactCreate action. This is a lot of code to do this & for | |
2090 | * - for some fields it fails - e.g Country - per testMergeCustomFields. | |
2091 | * | |
2092 | * Goal is to move all custom field handling into 'move' functions on the various BAO | |
2093 | * with an underlying DAO function. For custom fields it has been started on the BAO. | |
2094 | * | |
830ee2be | 2095 | * @param $mainId |
2096 | * @param $key | |
2097 | * @param $cFields | |
830ee2be | 2098 | * @param $submitted |
2099 | * @param $value | |
2100 | * | |
2101 | * @return array | |
1600a9c0 | 2102 | * @throws \Exception |
830ee2be | 2103 | */ |
1600a9c0 | 2104 | protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) { |
830ee2be | 2105 | if (substr($key, 0, 7) == 'custom_') { |
2106 | $fid = (int) substr($key, 7); | |
2107 | if (empty($cFields[$fid])) { | |
1600a9c0 | 2108 | return [$cFields, $submitted]; |
830ee2be | 2109 | } |
2110 | $htmlType = $cFields[$fid]['attributes']['html_type']; | |
2111 | switch ($htmlType) { | |
2112 | case 'File': | |
1600a9c0 | 2113 | // Handled in CustomField->move(). Tested in testMergeCustomFields. |
830ee2be | 2114 | unset($submitted["custom_$fid"]); |
2115 | break; | |
2116 | ||
2117 | case 'Select Country': | |
1600a9c0 | 2118 | // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move(). |
830ee2be | 2119 | case 'Select State/Province': |
2120 | $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid); | |
2121 | break; | |
2122 | ||
2123 | case 'Select Date': | |
2124 | if ($cFields[$fid]['attributes']['is_view']) { | |
2125 | $submitted[$key] = date('YmdHis', strtotime($submitted[$key])); | |
2126 | } | |
2127 | break; | |
2128 | ||
2129 | case 'CheckBox': | |
2130 | case 'Multi-Select': | |
2131 | case 'Multi-Select Country': | |
2132 | case 'Multi-Select State/Province': | |
2133 | // Merge values from both contacts for multivalue fields, CRM-4385 | |
2134 | // get the existing custom values from db. | |
2135 | $customParams = ['entityID' => $mainId, $key => TRUE]; | |
2136 | $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams); | |
2137 | if (!empty($customfieldValues[$key])) { | |
2138 | $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]); | |
2139 | if (is_array($existingValue) && !empty($existingValue)) { | |
2140 | $mergeValue = $submittedCustomFields = []; | |
2141 | if ($value == 'null') { | |
2142 | // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it. | |
2143 | $submitted[$key] = $value; | |
2144 | } | |
2145 | else { | |
2146 | if ($value) { | |
2147 | $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); | |
2148 | } | |
2149 | ||
2150 | // CRM-19653: overwrite or add the existing custom field value with dupicate contact's | |
2151 | // custom field value stored at $submittedCustomValue. | |
2152 | foreach ($submittedCustomFields as $k => $v) { | |
2153 | if ($v != '' && !in_array($v, $mergeValue)) { | |
2154 | $mergeValue[] = $v; | |
2155 | } | |
2156 | } | |
2157 | ||
2158 | //keep state and country as array format. | |
2159 | //for checkbox and m-select format w/ VALUE_SEPARATOR | |
2160 | if (in_array($htmlType, [ | |
2161 | 'CheckBox', | |
2162 | 'Multi-Select', | |
2163 | ])) { | |
2164 | $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, | |
2165 | $mergeValue | |
2166 | ) . CRM_Core_DAO::VALUE_SEPARATOR; | |
2167 | } | |
2168 | else { | |
2169 | $submitted[$key] = $mergeValue; | |
2170 | } | |
2171 | } | |
2172 | } | |
2173 | } | |
2174 | elseif (in_array($htmlType, [ | |
2175 | 'Multi-Select Country', | |
2176 | 'Multi-Select State/Province', | |
2177 | ])) { | |
2178 | //we require submitted values should be in array format | |
2179 | if ($value) { | |
2180 | $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); | |
2181 | //hack to remove null values from array. | |
2182 | $mergeValue = []; | |
2183 | foreach ($mergeValueArray as $k => $v) { | |
2184 | if ($v != '') { | |
2185 | $mergeValue[] = $v; | |
2186 | } | |
2187 | } | |
2188 | $submitted[$key] = $mergeValue; | |
2189 | } | |
2190 | } | |
2191 | break; | |
2192 | ||
2193 | default: | |
2194 | break; | |
2195 | } | |
2196 | } | |
1600a9c0 | 2197 | return [$cFields, $submitted]; |
830ee2be | 2198 | } |
2199 | ||
f941d73a | 2200 | /** |
2201 | * Get metadata for the custom fields for the merge. | |
2202 | * | |
2203 | * @param string $contactType | |
2204 | * | |
2205 | * @return array | |
2206 | */ | |
2207 | protected static function getCustomFieldMetadata($contactType) { | |
2208 | $treeCache = []; | |
2209 | if (!array_key_exists($contactType, $treeCache)) { | |
2210 | $treeCache[$contactType] = CRM_Core_BAO_CustomGroup::getTree( | |
2211 | $contactType, | |
2212 | NULL, | |
2213 | NULL, | |
2214 | -1, | |
2215 | [], | |
2216 | NULL, | |
2217 | TRUE, | |
2218 | NULL, | |
2219 | FALSE, | |
2220 | FALSE | |
2221 | ); | |
2222 | } | |
2223 | ||
2224 | $cFields = []; | |
2225 | foreach ($treeCache[$contactType] as $key => $group) { | |
2226 | if (!isset($group['fields'])) { | |
2227 | continue; | |
2228 | } | |
2229 | foreach ($group['fields'] as $fid => $field) { | |
2230 | $cFields[$fid]['attributes'] = $field; | |
2231 | } | |
2232 | } | |
2233 | return $cFields; | |
2234 | } | |
2235 | ||
a2abc387 | 2236 | /** |
2237 | * Get conflicts for proposed merge pair. | |
2238 | * | |
2239 | * @param array $migrationInfo | |
2240 | * This is primarily to inform hooks. The can also modify it which feels | |
2241 | * pretty fragile to do it here - but it is historical. | |
2242 | * @param int $mainId | |
2243 | * Main contact with whom merge has to happen. | |
2244 | * @param int $otherId | |
2245 | * Duplicate contact which would be deleted after merge operation. | |
2246 | * @param string $mode | |
2247 | * Helps decide how to behave when there are conflicts. | |
2248 | * - A 'safe' value skips the merge if there are any un-resolved conflicts. | |
2249 | * - Does a force merge otherwise (aggressive mode). | |
2250 | * | |
2251 | * @return array | |
aefc291e | 2252 | * |
2253 | * @throws \CRM_Core_Exception | |
2254 | * @throws \CiviCRM_API3_Exception | |
a2abc387 | 2255 | */ |
2256 | public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) { | |
2257 | $conflicts = []; | |
aefc291e | 2258 | // Generate var $migrationInfo. The variable structure is exactly same as |
2259 | // $formValues submitted during a UI merge for a pair of contacts. | |
2260 | $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, FALSE); | |
2261 | // add additional details that we might need to resolve conflicts | |
2262 | $migrationInfo = $rowsElementsAndInfo['migration_info']; | |
2263 | $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details']; | |
2264 | $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details']; | |
2265 | $migrationInfo['rows'] = &$rowsElementsAndInfo['rows']; | |
2266 | // go ahead with merge if there is no conflict | |
a2abc387 | 2267 | $originalMigrationInfo = $migrationInfo; |
2268 | foreach ($migrationInfo as $key => $val) { | |
2269 | if ($val === "null") { | |
2270 | // Rule: Never overwrite with an empty value (in any mode) | |
2271 | unset($migrationInfo[$key]); | |
2272 | continue; | |
2273 | } | |
2274 | elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or | |
2275 | substr($key, 0, 12) == 'move_custom_' | |
2276 | ) and $val != NULL | |
2277 | ) { | |
2278 | // Rule: If both main-contact, and other-contact have a field with a | |
2279 | // different value, then let $mode decide if to merge it or not | |
2280 | if ( | |
2281 | (!empty($migrationInfo['rows'][$key]['main']) | |
2282 | // For custom fields a 0 (e.g in an int field) could be a true conflict. This | |
2283 | // is probably true for other fields too - e.g. 'do_not_email' but | |
2284 | // leaving that investigation as a @todo - until tests can be written. | |
2285 | // Note the handling of this has test coverage - although the data-typing | |
2286 | // of '0' feels flakey we have insurance. | |
2287 | || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_') | |
2288 | ) | |
2289 | && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other'] | |
2290 | ) { | |
2291 | ||
2292 | // note it down & lets wait for response from the hook. | |
2293 | // For no response $mode will decide if to skip this merge | |
2294 | $conflicts[$key] = NULL; | |
2295 | } | |
2296 | } | |
2297 | elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) { | |
2298 | $locField = explode('_', $key); | |
2299 | $fieldName = $locField[2]; | |
2300 | $fieldCount = $locField[3]; | |
2301 | ||
2302 | // Rule: Catch address conflicts (same address type on both contacts) | |
2303 | if ( | |
2304 | isset($migrationInfo['main_details']['location_blocks'][$fieldName]) && | |
2305 | !empty($migrationInfo['main_details']['location_blocks'][$fieldName]) | |
2306 | ) { | |
2307 | ||
2308 | // Load the address we're inspecting from the 'other' contact | |
2309 | $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount]; | |
2310 | $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord); | |
2311 | ||
2312 | // If it exists on the 'main' contact already, skip it. Otherwise | |
2313 | // if the location type exists already, log a conflict. | |
2314 | foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) { | |
2315 | if (self::locationIsSame($addressRecord, $mainAddressRecord)) { | |
2316 | unset($migrationInfo[$key]); | |
2317 | break; | |
2318 | } | |
2319 | elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) { | |
2320 | $conflicts[$key] = NULL; | |
2321 | break; | |
2322 | } | |
2323 | } | |
2324 | } | |
2325 | ||
2326 | // For other locations, don't merge/add if the values are the same | |
2327 | elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) { | |
2328 | unset($migrationInfo[$key]); | |
2329 | } | |
2330 | } | |
2331 | } | |
2332 | ||
2333 | // A hook to implement other algorithms for choosing which contact to bias to when | |
2334 | // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here | |
2335 | // merge happens with new values filled in here. For a particular field / row not to be merged | |
2336 | // field should be unset from fields_in_conflict. | |
2337 | $migrationData = [ | |
2338 | 'old_migration_info' => $originalMigrationInfo, | |
2339 | 'mode' => $mode, | |
2340 | 'fields_in_conflict' => $conflicts, | |
2341 | 'merge_mode' => $mode, | |
2342 | 'migration_info' => $migrationInfo, | |
2343 | ]; | |
2344 | CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId); | |
2345 | $conflicts = $migrationData['fields_in_conflict']; | |
2346 | // allow hook to override / manipulate migrationInfo as well | |
2347 | $migrationInfo = $migrationData['migration_info']; | |
ffa59d18 | 2348 | foreach ($conflicts as $key => $val) { |
2349 | if ($val !== NULL || $mode !== 'safe') { | |
2350 | // copy over the resolved values | |
2351 | $migrationInfo[$key] = $val; | |
2352 | unset($conflicts[$key]); | |
2353 | } | |
2354 | } | |
ffa59d18 | 2355 | return self::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId); |
2356 | } | |
2357 | ||
2358 | /** | |
2359 | * @param array $conflicts | |
2360 | * @param array $migrationInfo | |
2361 | * @param $toKeepContactLocationBlocks | |
2362 | * @param $toRemoveContactLocationBlocks | |
2363 | * @param $toKeepID | |
2364 | * @param $toRemoveID | |
2365 | * | |
2366 | * @return mixed | |
2367 | * @throws \CRM_Core_Exception | |
2368 | */ | |
2369 | protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID) { | |
2370 | $return = []; | |
2371 | foreach (array_keys($conflicts) as $index) { | |
2372 | if (substr($index, 0, 14) === 'move_location_') { | |
2373 | $parts = explode('_', $index); | |
2374 | $entity = $parts[2]; | |
2375 | $blockIndex = $parts[3]; | |
2376 | $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id']; | |
2377 | $entityConflicts = [ | |
2378 | 'location_type_id' => $locationTypeID, | |
2379 | 'title' => $migrationInfo[$index]['title'], | |
2380 | ]; | |
2381 | foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) { | |
2382 | if (in_array($fieldName, self::ignoredFields())) { | |
2383 | continue; | |
2384 | } | |
2385 | $toRemoveValue = CRM_Utils_Array::value($fieldName, $toRemoveContactLocationBlocks[$entity][$blockIndex]); | |
2386 | if ($fieldValue !== $toRemoveValue) { | |
2387 | $entityConflicts[$fieldName] = [ | |
2388 | $toKeepID => $fieldValue, | |
2389 | $toRemoveID => $toRemoveValue, | |
2390 | ]; | |
2391 | } | |
2392 | } | |
2393 | $return[$entity][] = $entityConflicts; | |
2394 | } | |
2395 | elseif (substr($index, 0, 5) === 'move_') { | |
2396 | $contactFieldsToCompare[] = str_replace('move_', '', $index); | |
2397 | $return['contact'][str_replace('move_', '', $index)] = [ | |
2398 | 'title' => $migrationInfo[$index]['title'], | |
2399 | $toKeepID => $migrationInfo[$index]['main'], | |
2400 | $toRemoveID => $migrationInfo[$index]['other'], | |
2401 | ]; | |
2402 | } | |
2403 | else { | |
2404 | // Can't think of why this would be the case but perhaps it's ensuring it isn't as we | |
2405 | // refactor this. | |
2406 | throw new CRM_Core_Exception(ts('Unknown parameter') . $index); | |
2407 | } | |
2408 | } | |
2409 | return $return; | |
a2abc387 | 2410 | } |
2411 | ||
4107e11e | 2412 | /** |
e1e24a57 | 2413 | * Get any duplicate merge pairs that have been previously cached. |
2414 | * | |
2415 | * @param int $rule_group_id | |
2416 | * @param int $group_id | |
2417 | * @param int $batchLimit | |
2418 | * @param bool $isSelected | |
2419 | * @param bool $includeConflicts | |
2420 | * @param array $criteria | |
2421 | * @param int $checkPermissions | |
997a03fe | 2422 | * @param int $searchLimit |
4107e11e | 2423 | * |
2424 | * @return array | |
2425 | */ | |
997a03fe | 2426 | protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit = 0) { |
4107e11e | 2427 | return CRM_Core_BAO_PrevNextCache::retrieve( |
997a03fe | 2428 | self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit), |
4107e11e | 2429 | self::getJoinOnDedupeTable(), |
2430 | self::getWhereString($isSelected), | |
2431 | 0, $batchLimit, | |
2432 | [], '', | |
2433 | $includeConflicts | |
2434 | ); | |
2435 | } | |
2436 | ||
ffa59d18 | 2437 | /** |
2438 | * @return array | |
2439 | */ | |
2440 | protected static function ignoredFields(): array { | |
2441 | $keysToIgnore = [ | |
2442 | 'id', | |
2443 | 'is_primary', | |
2444 | 'is_billing', | |
2445 | 'manual_geo_code', | |
2446 | 'contact_id', | |
2447 | 'reset_date', | |
2448 | 'hold_date', | |
2449 | ]; | |
2450 | return $keysToIgnore; | |
2451 | } | |
2452 | ||
6704a926 | 2453 | /** |
2454 | * Get the field value & label for the given field. | |
2455 | * | |
2456 | * @param $field | |
2457 | * @param $contact | |
2458 | * | |
2459 | * @return array | |
2460 | * @throws \Exception | |
2461 | */ | |
2462 | private static function getFieldValueAndLabel($field, $contact): array { | |
2463 | $fields = self::getMergeFieldsMetadata(); | |
2464 | $value = $label = CRM_Utils_Array::value($field, $contact); | |
2465 | $fieldSpec = $fields[$field]; | |
2466 | if (!empty($fieldSpec['serialize']) && is_array($value)) { | |
2467 | // In practice this only applies to preferred_communication_method as the sub types are skipped above | |
2468 | // and no others are serialized. | |
2469 | $labels = []; | |
2470 | foreach ($value as $individualValue) { | |
2471 | $labels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue); | |
2472 | } | |
2473 | $label = implode(', ', $labels); | |
2474 | // We serialize this due to historic handling but it's likely that if we just left it as an | |
2475 | // array all would be well & we would have less code. | |
2476 | $value = CRM_Core_DAO::serializeField($value, $fieldSpec['serialize']); | |
2477 | } | |
2478 | elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type::T_DATE) { | |
2479 | if ($value) { | |
2480 | $value = str_replace('-', '', $value); | |
2481 | $label = CRM_Utils_Date::customFormat($label); | |
2482 | } | |
2483 | else { | |
2484 | $value = "null"; | |
2485 | } | |
2486 | } | |
2487 | elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) { | |
2488 | if ($label === '0') { | |
2489 | $label = ts('[ ]'); | |
2490 | } | |
2491 | if ($label === '1') { | |
2492 | $label = ts('[x]'); | |
2493 | } | |
2494 | } | |
2495 | elseif (!empty($fieldSpec['pseudoconstant'])) { | |
2496 | $label = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $value); | |
2497 | } | |
2498 | elseif ($field == 'current_employer_id' && !empty($value)) { | |
2499 | $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")"; | |
2500 | } | |
2fd72602 | 2501 | return ['label' => $label, 'value' => $value]; |
6704a926 | 2502 | } |
2503 | ||
1a90ac89 | 2504 | /** |
2505 | * Build up the location block for the contact in dedupe-screen display format. | |
2506 | * | |
2507 | * @param integer $cid | |
2508 | * @param array $blockInfo | |
2509 | * @param string $blockName | |
2510 | * | |
2511 | * @return array | |
2512 | * | |
2513 | * @throws \CiviCRM_API3_Exception | |
2514 | */ | |
2515 | private static function buildLocationBlockForContact($cid, $blockInfo, $blockName): array { | |
2516 | $searchParams = [ | |
2517 | 'contact_id' => $cid, | |
2518 | // CRM-17556 Order by field-specific criteria | |
2519 | 'options' => [ | |
2520 | 'sort' => $blockInfo['sortString'], | |
2521 | ], | |
2522 | ]; | |
2523 | $locationBlock = []; | |
2524 | $values = civicrm_api3($blockName, 'get', $searchParams); | |
2525 | if ($values['count']) { | |
2526 | $cnt = 0; | |
2527 | foreach ($values['values'] as $value) { | |
2528 | $locationBlock[$cnt] = $value; | |
2529 | // Fix address display | |
2530 | if ($blockName == 'address') { | |
2531 | // For performance avoid geocoding while merging https://issues.civicrm.org/jira/browse/CRM-21786 | |
2532 | // we can expect existing geocode values to be retained. | |
2533 | $value['skip_geocode'] = TRUE; | |
2534 | CRM_Core_BAO_Address::fixAddress($value); | |
2535 | unset($value['skip_geocode']); | |
2536 | $locationBlock[$cnt]['display'] = CRM_Utils_Address::format($value); | |
2537 | } | |
2538 | // Fix email display | |
2539 | elseif ($blockName == 'email') { | |
2540 | $locationBlock[$cnt]['display'] = CRM_Utils_Mail::format($value); | |
2541 | } | |
2542 | ||
2543 | $cnt++; | |
2544 | } | |
2545 | } | |
2546 | return $locationBlock; | |
2547 | } | |
2548 | ||
6a488035 | 2549 | } |