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