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'], |
aca7613b | 105 | 'url' => CRM_Utils_System::url('civicrm/admin/custom/group'), |
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); |
5f282bca | 506 | $multiValueCidRefs = self::getMultiValueCidRefs(); |
674920ca ES |
507 | |
508 | $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs)); | |
0556db5d CR |
509 | |
510 | // if there aren't any specific tables, don't affect the ones handled by relTables() | |
511 | // also don't affect tables in locTables() CRM-15658 | |
512 | $relTables = self::relTables(); | |
eca28463 | 513 | // These arrays don't make a lot of sense. For now ensure the tested handling of tags works... |
514 | // it is moved over further down.... | |
515 | unset($relTables['rel_table_tags']); | |
0556db5d CR |
516 | $handled = self::locTables(); |
517 | ||
518 | foreach ($relTables as $params) { | |
519 | $handled = array_merge($handled, $params['tables']); | |
6a488035 | 520 | } |
0556db5d | 521 | $affected = array_diff($affected, $handled); |
e3159b07 | 522 | $affected = array_unique(array_merge($affected, $tables)); |
6a488035 TO |
523 | |
524 | $mainId = (int) $mainId; | |
525 | $otherId = (int) $otherId; | |
526 | ||
2c16165a | 527 | $sqls = []; |
6a488035 TO |
528 | foreach ($affected as $table) { |
529 | // Call custom processing function for objects that require it | |
530 | if (isset($cpTables[$table])) { | |
531 | foreach ($cpTables[$table] as $className => $fnName) { | |
43d4ad93 | 532 | $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations); |
6a488035 TO |
533 | } |
534 | // Skip normal processing | |
535 | continue; | |
536 | } | |
b3fdbf3d | 537 | |
59041f88 | 538 | if ($table === 'civicrm_activity_contact') { |
539 | $sqls[] = "UPDATE IGNORE civicrm_activity_contact SET contact_id = $mainId WHERE contact_id = $otherId"; | |
540 | $sqls[] = "DELETE FROM civicrm_activity_contact WHERE contact_id = $otherId"; | |
541 | continue; | |
542 | } | |
543 | ||
f8c35cad | 544 | if ($table === 'civicrm_dashboard_contact') { |
545 | $sqls[] = "UPDATE IGNORE civicrm_dashboard_contact SET contact_id = $mainId WHERE contact_id = $otherId"; | |
546 | $sqls[] = "DELETE FROM civicrm_dashboard_contact WHERE contact_id = $otherId"; | |
547 | continue; | |
548 | } | |
549 | ||
119166b4 | 550 | if ($table === 'civicrm_dedupe_exception') { |
551 | $sqls[] = "UPDATE IGNORE civicrm_dedupe_exception SET contact_id1 = $mainId WHERE contact_id1 = $otherId"; | |
552 | $sqls[] = "UPDATE IGNORE civicrm_dedupe_exception SET contact_id2 = $mainId WHERE contact_id2 = $otherId"; | |
553 | $sqls[] = "DELETE FROM civicrm_dedupe_exception WHERE contact_id1 = $otherId OR contact_id2 = $otherId"; | |
554 | continue; | |
555 | } | |
556 | ||
2297a28d | 557 | if ($table === 'civicrm_setting') { |
558 | // Per https://lab.civicrm.org/dev/core/-/issues/1934 | |
559 | // Note this line is not unit tested as yet as a quick-fix for a regression | |
560 | // but it would be better to do a SELECT request & only update if needed (as a general rule | |
561 | // more selects & less UPDATES will result in less deadlocks while de-duping. | |
562 | // Note the delete is not important here - it can stay with the deleted contact on the | |
563 | // off chance they get restored. | |
564 | $sqls[] = "UPDATE IGNORE civicrm_setting SET contact_id = $mainId WHERE contact_id = $otherId"; | |
565 | continue; | |
566 | } | |
567 | ||
6a488035 TO |
568 | // use UPDATE IGNORE + DELETE query pair to skip on situations when |
569 | // there's a UNIQUE restriction on ($field, some_other_field) pair | |
570 | if (isset($cidRefs[$table])) { | |
571 | foreach ($cidRefs[$table] as $field) { | |
572 | // carry related contributions CRM-5359 | |
573 | if (in_array($table, $paymentTables)) { | |
6a488035 TO |
574 | $paymentSqls = self::paymentSql($table, $mainId, $otherId); |
575 | $sqls = array_merge($sqls, $paymentSqls); | |
71560cf3 C |
576 | |
577 | if (!empty($tables) && !in_array('civicrm_contribution', $tables)) { | |
578 | $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment'); | |
579 | $sqls = array_merge($sqls, $payOprSqls); | |
580 | } | |
6a488035 TO |
581 | } |
582 | ||
583 | $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations); | |
584 | $sqls = array_merge($sqls, $preOperationSqls); | |
5f282bca CW |
585 | |
586 | if (!empty($multiValueCidRefs[$table][$field])) { | |
587 | $sep = CRM_Core_DAO::VALUE_SEPARATOR; | |
588 | $sqls[] = "UPDATE $table SET $field = REPLACE($field, '$sep$otherId$sep', '$sep$mainId$sep') WHERE $field LIKE '%$sep$otherId$sep%'"; | |
589 | } | |
590 | else { | |
591 | $sqls[] = "UPDATE $table SET $field = $mainId WHERE $field = $otherId"; | |
592 | } | |
6a488035 TO |
593 | } |
594 | } | |
ae2346d4 | 595 | |
6a488035 | 596 | if (isset($eidRefs[$table])) { |
9811efd4 JG |
597 | foreach ($dynamicRefs[$table] as $dynamicRef) { |
598 | $sqls[] = "UPDATE IGNORE $table SET {$dynamicRef[0]}= $mainId WHERE {$dynamicRef[0]} = $otherId AND {$dynamicRef[1]} = 'civicrm_contact'"; | |
599 | $sqls[] = "DELETE FROM $table WHERE {$dynamicRef[0]} = $otherId AND {$dynamicRef[1]} = 'civicrm_contact'"; | |
600 | } | |
6a488035 TO |
601 | } |
602 | } | |
603 | ||
604 | // Allow hook_civicrm_merge() to add SQL statements for the merge operation. | |
605 | CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables); | |
606 | ||
6a488035 | 607 | foreach ($sqls as $sql) { |
2c16165a | 608 | CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE); |
6a488035 | 609 | } |
6bb508e5 | 610 | CRM_Dedupe_Merger::addMembershipToRelatedContacts($mainId); |
6a488035 TO |
611 | } |
612 | ||
fe3b8caf | 613 | /** |
614 | * Filter out custom tables from cidRefs unless they are there due to a contact reference or are a multiple set. | |
615 | * | |
616 | * The only fields where we want to move the data by sql is where entity reference fields | |
617 | * on another contact refer to the contact being merged, or it is a multiple record set. | |
618 | * The transference of custom data from one contact to another is done in 2 other places in the dedupe process but should | |
619 | * not be done in moveAllContactData. | |
620 | * | |
621 | * Note it's a bit silly the way we build & then cull cidRefs - however, poor hook placement means that | |
622 | * until we fully deprecate calling the hook from cidRefs we are stuck. | |
623 | * | |
624 | * It was deprecated in code (via deprecation notices if people altered it) in Mar 2019 but in docs only in Apri 2020. | |
625 | * | |
626 | * @param array $cidRefs | |
627 | * | |
628 | * @throws \API_Exception | |
629 | * @throws \Civi\API\Exception\UnauthorizedException | |
630 | */ | |
631 | protected static function filterRowBasedCustomDataFromCustomTables(array &$cidRefs) { | |
fe806431 | 632 | $customTables = (array) CustomGroup::get(FALSE) |
fe3b8caf | 633 | ->setSelect(['table_name']) |
634 | ->addWhere('is_multiple', '=', 0) | |
96a118e6 | 635 | ->addWhere('extends', 'IN', array_merge(['Contact'], CRM_Contact_BAO_ContactType::contactTypes())) |
fe3b8caf | 636 | ->execute() |
637 | ->indexBy('table_name'); | |
638 | foreach (array_intersect_key($cidRefs, $customTables) as $tableName => $cidSpec) { | |
639 | if (in_array('entity_id', $cidSpec, TRUE)) { | |
640 | unset($cidRefs[$tableName][array_search('entity_id', $cidSpec, TRUE)]); | |
641 | } | |
642 | if (empty($cidRefs[$tableName])) { | |
643 | unset($cidRefs[$tableName]); | |
644 | } | |
645 | } | |
646 | } | |
647 | ||
5f282bca CW |
648 | /** |
649 | * Return an array of tables & fields which hold serialized arrays of contact ids | |
650 | * | |
651 | * Return format is ['table_name' => ['field_name' => SERIALIZE_METHOD]] | |
652 | * | |
653 | * For now, only custom fields can be serialized and the only | |
654 | * method used is CRM_Core_DAO::SERIALIZE_SEPARATOR_BOOKEND. | |
655 | */ | |
656 | protected static function getMultiValueCidRefs() { | |
657 | $fields = \Civi\Api4\CustomField::get(FALSE) | |
84ad7693 | 658 | ->addSelect('custom_group_id.table_name', 'column_name', 'serialize') |
5f282bca CW |
659 | ->addWhere('data_type', '=', 'ContactReference') |
660 | ->addWhere('serialize', 'IS NOT EMPTY') | |
661 | ->execute(); | |
662 | ||
663 | $map = []; | |
664 | foreach ($fields as $field) { | |
84ad7693 | 665 | $map[$field['custom_group_id.table_name']][$field['column_name']] = $field['serialize']; |
5f282bca CW |
666 | } |
667 | return $map; | |
668 | } | |
669 | ||
d00dc576 | 670 | /** |
671 | * Update the contact with the new parameters. | |
672 | * | |
673 | * This function is intended as an interim function, with the intent being | |
674 | * an apiv4 call. | |
675 | * | |
676 | * The function was calling the rather-terrifying createProfileContact. I copied all | |
677 | * that code into this function and then removed all the parts that have no effect in this scenario. | |
678 | * | |
679 | * @param int $contactID | |
680 | * @param array $params | |
681 | * | |
682 | * @throws \CRM_Core_Exception | |
683 | * @throws \CiviCRM_API3_Exception | |
684 | * @throws \Civi\API\Exception\UnauthorizedException | |
685 | */ | |
630b73e3 | 686 | protected static function updateContact(int $contactID, $params): void { |
d00dc576 | 687 | // This parameter causes blank fields to be be emptied out. |
688 | // We can probably remove. | |
689 | $params['updateBlankLocInfo'] = TRUE; | |
7b3d682c | 690 | $data = self::formatProfileContactParams($params, $contactID); |
d00dc576 | 691 | CRM_Contact_BAO_Contact::create($data); |
692 | } | |
693 | ||
92ff9509 EM |
694 | /** |
695 | * Format profile contact parameters. | |
696 | * | |
697 | * Note this function has been duplicated from CRM_Contact_BAO_Contact | |
698 | * in order to allow us to unravel all the work this class | |
699 | * does to prepare to call this & create some sanity. Also start to | |
700 | * eliminate a toxic function. | |
701 | * | |
702 | * @param array $params | |
92ff9509 | 703 | * @param int $contactID |
92ff9509 EM |
704 | * |
705 | * @return array | |
706 | */ | |
707 | private static function formatProfileContactParams( | |
7b3d682c EM |
708 | $params, |
709 | int $contactID | |
92ff9509 EM |
710 | ) { |
711 | ||
712 | $data = $contactDetails = []; | |
713 | ||
714 | // get the contact details (hier) | |
7b3d682c | 715 | $details = CRM_Contact_BAO_Contact::getHierContactDetails($contactID, []); |
92ff9509 | 716 | |
d40d990d EM |
717 | $contactDetails = $details[$contactID]; |
718 | $data['contact_type'] = $contactDetails['contact_type'] ?? NULL; | |
719 | $data['contact_sub_type'] = $contactDetails['contact_sub_type'] ?? NULL; | |
92ff9509 EM |
720 | |
721 | //fix contact sub type CRM-5125 | |
722 | if (array_key_exists('contact_sub_type', $params) && | |
723 | !empty($params['contact_sub_type']) | |
724 | ) { | |
725 | $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']); | |
726 | } | |
727 | elseif (array_key_exists('contact_sub_type_hidden', $params) && | |
728 | !empty($params['contact_sub_type_hidden']) | |
729 | ) { | |
730 | // if profile was used, and had any subtype, we obtain it from there | |
731 | //CRM-13596 - add to existing contact types, rather than overwriting | |
732 | if (empty($data['contact_sub_type'])) { | |
733 | // If we don't have a contact ID the $data['contact_sub_type'] will not be defined... | |
734 | $data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']); | |
735 | } | |
736 | else { | |
737 | $data_contact_sub_type_arr = CRM_Utils_Array::explodePadded($data['contact_sub_type']); | |
738 | if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) { | |
739 | //CRM-20517 - make sure contact_sub_type gets the correct delimiters | |
740 | $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR); | |
741 | $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . $data['contact_sub_type'] . CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']); | |
742 | } | |
743 | } | |
744 | } | |
745 | ||
92ff9509 EM |
746 | $locationType = []; |
747 | $count = 1; | |
748 | ||
d40d990d EM |
749 | //add contact id |
750 | $data['contact_id'] = $contactID; | |
751 | $primaryLocationType = CRM_Contact_BAO_Contact::getPrimaryLocationType($contactID); | |
92ff9509 EM |
752 | |
753 | $billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling(); | |
754 | ||
755 | $blocks = ['email', 'phone', 'im', 'openid']; | |
756 | ||
757 | $multiplFields = ['url']; | |
758 | // prevent overwritten of formatted array, reset all block from | |
759 | // params if it is not in valid format (since import pass valid format) | |
760 | foreach ($blocks as $blk) { | |
761 | if (array_key_exists($blk, $params) && | |
762 | !is_array($params[$blk]) | |
763 | ) { | |
764 | unset($params[$blk]); | |
765 | } | |
766 | } | |
767 | ||
768 | $primaryPhoneLoc = NULL; | |
769 | $session = CRM_Core_Session::singleton(); | |
770 | foreach ($params as $key => $value) { | |
771 | [$fieldName, $locTypeId, $typeId] = CRM_Utils_System::explode('-', $key, 3); | |
772 | ||
773 | if ($locTypeId == 'Primary') { | |
d40d990d EM |
774 | if (in_array($fieldName, $blocks)) { |
775 | $locTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($contactID, FALSE, $fieldName); | |
92ff9509 EM |
776 | } |
777 | else { | |
d40d990d | 778 | $locTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($contactID, FALSE, 'address'); |
92ff9509 | 779 | } |
d40d990d | 780 | $primaryLocationType = $locTypeId; |
92ff9509 EM |
781 | } |
782 | ||
783 | if (is_numeric($locTypeId) && | |
784 | !in_array($fieldName, $multiplFields) && | |
785 | substr($fieldName, 0, 7) != 'custom_' | |
786 | ) { | |
787 | $index = $locTypeId; | |
788 | ||
789 | if (is_numeric($typeId)) { | |
790 | $index .= '-' . $typeId; | |
791 | } | |
792 | if (!in_array($index, $locationType)) { | |
793 | $locationType[$count] = $index; | |
794 | $count++; | |
795 | } | |
796 | ||
797 | $loc = CRM_Utils_Array::key($index, $locationType); | |
798 | ||
799 | $blockName = self::getLocationEntityForKey($fieldName); | |
800 | ||
801 | $data[$blockName][$loc]['location_type_id'] = $locTypeId; | |
802 | ||
803 | //set is_billing true, for location type "Billing" | |
804 | if ($locTypeId == $billingLocationTypeId) { | |
805 | $data[$blockName][$loc]['is_billing'] = 1; | |
806 | } | |
807 | ||
808 | if ($contactID) { | |
809 | //get the primary location type | |
810 | if ($locTypeId == $primaryLocationType) { | |
811 | $data[$blockName][$loc]['is_primary'] = 1; | |
812 | } | |
813 | } | |
814 | elseif ($locTypeId == $defaultLocationId) { | |
815 | $data[$blockName][$loc]['is_primary'] = 1; | |
816 | } | |
817 | ||
818 | if (in_array($fieldName, ['phone'])) { | |
819 | if ($typeId) { | |
820 | $data['phone'][$loc]['phone_type_id'] = $typeId; | |
821 | } | |
822 | else { | |
823 | $data['phone'][$loc]['phone_type_id'] = ''; | |
824 | } | |
825 | $data['phone'][$loc]['phone'] = $value; | |
826 | ||
827 | //special case to handle primary phone with different phone types | |
828 | // in this case we make first phone type as primary | |
829 | if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) { | |
830 | $primaryPhoneLoc = $loc; | |
831 | } | |
832 | ||
833 | if ($loc != $primaryPhoneLoc) { | |
834 | unset($data['phone'][$loc]['is_primary']); | |
835 | } | |
836 | } | |
837 | elseif ($fieldName == 'email') { | |
838 | $data['email'][$loc]['email'] = $value; | |
839 | if (empty($contactID)) { | |
840 | $data['email'][$loc]['is_primary'] = 1; | |
841 | } | |
842 | } | |
843 | elseif ($fieldName == 'im') { | |
844 | if (isset($params[$key . '-provider_id'])) { | |
845 | $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id']; | |
846 | } | |
847 | if (strpos($key, '-provider_id') !== FALSE) { | |
848 | $data['im'][$loc]['provider_id'] = $params[$key]; | |
849 | } | |
850 | else { | |
851 | $data['im'][$loc]['name'] = $value; | |
852 | } | |
853 | } | |
854 | elseif ($fieldName == 'openid') { | |
855 | $data['openid'][$loc]['openid'] = $value; | |
856 | } | |
857 | else { | |
858 | if ($fieldName === 'state_province') { | |
859 | // CRM-3393 | |
860 | if (is_numeric($value) && ((int ) $value) >= 1000) { | |
861 | $data['address'][$loc]['state_province_id'] = $value; | |
862 | } | |
863 | elseif (empty($value)) { | |
864 | $data['address'][$loc]['state_province_id'] = ''; | |
865 | } | |
866 | else { | |
867 | $data['address'][$loc]['state_province'] = $value; | |
868 | } | |
869 | } | |
870 | elseif ($fieldName === 'country') { | |
871 | // CRM-3393 | |
872 | if (is_numeric($value) && ((int ) $value) >= 1000 | |
873 | ) { | |
874 | $data['address'][$loc]['country_id'] = $value; | |
875 | } | |
876 | elseif (empty($value)) { | |
877 | $data['address'][$loc]['country_id'] = ''; | |
878 | } | |
879 | else { | |
880 | $data['address'][$loc]['country'] = $value; | |
881 | } | |
882 | } | |
883 | elseif ($fieldName === 'county') { | |
884 | $data['address'][$loc]['county_id'] = $value; | |
885 | } | |
886 | elseif ($fieldName == 'address_name') { | |
887 | $data['address'][$loc]['name'] = $value; | |
888 | } | |
889 | elseif (substr($fieldName, 0, 14) === 'address_custom') { | |
890 | $data['address'][$loc][substr($fieldName, 8)] = $value; | |
891 | } | |
892 | else { | |
893 | $data[$blockName][$loc][$fieldName] = $value; | |
894 | } | |
895 | } | |
896 | } | |
897 | else { | |
898 | if (substr($key, 0, 4) === 'url-') { | |
899 | $websiteField = explode('-', $key); | |
900 | $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1]; | |
901 | $data['website'][$websiteField[1]]['url'] = $value; | |
902 | } | |
903 | elseif (in_array($key, CRM_Contact_BAO_Contact::$_greetingTypes, TRUE)) { | |
904 | //save email/postal greeting and addressee values if any, CRM-4575 | |
905 | $data[$key . '_id'] = $value; | |
906 | } | |
6822d198 | 907 | elseif (($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) { |
92ff9509 EM |
908 | // for autocomplete transfer hidden value instead of label |
909 | if ($params[$key] && isset($params[$key . '_id'])) { | |
910 | $value = $params[$key . '_id']; | |
911 | } | |
912 | ||
913 | // we need to append time with date | |
914 | if ($params[$key] && isset($params[$key . '_time'])) { | |
915 | $value .= ' ' . $params[$key . '_time']; | |
916 | } | |
917 | ||
918 | // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128 | |
919 | if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 && | |
920 | ($value == '' || !isset($value)) | |
921 | ) { | |
922 | continue; | |
923 | } | |
924 | ||
925 | $valueId = NULL; | |
926 | if (!empty($params['customRecordValues'])) { | |
927 | if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) { | |
928 | foreach ($params['customRecordValues'] as $recId => $customFields) { | |
929 | if (is_array($customFields) && !empty($customFields)) { | |
930 | foreach ($customFields as $customFieldName) { | |
931 | if ($customFieldName == $key) { | |
932 | $valueId = $recId; | |
933 | break; | |
934 | } | |
935 | } | |
936 | } | |
937 | } | |
938 | } | |
939 | } | |
940 | ||
941 | //CRM-13596 - check for contact_sub_type_hidden first | |
942 | if (array_key_exists('contact_sub_type_hidden', $params)) { | |
943 | $type = $params['contact_sub_type_hidden']; | |
944 | } | |
945 | else { | |
946 | $type = $data['contact_type']; | |
947 | if (!empty($data['contact_sub_type'])) { | |
948 | $type = CRM_Utils_Array::explodePadded($data['contact_sub_type']); | |
949 | } | |
950 | } | |
951 | ||
952 | CRM_Core_BAO_CustomField::formatCustomField($customFieldId, | |
953 | $data['custom'], | |
954 | $value, | |
955 | $type, | |
956 | $valueId, | |
957 | $contactID, | |
958 | FALSE, | |
959 | FALSE | |
960 | ); | |
961 | } | |
962 | elseif ($key === 'edit') { | |
963 | continue; | |
964 | } | |
965 | else { | |
966 | if ($key === 'location') { | |
967 | foreach ($value as $locationTypeId => $field) { | |
968 | foreach ($field as $block => $val) { | |
969 | if ($block === 'address' && array_key_exists('address_name', $val)) { | |
970 | $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name']; | |
971 | } | |
972 | } | |
973 | } | |
974 | } | |
975 | if ($key === 'phone' && isset($params['phone_ext'])) { | |
976 | $data[$key] = $value; | |
977 | foreach ($value as $cnt => $phoneBlock) { | |
978 | if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) { | |
979 | $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext'); | |
980 | } | |
981 | } | |
982 | } | |
983 | elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id']) | |
984 | && ($value == '' || !isset($value)) && | |
985 | ($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 || | |
986 | ($key === 'current_employer' && empty($params['current_employer']))) { | |
987 | // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value | |
988 | // to avoid update with empty values | |
989 | continue; | |
990 | } | |
991 | else { | |
992 | $data[$key] = $value; | |
993 | } | |
994 | } | |
995 | } | |
996 | } | |
997 | ||
998 | if (!isset($data['contact_type'])) { | |
999 | $data['contact_type'] = 'Individual'; | |
1000 | } | |
1001 | ||
6822d198 | 1002 | return $data; |
92ff9509 EM |
1003 | } |
1004 | ||
1005 | /** | |
1006 | * Get the relevant location entity for the array key. | |
1007 | * | |
1008 | * This function is duplicated from CRM_Contact_BAO_Contact to allow cleanup. | |
1009 | * See self::formatProfileContactParams | |
1010 | * | |
1011 | * Based on the field name we determine which location entity | |
1012 | * we are dealing with. Apart from a few specific ones they | |
1013 | * are mostly 'address' (the default). | |
1014 | * | |
1015 | * @param string $fieldName | |
1016 | * | |
1017 | * @return string | |
1018 | */ | |
1019 | protected static function getLocationEntityForKey($fieldName) { | |
1020 | if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) { | |
1021 | return $fieldName; | |
1022 | } | |
1023 | if ($fieldName === 'phone_ext') { | |
1024 | return 'phone'; | |
1025 | } | |
1026 | return 'address'; | |
1027 | } | |
1028 | ||
6a488035 | 1029 | /** |
4eea8606 | 1030 | * Load all non-empty fields for the contacts |
b3fdbf3d | 1031 | * |
98997235 TO |
1032 | * @param array $main |
1033 | * Contact details. | |
1034 | * @param array $other | |
1035 | * Contact details. | |
6a488035 | 1036 | * |
77b97be7 | 1037 | * @return array |
723c5a81 | 1038 | * |
1039 | * @throws \CRM_Core_Exception | |
6a488035 | 1040 | */ |
4eea8606 | 1041 | public static function retrieveFields($main, $other) { |
2c16165a | 1042 | $result = [ |
1043 | 'contact' => [], | |
1044 | 'custom' => [], | |
1045 | ]; | |
16254ae1 | 1046 | foreach (self::getContactFields() as $validField) { |
eb61dc07 J |
1047 | // CRM-17556 Get all non-empty fields, to make comparison easier |
1048 | if (!empty($main[$validField]) || !empty($other[$validField])) { | |
6a488035 TO |
1049 | $result['contact'][] = $validField; |
1050 | } | |
1051 | } | |
1052 | ||
1053 | $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']); | |
1054 | $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']); | |
1055 | $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs))); | |
1056 | foreach ($keys as $key) { | |
76c53278 CW |
1057 | // Exclude multi-value fields CRM-13836 |
1058 | if (strpos($key, '_')) { | |
1059 | continue; | |
1060 | } | |
9c1bc317 CW |
1061 | $key1 = $mainEvs[$key] ?? NULL; |
1062 | $key2 = $otherEvs[$key] ?? NULL; | |
26b7ff28 | 1063 | // We wish to retain '0' as it has a different meaning than NULL on a checkbox. |
1064 | // However I can't think of a case where an empty string is more meaningful than null | |
1065 | // or where it would be FALSE or something else nullish. | |
1066 | $valuesToIgnore = [NULL, '', []]; | |
1067 | if (!in_array($key1, $valuesToIgnore, TRUE) || !in_array($key2, $valuesToIgnore, TRUE)) { | |
6a488035 TO |
1068 | $result['custom'][] = $key; |
1069 | } | |
1070 | } | |
1071 | return $result; | |
1072 | } | |
1073 | ||
1074 | /** | |
100fef9d | 1075 | * Batch merge a set of contacts based on rule-group and group. |
6a488035 | 1076 | * |
98997235 TO |
1077 | * @param int $rgid |
1078 | * Rule group id. | |
1079 | * @param int $gid | |
1080 | * Group id. | |
1081 | * @param string $mode | |
1082 | * Helps decide how to behave when there are conflicts. | |
15a793bb EM |
1083 | * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive' |
1084 | * mode does a force merge. | |
f931b74c | 1085 | * @param int $batchLimit number of merges to carry out in one batch. |
1086 | * @param int $isSelected if records with is_selected column needs to be processed. | |
bb22928b | 1087 | * Note the option of '2' is only used in conjunction with $redirectForPerformance |
b5a6c6c5 | 1088 | * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered |
1089 | * out in favour of explicitly passing in $reloadCacheIfEmpty | |
6a488035 | 1090 | * |
e23e26ec | 1091 | * @param array $criteria |
1092 | * Criteria to use in the filter. | |
1093 | * | |
3058f4d9 | 1094 | * @param bool $checkPermissions |
1095 | * Respect logged in user permissions. | |
2024d5b9 | 1096 | * @param bool|null $reloadCacheIfEmpty |
bb22928b | 1097 | * If not set explicitly this is calculated but it is preferred that it be set |
1098 | * per comments on isSelected above. | |
3058f4d9 | 1099 | * |
997a03fe | 1100 | * @param int $searchLimit |
1101 | * Limit on number of contacts to search for duplicates for. | |
1102 | * This means that if the limit is 1000 then only duplicates for the first 1000 contacts | |
1103 | * matching criteria will be found and batchMerged (the number of merges could be less than or greater than 100) | |
1104 | * | |
77b97be7 | 1105 | * @return array|bool |
997a03fe | 1106 | * |
1107 | * @throws \CRM_Core_Exception | |
1108 | * @throws \CiviCRM_API3_Exception | |
96a118e6 | 1109 | * @throws \API_Exception |
6a488035 | 1110 | */ |
997a03fe | 1111 | public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL, $searchLimit = 0) { |
f7dbf5d9 | 1112 | $redirectForPerformance = $batchLimit > 1; |
418ffc5b | 1113 | if ($mode === 'aggressive' && $checkPermissions && !CRM_Core_Permission::check('force merge duplicate contacts')) { |
1114 | throw new CRM_Core_Exception(ts('Insufficient permissions for aggressive mode batch merge')); | |
1115 | } | |
bb22928b | 1116 | if (!isset($reloadCacheIfEmpty)) { |
1117 | $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2); | |
1118 | } | |
1119 | if ($isSelected !== 0 && $isSelected !== 1) { | |
1120 | // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value. | |
1121 | $isSelected = NULL; | |
1122 | } | |
723c5a81 | 1123 | $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode === 'aggressive'), $criteria, $checkPermissions, $searchLimit); |
6a488035 | 1124 | |
2c16165a | 1125 | $cacheParams = [ |
997a03fe | 1126 | 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions, $searchLimit), |
2988f5c7 | 1127 | // @todo stop passing these parameters in & instead calculate them in the merge function based |
1128 | // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected. | |
1129 | 'join' => self::getJoinOnDedupeTable(), | |
ed3c1599 | 1130 | 'where' => self::getWhereString($isSelected), |
1131 | 'limit' => (int) $batchLimit, | |
2c16165a | 1132 | ]; |
d238756a | 1133 | return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions); |
6a488035 TO |
1134 | } |
1135 | ||
2ae26001 | 1136 | /** |
1137 | * Get the string to join the prevnext cache to the dedupe table. | |
1138 | * | |
1139 | * @return string | |
1140 | * The join string to join prevnext cache on the dedupe table. | |
1141 | */ | |
1142 | public static function getJoinOnDedupeTable() { | |
723c5a81 | 1143 | return ' |
2ae26001 | 1144 | LEFT JOIN civicrm_dedupe_exception de |
1145 | ON ( | |
1146 | pn.entity_id1 = de.contact_id1 | |
1147 | AND pn.entity_id2 = de.contact_id2 ) | |
723c5a81 | 1148 | '; |
2ae26001 | 1149 | } |
1150 | ||
2988f5c7 | 1151 | /** |
1152 | * Get where string for dedupe join. | |
1153 | * | |
2988f5c7 | 1154 | * @param bool $isSelected |
1155 | * | |
1156 | * @return string | |
1157 | */ | |
ed3c1599 | 1158 | protected static function getWhereString($isSelected) { |
723c5a81 | 1159 | $where = 'de.id IS NULL'; |
2988f5c7 | 1160 | if ($isSelected === 0 || $isSelected === 1) { |
1161 | $where .= " AND pn.is_selected = {$isSelected}"; | |
1162 | } | |
2988f5c7 | 1163 | return $where; |
1164 | } | |
1165 | ||
bc854509 | 1166 | /** |
1167 | * Update the statistics for the merge set. | |
1168 | * | |
1169 | * @param string $cacheKeyString | |
1170 | * @param array $result | |
723c5a81 | 1171 | * |
1172 | * @throws \CiviCRM_API3_Exception | |
bc854509 | 1173 | */ |
2c16165a | 1174 | public static function updateMergeStats($cacheKeyString, $result = []) { |
63ef778e | 1175 | // gather latest stats |
2c16165a | 1176 | $merged = count($result['merged']); |
63ef778e | 1177 | $skipped = count($result['skipped']); |
1178 | ||
1179 | if ($merged <= 0 && $skipped <= 0) { | |
1180 | return; | |
1181 | } | |
1182 | ||
1183 | // get previous stats | |
e13fa54b | 1184 | $previousStats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString); |
63ef778e | 1185 | if (!empty($previousStats)) { |
e13fa54b | 1186 | if ($previousStats['merged']) { |
1187 | $merged = $merged + $previousStats['merged']; | |
63ef778e | 1188 | } |
e13fa54b | 1189 | if ($previousStats['skipped']) { |
1190 | $skipped = $skipped + $previousStats['skipped']; | |
63ef778e | 1191 | } |
1192 | } | |
1193 | ||
1194 | // delete old stats | |
1195 | CRM_Dedupe_Merger::resetMergeStats($cacheKeyString); | |
1196 | ||
1197 | // store the updated stats | |
2c16165a | 1198 | $data = [ |
3bcde7f1 | 1199 | 'merged' => (int) $merged, |
1200 | 'skipped' => (int) $skipped, | |
2c16165a | 1201 | ]; |
63ef778e | 1202 | |
3bcde7f1 | 1203 | CRM_Core_DAO::executeQuery("INSERT INTO civicrm_prevnext_cache (entity_table, entity_id1, entity_id2, cacheKey, data) VALUES |
2e09a60f | 1204 | ('civicrm_contact', 0, 0, %1, %2)", [1 => [$cacheKeyString . '_stats', 'String'], 2 => [serialize($data), 'String']]); |
63ef778e | 1205 | } |
1206 | ||
ae6455b2 | 1207 | /** |
1208 | * Delete information about merges for the given string. | |
1209 | * | |
1210 | * @param $cacheKeyString | |
1211 | */ | |
f931b74c | 1212 | public static function resetMergeStats($cacheKeyString) { |
ae6455b2 | 1213 | CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats"); |
63ef778e | 1214 | } |
1215 | ||
bc854509 | 1216 | /** |
1217 | * Get merge outcome statistics. | |
1218 | * | |
1219 | * @param string $cacheKeyString | |
1220 | * | |
1221 | * @return array | |
1222 | * Array of how many were merged and how many were skipped. | |
e13fa54b | 1223 | * |
1224 | * @throws \CiviCRM_API3_Exception | |
bc854509 | 1225 | */ |
f931b74c | 1226 | public static function getMergeStats($cacheKeyString) { |
e13fa54b | 1227 | $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values']; |
63ef778e | 1228 | if (!empty($stats)) { |
e13fa54b | 1229 | return $stats[0]['data']; |
63ef778e | 1230 | } |
e13fa54b | 1231 | return []; |
63ef778e | 1232 | } |
1233 | ||
bc854509 | 1234 | /** |
1235 | * Get merge statistics message. | |
1236 | * | |
3743fd3d | 1237 | * @param array $stats |
bc854509 | 1238 | * |
1239 | * @return string | |
1240 | */ | |
3743fd3d CW |
1241 | public static function getMergeStatsMsg($stats) { |
1242 | $msg = ''; | |
63ef778e | 1243 | if (!empty($stats['merged'])) { |
2c16165a | 1244 | $msg = '<p>' . ts('One contact merged.', [ |
518fa0ee SL |
1245 | 'count' => $stats['merged'], |
1246 | 'plural' => '%count contacts merged.', | |
1247 | ]) . '</p>'; | |
63ef778e | 1248 | } |
1249 | if (!empty($stats['skipped'])) { | |
2c16165a | 1250 | $msg .= '<p>' . ts('One contact was skipped.', [ |
518fa0ee SL |
1251 | 'count' => $stats['skipped'], |
1252 | 'plural' => '%count contacts were skipped.', | |
1253 | ]) . '</p>'; | |
63ef778e | 1254 | } |
1255 | return $msg; | |
1256 | } | |
1257 | ||
6a488035 | 1258 | /** |
100fef9d | 1259 | * Merge given set of contacts. Performs core operation. |
6a488035 | 1260 | * |
98997235 TO |
1261 | * @param array $dupePairs |
1262 | * Set of pair of contacts for whom merge is to be done. | |
1263 | * @param array $cacheParams | |
1264 | * Prev-next-cache params based on which next pair of contacts are computed. | |
6a488035 | 1265 | * Generally used with batch-merge. |
98997235 TO |
1266 | * @param string $mode |
1267 | * Helps decide how to behave when there are conflicts. | |
6a488035 TO |
1268 | * A 'safe' value skips the merge if there are any un-resolved conflicts. |
1269 | * Does a force merge otherwise (aggressive mode). | |
6a488035 | 1270 | * |
77b97be7 | 1271 | * @param bool $redirectForPerformance |
3058f4d9 | 1272 | * Redirect to a url for batch processing. |
1273 | * | |
1274 | * @param bool $checkPermissions | |
1275 | * Respect logged in user permissions. | |
77b97be7 EM |
1276 | * |
1277 | * @return array|bool | |
b068bfde | 1278 | * |
1279 | * @throws \API_Exception | |
1280 | * @throws \CRM_Core_Exception | |
1281 | * @throws \CiviCRM_API3_Exception | |
6a488035 | 1282 | */ |
2c16165a | 1283 | public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe', |
1284 | $redirectForPerformance = FALSE, $checkPermissions = TRUE | |
6a488035 | 1285 | ) { |
9c1bc317 | 1286 | $cacheKeyString = $cacheParams['cache_key_string'] ?? NULL; |
2c16165a | 1287 | $resultStats = ['merged' => [], 'skipped' => []]; |
6a488035 TO |
1288 | |
1289 | // we don't want dupe caching to get reset after every-merge, and therefore set the | |
0626851e | 1290 | CRM_Core_Config::setPermitCacheFlushMode(FALSE); |
2c16165a | 1291 | $deletedContacts = []; |
6a488035 TO |
1292 | |
1293 | while (!empty($dupePairs)) { | |
78272750 | 1294 | foreach ($dupePairs as $index => $dupes) { |
1295 | if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) { | |
1296 | unset($dupePairs[$index]); | |
1297 | continue; | |
1298 | } | |
a6b7cfc6 | 1299 | CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']); |
1300 | if (($result = self::dedupePair((int) $dupes['dstID'], (int) $dupes['srcID'], $mode, $checkPermissions, $cacheKeyString)) === FALSE) { | |
b068bfde | 1301 | unset($dupePairs[$index]); |
1302 | continue; | |
1303 | } | |
1304 | if (!empty($result['merged'])) { | |
1305 | $deletedContacts[] = $result['merged'][0]['other_id']; | |
1306 | $resultStats['merged'][] = ($result['merged'][0]); | |
1307 | } | |
1308 | else { | |
1309 | $resultStats['skipped'][] = ($result['skipped'][0]); | |
6a488035 | 1310 | } |
6a488035 TO |
1311 | } |
1312 | ||
1313 | if ($cacheKeyString && !$redirectForPerformance) { | |
1314 | // retrieve next pair of dupes | |
2988f5c7 | 1315 | // @todo call getDuplicatePairs. |
6a488035 TO |
1316 | $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, |
1317 | $cacheParams['join'], | |
66eceb0b | 1318 | $cacheParams['where'], |
1319 | 0, | |
ed3c1599 | 1320 | $cacheParams['limit'], |
2c16165a | 1321 | [], |
66eceb0b | 1322 | '', |
1323 | FALSE | |
6a488035 TO |
1324 | ); |
1325 | } | |
1326 | else { | |
1327 | // do not proceed. Terminate the loop | |
1328 | unset($dupePairs); | |
1329 | } | |
1330 | } | |
63ef778e | 1331 | |
1332 | CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats); | |
6a488035 TO |
1333 | return $resultStats; |
1334 | } | |
1335 | ||
1336 | /** | |
1337 | * A function which uses various rules / algorithms for choosing which contact to bias to | |
1338 | * when there's a conflict (to handle "gotchas"). Plus the safest route to merge. | |
1339 | * | |
98997235 TO |
1340 | * @param int $mainId |
1341 | * Main contact with whom merge has to happen. | |
1342 | * @param int $otherId | |
1343 | * Duplicate contact which would be deleted after merge operation. | |
1344 | * @param array $migrationInfo | |
1345 | * Array of information about which elements to merge. | |
1346 | * @param string $mode | |
1347 | * Helps decide how to behave when there are conflicts. | |
13919cf8 J |
1348 | * - A 'safe' value skips the merge if there are any un-resolved conflicts. |
1349 | * - Does a force merge otherwise (aggressive mode). | |
6a488035 | 1350 | * |
ad37ac8e | 1351 | * @param array $conflicts |
a2abc387 | 1352 | * An empty array to be filed with conflict information. |
ad37ac8e | 1353 | * |
77b97be7 | 1354 | * @return bool |
ffa59d18 | 1355 | * |
1356 | * @throws \CRM_Core_Exception | |
1357 | * @throws \CiviCRM_API3_Exception | |
1358 | * @throws \API_Exception | |
6a488035 | 1359 | */ |
2c16165a | 1360 | public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) { |
0971143c | 1361 | |
e908d4ab | 1362 | $conflicts = self::getConflicts($migrationInfo, (int) $mainId, (int) $otherId, $mode)['conflicts']; |
d73a022b | 1363 | // A hook could have set skip_merge in order to alter merge behaviour. |
1364 | // This is a something we might ideally deprecate since they really 'should' | |
1365 | // mess with the conflicts array instead. | |
1366 | return (bool) ($migrationData['skip_merge'] ?? !empty($conflicts)); | |
6a488035 TO |
1367 | } |
1368 | ||
d48ad2c0 | 1369 | /** |
ffcc831f | 1370 | * Compare 2 addresses to see if they are the effectively the same. |
1371 | * | |
1372 | * Being the same would mean same location type and any populated fields that describe the locationn match. | |
1373 | * | |
1374 | * Metadata fields such as is_primary, on_hold, manual_geocode may differ. | |
d48ad2c0 | 1375 | * |
1376 | * @param array $mainAddress | |
1377 | * @param array $comparisonAddress | |
1378 | * | |
1379 | * @return bool | |
1380 | */ | |
518fa0ee | 1381 | public static function locationIsSame($mainAddress, $comparisonAddress) { |
ffa59d18 | 1382 | $keysToIgnore = self::ignoredFields(); |
d48ad2c0 | 1383 | foreach ($comparisonAddress as $field => $value) { |
1384 | if (in_array($field, $keysToIgnore)) { | |
1385 | continue; | |
1386 | } | |
00443529 | 1387 | if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) { |
d48ad2c0 | 1388 | return FALSE; |
1389 | } | |
1390 | } | |
1391 | return TRUE; | |
1392 | } | |
1393 | ||
ffcc831f | 1394 | /** |
1395 | * Does the location array have valid data. | |
1396 | * | |
1397 | * While not UI-creatable some sites wind up with email or address rows with no actual email or address | |
1398 | * through non core-UI processes. | |
1399 | * | |
1400 | * @param array $location | |
1401 | * | |
1402 | * @return bool | |
1403 | */ | |
1404 | public static function locationHasData($location) { | |
1405 | return !empty(self::getLocationDataFields($location)); | |
1406 | } | |
1407 | ||
1408 | /** | |
1409 | * Get the location data from a location array, filtering out metadata. | |
1410 | * | |
1411 | * This returns data like street_address but not metadata like is_primary, on_hold etc. | |
1412 | * | |
1413 | * @param array $location | |
1414 | * | |
1415 | * @return mixed | |
1416 | */ | |
1417 | public static function getLocationDataFields($location) { | |
1418 | $keysToIgnore = array_merge(self::ignoredFields(), ['display', 'location_type_id']); | |
1419 | foreach ($location as $field => $value) { | |
1420 | if (in_array($field, $keysToIgnore, TRUE)) { | |
1421 | unset($location[$field]); | |
1422 | } | |
1423 | } | |
1424 | return $location; | |
1425 | } | |
1426 | ||
34917198 J |
1427 | /** |
1428 | * A function to build an array of information about location blocks that is | |
1429 | * required when merging location fields | |
1430 | * | |
1431 | * @return array | |
1432 | */ | |
1433 | public static function getLocationBlockInfo() { | |
723c5a81 | 1434 | return [ |
2c16165a | 1435 | 'address' => [ |
34917198 J |
1436 | 'label' => 'Address', |
1437 | 'displayField' => 'display', | |
1438 | 'sortString' => 'location_type_id', | |
1439 | 'hasLocation' => TRUE, | |
1440 | 'hasType' => FALSE, | |
2c16165a | 1441 | ], |
1442 | 'email' => [ | |
34917198 | 1443 | 'label' => 'Email', |
2a7e1ddc | 1444 | 'displayField' => 'display', |
34917198 J |
1445 | 'sortString' => 'location_type_id', |
1446 | 'hasLocation' => TRUE, | |
1447 | 'hasType' => FALSE, | |
2c16165a | 1448 | ], |
1449 | 'im' => [ | |
34917198 J |
1450 | 'label' => 'IM', |
1451 | 'displayField' => 'name', | |
1452 | 'sortString' => 'location_type_id,provider_id', | |
1453 | 'hasLocation' => TRUE, | |
1454 | 'hasType' => 'provider_id', | |
2c16165a | 1455 | ], |
1456 | 'phone' => [ | |
34917198 J |
1457 | 'label' => 'Phone', |
1458 | 'displayField' => 'phone', | |
1459 | 'sortString' => 'location_type_id,phone_type_id', | |
1460 | 'hasLocation' => TRUE, | |
1461 | 'hasType' => 'phone_type_id', | |
2c16165a | 1462 | ], |
1463 | 'website' => [ | |
34917198 J |
1464 | 'label' => 'Website', |
1465 | 'displayField' => 'url', | |
1466 | 'sortString' => 'website_type_id', | |
1467 | 'hasLocation' => FALSE, | |
1468 | 'hasType' => 'website_type_id', | |
2c16165a | 1469 | ], |
1470 | ]; | |
34917198 J |
1471 | } |
1472 | ||
6a488035 TO |
1473 | /** |
1474 | * A function to build an array of information required by merge function and the merge UI. | |
1475 | * | |
98997235 TO |
1476 | * @param int $mainId |
1477 | * Main contact with whom merge has to happen. | |
1478 | * @param int $otherId | |
1479 | * Duplicate contact which would be deleted after merge operation. | |
201057c0 | 1480 | * @param bool $checkPermissions |
1481 | * Should the logged in user's permissions be ignore. Setting this to false is | |
1482 | * highly risky as it could cause data to be lost due to conflicts not showing up. | |
1483 | * OTOH there is a risk a merger might view custom data they do not have permission to. | |
1484 | * Hence for now only making this really explicit and making it reflect perms in | |
1485 | * an api call. | |
1486 | * | |
1487 | * @todo review permissions issue! | |
6a488035 | 1488 | * |
77b97be7 | 1489 | * @return array|bool|int |
1e3e0eed J |
1490 | * |
1491 | * rows => An array of arrays, each is row of merge information for the table | |
1492 | * Format: move_fieldname, eg: move_contact_type | |
1493 | * main => Value associated with the main contact | |
1494 | * other => Value associated with the other contact | |
1495 | * title => The title of the field to display in the merge table | |
1496 | * | |
1497 | * elements => An array of form elements for the merge UI | |
1498 | * | |
1e3e0eed J |
1499 | * rel_tables => Stores the tables that have related entities for the contact |
1500 | * for example mailings, groups | |
1501 | * | |
1502 | * main_details => An array of core contact field values, eg: first_name, etc. | |
1503 | * location_blocks => An array of location block data for the main contact | |
1504 | * stored as the 'result' of an API call. | |
1505 | * eg: main_details['location_blocks']['address'][0]['id'] | |
1506 | * eg: main_details['location_blocks']['email'][1]['id'] | |
1507 | * | |
1508 | * other_details => As above, but for the 'other' contact | |
1509 | * | |
1510 | * migration_info => Stores the 'default' merge actions for each field which | |
1511 | * is used when programatically merging contacts. It contains instructions | |
1512 | * to move all fields from the 'other' contact to the 'main' contact, as | |
1513 | * though the form had been submitted with those options. | |
1514 | * | |
3058f4d9 | 1515 | * @throws \CRM_Core_Exception |
1516 | * @throws \CiviCRM_API3_Exception | |
6a488035 | 1517 | */ |
201057c0 | 1518 | public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) { |
6a488035 | 1519 | $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; |
74a6069d | 1520 | $fields = self::getMergeFieldsMetadata(); |
6a488035 | 1521 | |
fcc3d8ee | 1522 | $main = self::getMergeContactDetails($mainId); |
1523 | $other = self::getMergeContactDetails($otherId); | |
6a488035 | 1524 | |
4eea8606 | 1525 | $compareFields = self::retrieveFields($main, $other); |
6a488035 | 1526 | |
c813e8f4 | 1527 | $rows = $elements = $migrationInfo = []; |
6a488035 | 1528 | |
4eea8606 | 1529 | foreach ($compareFields['contact'] as $field) { |
723c5a81 | 1530 | if ($field === 'contact_sub_type') { |
4d5f18cc | 1531 | // CRM-15681 don't display sub-types in UI |
1532 | continue; | |
1533 | } | |
1ce87307 | 1534 | $rows["move_$field"] = [ |
1535 | 'main' => self::getFieldValueAndLabel($field, $main)['label'], | |
1536 | 'other' => self::getFieldValueAndLabel($field, $other)['label'], | |
9ac33d0f | 1537 | 'title' => $fields[$field]['html']['label'] ?? $fields[$field]['title'], |
1ce87307 | 1538 | ]; |
2fd72602 | 1539 | |
bdc6e6ee | 1540 | $value = self::getFieldValueAndLabel($field, $other)['value']; |
1541 | //CRM-14334 | |
1542 | if ($value === NULL || $value == '') { | |
1543 | $value = 'null'; | |
1544 | } | |
1545 | if ($value === 0 or $value === '0') { | |
1546 | $value = $qfZeroBug; | |
1547 | } | |
1548 | if (is_array($value) && empty($value[1])) { | |
1549 | $value[1] = NULL; | |
1550 | } | |
13919cf8 | 1551 | |
bdc6e6ee | 1552 | // Display a checkbox to migrate, only if the values are different |
1553 | if ($value != $main[$field]) { | |
1554 | $elements[] = [ | |
3d1d395a | 1555 | 0 => 'advcheckbox', |
1556 | 1 => "move_$field", | |
1557 | 2 => NULL, | |
1558 | 3 => NULL, | |
1559 | 4 => NULL, | |
1560 | 5 => $value, | |
1561 | 'is_checked' => (!isset($main[$field]) || $main[$field] === ''), | |
bdc6e6ee | 1562 | ]; |
1563 | } | |
13919cf8 | 1564 | |
bdc6e6ee | 1565 | $migrationInfo["move_$field"] = $value; |
6a488035 TO |
1566 | } |
1567 | ||
eb61dc07 J |
1568 | // Handle location blocks. |
1569 | // @todo OpenID not in API yet, so is not supported here. | |
65a35632 | 1570 | |
087f00ec | 1571 | // Set up useful information about the location blocks |
34917198 | 1572 | $locationBlocks = self::getLocationBlockInfo(); |
087f00ec | 1573 | |
1a90ac89 | 1574 | $locations = ['main' => [], 'other' => []]; |
6a488035 | 1575 | |
087f00ec | 1576 | foreach ($locationBlocks as $blockName => $blockInfo) { |
e908d4ab | 1577 | [$locations, $rows, $elements, $migrationInfo] = self::addLocationFieldInfo($mainId, $otherId, $blockInfo, $blockName, $locations, $rows, $elements, $migrationInfo); |
34917198 | 1578 | } // End loop through each location block entity |
6a488035 TO |
1579 | |
1580 | // add the related tables and unset the ones that don't sport any of the duplicate contact's info | |
9287a0b7 | 1581 | $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId); |
1582 | $relTables = $mergeHandler->getTablesRelatedToTheMergePair(); | |
6a488035 | 1583 | foreach ($relTables as $name => $null) { |
6a488035 TO |
1584 | $migrationInfo["move_$name"] = 1; |
1585 | ||
1586 | $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']); | |
1587 | $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']); | |
8372e605 | 1588 | if ($name === 'rel_table_users') { |
1589 | // @todo - this user url stuff is only needed for the form layer - move to CRM_Contact_Form_Merge | |
8ac99646 | 1590 | $relTables[$name]['main_url'] = str_replace('%ufid', CRM_Core_BAO_UFMatch::getUFId($mainId), $relTables[$name]['url']); |
8372e605 | 1591 | $relTables[$name]['other_url'] = str_replace('%ufid', CRM_Core_BAO_UFMatch::getUFId($otherId), $relTables[$name]['url']); |
6a488035 | 1592 | } |
723c5a81 | 1593 | if ($name === 'rel_table_memberships') { |
7d84a47d JP |
1594 | //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact. |
1595 | $attributes = ['checked' => 'checked']; | |
1596 | $otherContactMemberships = CRM_Member_BAO_Membership::getAllContactMembership($otherId); | |
1597 | foreach ($otherContactMemberships as $membership) { | |
1598 | $mainMembership = CRM_Member_BAO_Membership::getContactMembership($mainId, $membership['membership_type_id'], FALSE); | |
1599 | if ($mainMembership) { | |
1600 | $attributes = []; | |
1601 | } | |
1602 | } | |
2c16165a | 1603 | $elements[] = [ |
1604 | 'checkbox', | |
1605 | "operation[move_{$name}][add]", | |
1606 | NULL, | |
1607 | ts('add new'), | |
1608 | $attributes, | |
1609 | ]; | |
6a488035 TO |
1610 | $migrationInfo["operation"]["move_{$name}"]['add'] = 1; |
1611 | } | |
1612 | } | |
1613 | foreach ($relTables as $name => $null) { | |
1614 | $relTables["move_$name"] = $relTables[$name]; | |
1615 | unset($relTables[$name]); | |
1616 | } | |
1617 | ||
1618 | // handle custom fields | |
201057c0 | 1619 | $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1, |
317103ab CW |
1620 | CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, |
1621 | $checkPermissions ? CRM_Core_Permission::EDIT : FALSE | |
6a488035 | 1622 | ); |
0b330e6d | 1623 | $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1, |
317103ab CW |
1624 | CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, |
1625 | $checkPermissions ? CRM_Core_Permission::EDIT : FALSE | |
6a488035 | 1626 | ); |
6a488035 TO |
1627 | |
1628 | foreach ($otherTree as $gid => $group) { | |
6a488035 TO |
1629 | if (!isset($group['fields'])) { |
1630 | continue; | |
1631 | } | |
1632 | ||
1633 | foreach ($group['fields'] as $fid => $field) { | |
b1ff97eb | 1634 | $mainContactValue = $mainTree[$gid]['fields'][$fid]['customValue'] ?? NULL; |
1635 | $otherContactValue = $otherTree[$gid]['fields'][$fid]['customValue'] ?? NULL; | |
4eea8606 | 1636 | if (in_array($fid, $compareFields['custom'])) { |
b1ff97eb | 1637 | $rows["custom_group_$gid"]['title'] = $rows["custom_group_$gid"]['title'] ?? $group['title']; |
1638 | ||
1639 | if ($mainContactValue) { | |
1640 | foreach ($mainContactValue as $valueId => $values) { | |
51a3717f | 1641 | $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid); |
6a488035 TO |
1642 | } |
1643 | } | |
b1ff97eb | 1644 | $value = 'null'; |
1645 | if ($otherContactValue) { | |
1646 | foreach ($otherContactValue as $valueId => $values) { | |
51a3717f | 1647 | $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid); |
6a488035 TO |
1648 | if ($values['data'] === 0 || $values['data'] === '0') { |
1649 | $values['data'] = $qfZeroBug; | |
d58a19a1 | 1650 | } |
6a488035 | 1651 | $value = ($values['data']) ? $values['data'] : $value; |
d58a19a1 | 1652 | } |
6a488035 TO |
1653 | } |
1654 | $rows["move_custom_$fid"]['title'] = $field['label']; | |
1655 | ||
2c16165a | 1656 | $elements[] = [ |
97be1890 | 1657 | 0 => 'advcheckbox', |
1658 | 1 => "move_custom_$fid", | |
1659 | 2 => NULL, | |
1660 | 3 => NULL, | |
1661 | 4 => NULL, | |
1662 | 5 => $value, | |
1663 | 'is_checked' => (!isset($rows["move_custom_$fid"]['main']) || $rows["move_custom_$fid"]['main'] === ''), | |
2c16165a | 1664 | ]; |
6a488035 TO |
1665 | $migrationInfo["move_custom_$fid"] = $value; |
1666 | } | |
1667 | } | |
1668 | } | |
abb422f9 | 1669 | |
2c16165a | 1670 | $result = [ |
6a488035 TO |
1671 | 'rows' => $rows, |
1672 | 'elements' => $elements, | |
6a488035 TO |
1673 | 'rel_tables' => $relTables, |
1674 | 'main_details' => $main, | |
1675 | 'other_details' => $other, | |
1676 | 'migration_info' => $migrationInfo, | |
2c16165a | 1677 | ]; |
6a488035 | 1678 | |
34917198 J |
1679 | $result['main_details']['location_blocks'] = $locations['main']; |
1680 | $result['other_details']['location_blocks'] = $locations['other']; | |
6a488035 TO |
1681 | |
1682 | return $result; | |
1683 | } | |
1684 | ||
1685 | /** | |
1686 | * Based on the provided two contact_ids and a set of tables, move the belongings of the | |
1687 | * other contact to the main one - be it Location / CustomFields or Contact .. related info. | |
1688 | * A superset of moveContactBelongings() function. | |
1689 | * | |
98997235 TO |
1690 | * @param int $mainId |
1691 | * Main contact with whom merge has to happen. | |
1692 | * @param int $otherId | |
1693 | * Duplicate contact which would be deleted after merge operation. | |
77b97be7 | 1694 | * |
1600a9c0 | 1695 | * @param array $migrationInfo |
6a488035 | 1696 | * |
3058f4d9 | 1697 | * @param bool $checkPermissions |
1698 | * Respect logged in user permissions. | |
1699 | * | |
77b97be7 | 1700 | * @return bool |
fe3b8caf | 1701 | * |
1702 | * @throws \API_Exception | |
1703 | * @throws \CRM_Core_Exception | |
1600a9c0 | 1704 | * @throws \CiviCRM_API3_Exception |
fe3b8caf | 1705 | * @throws \Civi\API\Exception\UnauthorizedException |
6a488035 | 1706 | */ |
3058f4d9 | 1707 | public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) { |
6a488035 TO |
1708 | if (empty($migrationInfo)) { |
1709 | return FALSE; | |
1710 | } | |
119664d6 | 1711 | // Encapsulate in a transaction to avoid half-merges. |
1712 | $transaction = new CRM_Core_Transaction(); | |
6a488035 | 1713 | |
1acd98ec | 1714 | $contactType = $migrationInfo['main_details']['contact_type']; |
6a488035 | 1715 | $relTables = CRM_Dedupe_Merger::relTables(); |
35e0e03e | 1716 | $submittedCustomFields = $moveTables = $tableOperations = $removeTables = []; |
ae2346d4 | 1717 | |
54ed517e | 1718 | self::swapOutFieldsAffectedByQFZeroBug($migrationInfo); |
6a488035 | 1719 | foreach ($migrationInfo as $key => $value) { |
08b00099 | 1720 | |
723c5a81 | 1721 | if (substr($key, 0, 12) === 'move_custom_' && $value != NULL) { |
6a488035 | 1722 | $submitted[substr($key, 5)] = $value; |
ae2346d4 | 1723 | $submittedCustomFields[] = substr($key, 12); |
6a488035 | 1724 | } |
08b00099 | 1725 | elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) { |
6a488035 TO |
1726 | $submitted[substr($key, 5)] = $value; |
1727 | } | |
723c5a81 | 1728 | elseif (substr($key, 0, 15) === 'move_rel_table_' and $value == '1') { |
6a488035 TO |
1729 | $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']); |
1730 | if (array_key_exists('operation', $migrationInfo)) { | |
1731 | foreach ($relTables[substr($key, 5)]['tables'] as $table) { | |
1732 | if (array_key_exists($key, $migrationInfo['operation'])) { | |
1733 | $tableOperations[$table] = $migrationInfo['operation'][$key]; | |
1734 | } | |
1735 | } | |
1736 | } | |
1737 | } | |
723c5a81 | 1738 | elseif (substr($key, 0, 15) === 'move_rel_table_' and $value == '0') { |
4099a9c5 AP |
1739 | $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']); |
1740 | } | |
6a488035 | 1741 | } |
4c54e0bd | 1742 | $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId); |
1743 | $mergeHandler->setMigrationInfo($migrationInfo); | |
a5e9dbe9 | 1744 | $mergeHandler->mergeLocations(); |
6a488035 | 1745 | |
6a488035 | 1746 | // **** Do contact related migrations |
1600a9c0 | 1747 | // @todo - move all custom field processing to the move class & eventually have an |
1748 | // overridable DAO class for it. | |
1749 | $customFieldBAO = new CRM_Core_BAO_CustomField(); | |
1750 | $customFieldBAO->move($otherId, $mainId, $submittedCustomFields); | |
eca28463 | 1751 | // add the related tables and unset the ones that don't sport any of the duplicate contact's info |
4c54e0bd | 1752 | |
eca28463 | 1753 | CRM_Dedupe_Merger::moveContactBelongings($mergeHandler, $moveTables, $tableOperations); |
0556db5d | 1754 | unset($moveTables, $tableOperations); |
6a488035 | 1755 | |
4099a9c5 AP |
1756 | // **** Do table related removals |
1757 | if (!empty($removeTables)) { | |
1758 | // **** CRM-20421 | |
1759 | CRM_Dedupe_Merger::removeContactBelongings($otherId, $removeTables); | |
2c16165a | 1760 | $removeTables = []; |
4099a9c5 AP |
1761 | } |
1762 | ||
6a488035 | 1763 | // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact() |
2c16165a | 1764 | $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender']; |
1765 | $names['individual_prefix'] = [ | |
1766 | 'newName' => 'prefix_id', | |
1767 | 'groupName' => 'individual_prefix', | |
1768 | ]; | |
1769 | $names['individual_suffix'] = [ | |
1770 | 'newName' => 'suffix_id', | |
1771 | 'groupName' => 'individual_suffix', | |
1772 | ]; | |
1773 | $names['communication_style'] = [ | |
1774 | 'newName' => 'communication_style_id', | |
1775 | 'groupName' => 'communication_style', | |
1776 | ]; | |
1777 | $names['addressee'] = [ | |
1778 | 'newName' => 'addressee_id', | |
1779 | 'groupName' => 'addressee', | |
1780 | ]; | |
1781 | $names['email_greeting'] = [ | |
1782 | 'newName' => 'email_greeting_id', | |
1783 | 'groupName' => 'email_greeting', | |
1784 | ]; | |
1785 | $names['postal_greeting'] = [ | |
1786 | 'newName' => 'postal_greeting_id', | |
1787 | 'groupName' => 'postal_greeting', | |
1788 | ]; | |
6a488035 | 1789 | CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE); |
6a488035 | 1790 | // fix custom fields so they're edible by createProfileContact() |
f941d73a | 1791 | $cFields = self::getCustomFieldMetadata($contactType); |
6a488035 TO |
1792 | |
1793 | if (!isset($submitted)) { | |
2c16165a | 1794 | $submitted = []; |
6a488035 TO |
1795 | } |
1796 | foreach ($submitted as $key => $value) { | |
e908d4ab | 1797 | [$cFields, $submitted] = self::processCustomFields($mainId, $key, $cFields, $submitted, $value); |
6a488035 TO |
1798 | } |
1799 | ||
6a488035 | 1800 | // move view only custom fields CRM-5362 |
2c16165a | 1801 | $viewOnlyCustomFields = []; |
6a488035 | 1802 | foreach ($submitted as $key => $value) { |
ca38a45b | 1803 | $fid = CRM_Core_BAO_CustomField::getKeyID($key); |
1804 | if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view']) | |
1805 | ) { | |
6a488035 TO |
1806 | $viewOnlyCustomFields[$key] = $value; |
1807 | } | |
1808 | } | |
6a488035 TO |
1809 | // special case to set values for view only, CRM-5362 |
1810 | if (!empty($viewOnlyCustomFields)) { | |
1811 | $viewOnlyCustomFields['entityID'] = $mainId; | |
1812 | CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields); | |
1813 | } | |
1814 | ||
1f0138dd SL |
1815 | // dev/core#996 Ensure that the earliest created date is stored against the kept contact id |
1816 | $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [ | |
1817 | 'id' => $mainId, | |
1818 | 'return' => ['created_date'], | |
1819 | ])['created_date']; | |
1820 | $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [ | |
1821 | 'id' => $otherId, | |
1822 | 'return' => ['created_date'], | |
1823 | ])['created_date']; | |
978b982d | 1824 | if ($otherCreatedDate < $mainCreatedDate && !empty($otherCreatedDate)) { |
1f0138dd SL |
1825 | CRM_Core_DAO::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [ |
1826 | 1 => [$otherCreatedDate, 'String'], | |
1827 | 2 => [$mainId, 'Positive'], | |
1828 | ]); | |
1829 | } | |
1830 | ||
3058f4d9 | 1831 | if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') && |
2c16165a | 1832 | CRM_Core_Permission::check('delete contacts')) |
6a488035 TO |
1833 | ) { |
1834 | // if ext id is submitted then set it null for contact to be deleted | |
a7488080 | 1835 | if (!empty($submitted['external_identifier'])) { |
6a488035 TO |
1836 | $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}"; |
1837 | CRM_Core_DAO::executeQuery($query); | |
1838 | } | |
2c16165a | 1839 | civicrm_api3('contact', 'delete', ['id' => $otherId]); |
6a488035 | 1840 | } |
6a488035 | 1841 | |
4d5f18cc | 1842 | // CRM-15681 merge sub_types |
35522279 J |
1843 | if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) { |
1844 | if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) { | |
481a74f4 | 1845 | $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types)); |
0db6c3e1 TO |
1846 | } |
1847 | else { | |
4d5f18cc | 1848 | $submitted['contact_sub_type'] = $other_sub_types; |
1849 | } | |
1850 | } | |
1851 | ||
6a488035 TO |
1852 | // **** Update contact related info for the main contact |
1853 | if (!empty($submitted)) { | |
1854 | $submitted['contact_id'] = $mainId; | |
1855 | ||
1856 | //update current employer field | |
1857 | if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) { | |
1858 | if (!CRM_Utils_System::isNull($currentEmloyerId)) { | |
1859 | $submitted['current_employer'] = $submitted['current_employer_id']; | |
0db6c3e1 TO |
1860 | } |
1861 | else { | |
6a488035 TO |
1862 | $submitted['current_employer'] = ''; |
1863 | } | |
1864 | unset($submitted['current_employer_id']); | |
1865 | } | |
1866 | ||
00f3da2e | 1867 | //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name |
481a74f4 | 1868 | if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) { |
00f3da2e BS |
1869 | $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id']; |
1870 | } | |
481a74f4 | 1871 | if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) { |
00f3da2e BS |
1872 | $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id']; |
1873 | } | |
630b73e3 | 1874 | self::updateContact($mainId, $submitted); |
6a488035 | 1875 | } |
119664d6 | 1876 | $transaction->commit(); |
1273d77c | 1877 | CRM_Utils_Hook::post('merge', 'Contact', $mainId); |
f00283b5 | 1878 | self::createMergeActivities($mainId, $otherId); |
5ea06a7b | 1879 | |
6a488035 TO |
1880 | return TRUE; |
1881 | } | |
16254ae1 ARW |
1882 | |
1883 | /** | |
f00283b5 | 1884 | * Get fields in the contact table suitable for merging. |
1885 | * | |
a6c01b45 | 1886 | * @return array |
f00283b5 | 1887 | * Array of field names to be potentially merged. |
16254ae1 | 1888 | */ |
00be9182 | 1889 | public static function getContactFields() { |
16254ae1 | 1890 | $contactFields = CRM_Contact_DAO_Contact::fields(); |
2c16165a | 1891 | $invalidFields = [ |
353ffa53 | 1892 | 'api_key', |
353ffa53 TO |
1893 | 'created_date', |
1894 | 'display_name', | |
1895 | 'hash', | |
1896 | 'id', | |
1897 | 'modified_date', | |
1898 | 'primary_contact_id', | |
1899 | 'sort_name', | |
c301f76e | 1900 | 'user_unique_id', |
2c16165a | 1901 | ]; |
bdd7870e RN |
1902 | foreach ($contactFields as $field => $value) { |
1903 | if (in_array($field, $invalidFields)) { | |
1904 | unset($contactFields[$field]); | |
1905 | } | |
1906 | } | |
16254ae1 ARW |
1907 | return array_keys($contactFields); |
1908 | } | |
ada104d5 AW |
1909 | |
1910 | /** | |
1911 | * Added for CRM-12695 | |
c301f76e | 1912 | * Based on the contactID provided |
ada104d5 AW |
1913 | * add/update membership(s) to related contacts |
1914 | * | |
c301f76e | 1915 | * @param int $contactID |
723c5a81 | 1916 | * |
1917 | * @throws \CRM_Core_Exception | |
1918 | * @throws \CiviCRM_API3_Exception | |
ada104d5 | 1919 | */ |
6bb508e5 | 1920 | public static function addMembershipToRelatedContacts($contactID) { |
ada104d5 AW |
1921 | $dao = new CRM_Member_DAO_Membership(); |
1922 | $dao->contact_id = $contactID; | |
1923 | $dao->is_test = 0; | |
1924 | $dao->find(); | |
1925 | ||
1926 | //checks membership of contact itself | |
1927 | while ($dao->fetch()) { | |
1928 | $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id'); | |
1929 | if ($relationshipTypeId) { | |
2c16165a | 1930 | $membershipParams = [ |
ada104d5 AW |
1931 | 'id' => $dao->id, |
1932 | 'contact_id' => $dao->contact_id, | |
1933 | 'membership_type_id' => $dao->membership_type_id, | |
1934 | 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date), | |
1935 | 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date), | |
1936 | 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date), | |
1937 | 'source' => $dao->source, | |
21dfd5f5 | 1938 | 'status_id' => $dao->status_id, |
2c16165a | 1939 | ]; |
ada104d5 AW |
1940 | // create/update membership(s) for related contact(s) |
1941 | CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao); | |
1942 | } // end of if relationshipTypeId | |
1943 | } | |
1944 | } | |
96025800 | 1945 | |
f00283b5 | 1946 | /** |
1947 | * Create activities tracking the merge on affected contacts. | |
1948 | * | |
1949 | * @param int $mainId | |
1950 | * @param int $otherId | |
1951 | * | |
1952 | * @throws \CiviCRM_API3_Exception | |
1953 | */ | |
1954 | public static function createMergeActivities($mainId, $otherId) { | |
2c16165a | 1955 | $params = [ |
f00283b5 | 1956 | 1 => $otherId, |
1957 | 2 => $mainId, | |
2c16165a | 1958 | ]; |
1959 | $activity = civicrm_api3('activity', 'create', [ | |
dc33398e | 1960 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : |
518fa0ee | 1961 | $mainId, |
f00283b5 | 1962 | 'subject' => ts('Contact ID %1 has been merged and deleted.', $params), |
1963 | 'target_contact_id' => $mainId, | |
1964 | 'activity_type_id' => 'Contact Merged', | |
1965 | 'status_id' => 'Completed', | |
2c16165a | 1966 | ]); |
1967 | if (civicrm_api3('Setting', 'getvalue', [ | |
1968 | 'name' => 'contact_undelete', | |
1969 | 'group' => 'CiviCRM Preferences', | |
1970 | ])) { | |
1971 | civicrm_api3('activity', 'create', [ | |
dc33398e | 1972 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : |
518fa0ee | 1973 | $otherId, |
4d834a99 | 1974 | 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params), |
1975 | 'target_contact_id' => $otherId, | |
1976 | 'activity_type_id' => 'Contact Deleted by Merge', | |
1977 | 'parent_id' => $activity['id'], | |
1978 | 'status_id' => 'Completed', | |
2c16165a | 1979 | ]); |
4d834a99 | 1980 | } |
f00283b5 | 1981 | } |
1982 | ||
2988f5c7 | 1983 | /** |
1984 | * Get Duplicate Pairs based on a rule for a group. | |
1985 | * | |
1986 | * @param int $rule_group_id | |
1987 | * @param int $group_id | |
1988 | * @param bool $reloadCacheIfEmpty | |
917acf6f | 1989 | * Should the cache be reloaded if empty - this must be false when in a dedupe action! |
2988f5c7 | 1990 | * @param int $batchLimit |
1991 | * @param bool $isSelected | |
5721d85e | 1992 | * Limit to selected pairs. |
66eceb0b | 1993 | * @param bool $includeConflicts |
e23e26ec | 1994 | * @param array $criteria |
1995 | * Additional criteria to narrow down the merge group. | |
2988f5c7 | 1996 | * |
3058f4d9 | 1997 | * @param bool $checkPermissions |
1998 | * Respect logged in user permissions. | |
1999 | * | |
21a95d83 | 2000 | * @param int $searchLimit |
2001 | * Limit to searching for matches against this many contacts. | |
2002 | * | |
c41f68a5 | 2003 | * @param int $isForceNewSearch |
2004 | * Should a new search be forced, bypassing any cache retrieval. | |
2005 | * | |
2988f5c7 | 2006 | * @return array |
518fa0ee | 2007 | * Array of matches meeting the criteria. |
9c5fe572 | 2008 | * |
2009 | * @throws \CRM_Core_Exception | |
2010 | * @throws \CiviCRM_API3_Exception | |
2988f5c7 | 2011 | */ |
c41f68a5 | 2012 | public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0, $isForceNewSearch = 0) { |
2013 | $dupePairs = $isForceNewSearch ? [] : self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit); | |
2988f5c7 | 2014 | if (empty($dupePairs) && $reloadCacheIfEmpty) { |
2015 | // If we haven't found any dupes, probably cache is empty. | |
66eceb0b | 2016 | // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any |
2017 | // until we have done some processing. | |
e1e24a57 | 2018 | CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit); |
997a03fe | 2019 | return self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions, $searchLimit); |
2988f5c7 | 2020 | } |
2021 | return $dupePairs; | |
2022 | } | |
2023 | ||
2ae26001 | 2024 | /** |
2025 | * Get the cache key string for the merge action. | |
2026 | * | |
2027 | * @param int $rule_group_id | |
2028 | * @param int $group_id | |
e23e26ec | 2029 | * @param array $criteria |
2030 | * Additional criteria to narrow down the merge group. | |
2031 | * Currently we are only supporting the key 'contact' within it. | |
3058f4d9 | 2032 | * @param bool $checkPermissions |
2033 | * Respect the users permissions. | |
997a03fe | 2034 | * @param int $searchLimit |
2035 | * Number of contacts to seek dupes for (we need this because if | |
2036 | * we change it the results won't be refreshed otherwise. Changing the limit | |
2037 | * from 100 to 1000 SHOULD result in a new dedupe search). | |
3058f4d9 | 2038 | * |
2ae26001 | 2039 | * @return string |
2040 | */ | |
997a03fe | 2041 | public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit) { |
61194d45 | 2042 | $contactType = CRM_Dedupe_BAO_DedupeRuleGroup::getContactTypeForRuleGroup($rule_group_id); |
9d2f6d53 | 2043 | $cacheKeyString = "merge_{$contactType}"; |
2ae26001 | 2044 | $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0'; |
2045 | $cacheKeyString .= $group_id ? "_{$group_id}" : '_0'; | |
997a03fe | 2046 | $cacheKeyString .= '_' . (int) $searchLimit; |
629dd4f3 | 2047 | $cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0'; |
3058f4d9 | 2048 | if ($checkPermissions) { |
2049 | $contactID = CRM_Core_Session::getLoggedInContactID(); | |
2050 | if (!$contactID) { | |
2051 | // Distinguish between no permission check & no logged in user. | |
2052 | $contactID = 'null'; | |
2053 | } | |
2054 | $cacheKeyString .= '_' . $contactID; | |
2055 | } | |
2056 | else { | |
2057 | $cacheKeyString .= '_0'; | |
2058 | } | |
2ae26001 | 2059 | return $cacheKeyString; |
2060 | } | |
2061 | ||
74a6069d | 2062 | /** |
2063 | * Get the metadata for the merge fields. | |
2064 | * | |
2065 | * This is basically the contact metadata, augmented with fields to | |
2066 | * represent email greeting, postal greeting & addressee. | |
2067 | * | |
2068 | * @return array | |
2069 | */ | |
2070 | public static function getMergeFieldsMetadata() { | |
2071 | if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) { | |
2072 | return \Civi::$statics[__CLASS__]['merge_fields_metadata']; | |
2073 | } | |
2074 | $fields = CRM_Contact_DAO_Contact::fields(); | |
2c16165a | 2075 | static $optionValueFields = []; |
74a6069d | 2076 | if (empty($optionValueFields)) { |
2077 | $optionValueFields = CRM_Core_OptionValue::getFields(); | |
2078 | } | |
2079 | foreach ($optionValueFields as $field => $params) { | |
2080 | $fields[$field]['title'] = $params['title']; | |
2081 | } | |
2082 | \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields; | |
2083 | return \Civi::$statics[__CLASS__]['merge_fields_metadata']; | |
2084 | } | |
2085 | ||
2086 | /** | |
2087 | * Get the details of the contact to be merged. | |
2088 | * | |
2089 | * @param int $contact_id | |
74a6069d | 2090 | * |
2091 | * @return array | |
2092 | * | |
2093 | * @throws CRM_Core_Exception | |
2094 | */ | |
fcc3d8ee | 2095 | public static function getMergeContactDetails($contact_id) { |
2c16165a | 2096 | $params = [ |
74a6069d | 2097 | 'contact_id' => $contact_id, |
2098 | 'version' => 3, | |
2c16165a | 2099 | 'return' => array_merge(['display_name'], self::getContactFields()), |
2100 | ]; | |
74a6069d | 2101 | $result = civicrm_api('contact', 'get', $params); |
2102 | ||
2103 | // CRM-18480: Cancel the process if the contact is already deleted | |
2104 | if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) { | |
2c16165a | 2105 | throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [ |
fcc3d8ee | 2106 | 1 => $contact_id, |
2c16165a | 2107 | ])); |
74a6069d | 2108 | } |
2109 | ||
2110 | return $result['values'][$contact_id]; | |
2111 | } | |
2112 | ||
e4e1db4b | 2113 | /** |
2114 | * Dedupe a pair of contacts. | |
2115 | * | |
a6b7cfc6 | 2116 | * @param int $mainId Id of contact to keep. |
2117 | * @param int $otherId Id of contact to delete. | |
e4e1db4b | 2118 | * @param string $mode |
2119 | * @param bool $checkPermissions | |
e4e1db4b | 2120 | * @param string $cacheKeyString |
37cd9336 | 2121 | * |
b068bfde | 2122 | * @return bool|array |
a6b7cfc6 | 2123 | * @throws \API_Exception |
37cd9336 | 2124 | * @throws \CRM_Core_Exception |
a6b7cfc6 | 2125 | * @throws \CRM_Core_Exception_ResourceConflictException |
37cd9336 | 2126 | * @throws \CiviCRM_API3_Exception |
a6b7cfc6 | 2127 | * @throws \Civi\API\Exception\UnauthorizedException |
e4e1db4b | 2128 | */ |
a6b7cfc6 | 2129 | protected static function dedupePair(int $mainId, int $otherId, $mode = 'safe', $checkPermissions = TRUE, $cacheKeyString = NULL) { |
b068bfde | 2130 | $resultStats = []; |
2131 | ||
aefc291e | 2132 | $migrationInfo = []; |
2c16165a | 2133 | $conflicts = []; |
c9f05fb3 | 2134 | // Try to lock the contacts before we load the data as we don't want it changing under us. |
2135 | // https://lab.civicrm.org/dev/core/issues/1355 | |
2136 | $locks = self::getLocksOnContacts([$mainId, $otherId]); | |
e4e1db4b | 2137 | if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) { |
2138 | CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions); | |
2c16165a | 2139 | $resultStats['merged'][] = [ |
e4e1db4b | 2140 | 'main_id' => $mainId, |
2141 | 'other_id' => $otherId, | |
2c16165a | 2142 | ]; |
e4e1db4b | 2143 | } |
2144 | else { | |
2c16165a | 2145 | $resultStats['skipped'][] = [ |
e4e1db4b | 2146 | 'main_id' => $mainId, |
2147 | 'other_id' => $otherId, | |
2c16165a | 2148 | ]; |
e4e1db4b | 2149 | } |
2150 | ||
2151 | // store any conflicts | |
2152 | if (!empty($conflicts)) { | |
ffa59d18 | 2153 | CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode); |
e4e1db4b | 2154 | } |
2155 | else { | |
eec58f8a | 2156 | self::deletePairFromPrevNextCache((int) $mainId, (int) $otherId); |
e4e1db4b | 2157 | } |
c9f05fb3 | 2158 | self::releaseLocks($locks); |
b068bfde | 2159 | return $resultStats; |
e4e1db4b | 2160 | } |
2161 | ||
eec58f8a | 2162 | /** |
2163 | * Delete merged pair from the previous next cache table as the are no longer a merge candidate. | |
2164 | * | |
2165 | * It's possible there may be more than one set of merge results cached, with different cache keys. | |
2166 | * Once we have merged a pair these should all go (even from a different merge search) as they | |
2167 | * can only be merged once. | |
2168 | * | |
2169 | * @param int $contactID1 | |
2170 | * @param int $contactID2 | |
2171 | */ | |
2172 | protected static function deletePairFromPrevNextCache(int $contactID1, int $contactID2) { | |
2173 | CRM_Core_DAO::executeQuery(" | |
2174 | DELETE FROM civicrm_prevnext_cache | |
2175 | WHERE entity_table = 'civicrm_contact' | |
2176 | AND (entity_id1 = %1 AND entity_id2 = %2) OR (entity_id1 = %2 AND entity_id2 = %1)", | |
2177 | [1 => [$contactID1, 'Integer'], 2 => [$contactID2, 'Integer']] | |
2178 | ); | |
2179 | } | |
2180 | ||
54ed517e | 2181 | /** |
2182 | * Replace the pseudo QFKey with zero if it is present. | |
2183 | * | |
2184 | * @todo - on the slim chance this is still relevant it should be moved to the form layer. | |
2185 | * | |
2186 | * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA | |
2187 | * can still help. | |
2188 | * | |
2189 | * @param array $migrationInfo | |
2190 | */ | |
2191 | protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) { | |
2192 | $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; | |
2193 | foreach ($migrationInfo as $key => &$value) { | |
723c5a81 | 2194 | if ($value === $qfZeroBug) { |
54ed517e | 2195 | $value = '0'; |
2196 | } | |
2197 | } | |
2198 | } | |
2199 | ||
830ee2be | 2200 | /** |
2201 | * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose. | |
2202 | * | |
1600a9c0 | 2203 | * Update this function formats fields in preparation for them to be submitted to the |
2204 | * 'ProfileContactCreate action. This is a lot of code to do this & for | |
2205 | * - for some fields it fails - e.g Country - per testMergeCustomFields. | |
2206 | * | |
2207 | * Goal is to move all custom field handling into 'move' functions on the various BAO | |
2208 | * with an underlying DAO function. For custom fields it has been started on the BAO. | |
2209 | * | |
723c5a81 | 2210 | * @param int $mainId |
2211 | * @param string $key | |
2212 | * @param array $cFields | |
2213 | * @param array $submitted | |
2214 | * @param mixed $value | |
830ee2be | 2215 | * |
2216 | * @return array | |
9a248526 | 2217 | * @throws \CRM_Core_Exception |
830ee2be | 2218 | */ |
1600a9c0 | 2219 | protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) { |
723c5a81 | 2220 | if (substr($key, 0, 7) === 'custom_') { |
830ee2be | 2221 | $fid = (int) substr($key, 7); |
2222 | if (empty($cFields[$fid])) { | |
1600a9c0 | 2223 | return [$cFields, $submitted]; |
830ee2be | 2224 | } |
2225 | $htmlType = $cFields[$fid]['attributes']['html_type']; | |
7f348139 | 2226 | $isSerialized = CRM_Core_BAO_CustomField::isSerialized($cFields[$fid]['attributes']); |
830ee2be | 2227 | |
7f348139 CW |
2228 | if ($htmlType === 'File') { |
2229 | // Handled in CustomField->move(). Tested in testMergeCustomFields. | |
2230 | unset($submitted["custom_$fid"]); | |
2231 | } | |
2232 | elseif (!$isSerialized && ($htmlType === 'Select Country' || $htmlType === 'Select State/Province')) { | |
2233 | // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move(). | |
2234 | $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid); | |
2235 | } | |
2236 | elseif ($htmlType === 'Select Date') { | |
2237 | if ($cFields[$fid]['attributes']['is_view']) { | |
2238 | $submitted[$key] = date('YmdHis', strtotime($submitted[$key])); | |
2239 | } | |
2240 | } | |
2241 | elseif ($isSerialized) { | |
2242 | // Merge values from both contacts for multivalue fields, CRM-4385 | |
2243 | // get the existing custom values from db. | |
2244 | $customParams = ['entityID' => $mainId, $key => TRUE]; | |
2245 | $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams); | |
2246 | if (!empty($customfieldValues[$key])) { | |
2247 | $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]); | |
2248 | if (is_array($existingValue) && !empty($existingValue)) { | |
2249 | $mergeValue = $submittedCustomFields = []; | |
723c5a81 | 2250 | if ($value === 'null') { |
7f348139 CW |
2251 | // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it. |
2252 | $submitted[$key] = $value; | |
2253 | } | |
2254 | else { | |
2255 | if ($value) { | |
2256 | $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); | |
830ee2be | 2257 | } |
830ee2be | 2258 | |
7f348139 CW |
2259 | // CRM-19653: overwrite or add the existing custom field value with dupicate contact's |
2260 | // custom field value stored at $submittedCustomValue. | |
2261 | foreach ($submittedCustomFields as $k => $v) { | |
2262 | if ($v != '' && !in_array($v, $mergeValue)) { | |
2263 | $mergeValue[] = $v; | |
830ee2be | 2264 | } |
7f348139 | 2265 | } |
830ee2be | 2266 | |
7f348139 CW |
2267 | //keep state and country as array format. |
2268 | //for checkbox and m-select format w/ VALUE_SEPARATOR | |
2269 | if (in_array($htmlType, ['CheckBox', 'Select'])) { | |
2270 | $submitted[$key] = CRM_Utils_Array::implodePadded($mergeValue); | |
2271 | } | |
2272 | else { | |
2273 | $submitted[$key] = $mergeValue; | |
830ee2be | 2274 | } |
2275 | } | |
2276 | } | |
7f348139 CW |
2277 | } |
2278 | elseif (in_array($htmlType, ['Select Country', 'Select State/Province'])) { | |
2279 | //we require submitted values should be in array format | |
2280 | if ($value) { | |
2281 | $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); | |
2282 | //hack to remove null values from array. | |
2283 | $mergeValue = []; | |
2284 | foreach ($mergeValueArray as $k => $v) { | |
2285 | if ($v != '') { | |
2286 | $mergeValue[] = $v; | |
830ee2be | 2287 | } |
830ee2be | 2288 | } |
7f348139 | 2289 | $submitted[$key] = $mergeValue; |
830ee2be | 2290 | } |
7f348139 | 2291 | } |
830ee2be | 2292 | } |
2293 | } | |
1600a9c0 | 2294 | return [$cFields, $submitted]; |
830ee2be | 2295 | } |
2296 | ||
f941d73a | 2297 | /** |
2298 | * Get metadata for the custom fields for the merge. | |
2299 | * | |
2300 | * @param string $contactType | |
2301 | * | |
2302 | * @return array | |
9a248526 | 2303 | * @throws \CRM_Core_Exception |
f941d73a | 2304 | */ |
2305 | protected static function getCustomFieldMetadata($contactType) { | |
2306 | $treeCache = []; | |
2307 | if (!array_key_exists($contactType, $treeCache)) { | |
2308 | $treeCache[$contactType] = CRM_Core_BAO_CustomGroup::getTree( | |
2309 | $contactType, | |
2310 | NULL, | |
2311 | NULL, | |
2312 | -1, | |
2313 | [], | |
2314 | NULL, | |
2315 | TRUE, | |
2316 | NULL, | |
2317 | FALSE, | |
2318 | FALSE | |
2319 | ); | |
2320 | } | |
2321 | ||
2322 | $cFields = []; | |
2323 | foreach ($treeCache[$contactType] as $key => $group) { | |
2324 | if (!isset($group['fields'])) { | |
2325 | continue; | |
2326 | } | |
2327 | foreach ($group['fields'] as $fid => $field) { | |
2328 | $cFields[$fid]['attributes'] = $field; | |
2329 | } | |
2330 | } | |
2331 | return $cFields; | |
2332 | } | |
2333 | ||
a2abc387 | 2334 | /** |
2335 | * Get conflicts for proposed merge pair. | |
2336 | * | |
2337 | * @param array $migrationInfo | |
2338 | * This is primarily to inform hooks. The can also modify it which feels | |
2339 | * pretty fragile to do it here - but it is historical. | |
2340 | * @param int $mainId | |
2341 | * Main contact with whom merge has to happen. | |
2342 | * @param int $otherId | |
2343 | * Duplicate contact which would be deleted after merge operation. | |
2344 | * @param string $mode | |
2345 | * Helps decide how to behave when there are conflicts. | |
2346 | * - A 'safe' value skips the merge if there are any un-resolved conflicts. | |
2347 | * - Does a force merge otherwise (aggressive mode). | |
2348 | * | |
2349 | * @return array | |
aefc291e | 2350 | * |
2351 | * @throws \CRM_Core_Exception | |
2352 | * @throws \CiviCRM_API3_Exception | |
a2abc387 | 2353 | */ |
e908d4ab | 2354 | public static function getConflicts(array &$migrationInfo, int $mainId, int $otherId, string $mode): array { |
a2abc387 | 2355 | $conflicts = []; |
aefc291e | 2356 | // Generate var $migrationInfo. The variable structure is exactly same as |
2357 | // $formValues submitted during a UI merge for a pair of contacts. | |
2358 | $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, FALSE); | |
2359 | // add additional details that we might need to resolve conflicts | |
2360 | $migrationInfo = $rowsElementsAndInfo['migration_info']; | |
2361 | $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details']; | |
2362 | $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details']; | |
2363 | $migrationInfo['rows'] = &$rowsElementsAndInfo['rows']; | |
2364 | // go ahead with merge if there is no conflict | |
a2abc387 | 2365 | $originalMigrationInfo = $migrationInfo; |
2366 | foreach ($migrationInfo as $key => $val) { | |
2367 | if ($val === "null") { | |
2368 | // Rule: Never overwrite with an empty value (in any mode) | |
2369 | unset($migrationInfo[$key]); | |
2370 | continue; | |
2371 | } | |
2372 | elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or | |
e908d4ab | 2373 | strpos($key, 'move_custom_') === 0 |
2374 | ) and $val !== NULL | |
a2abc387 | 2375 | ) { |
2376 | // Rule: If both main-contact, and other-contact have a field with a | |
2377 | // different value, then let $mode decide if to merge it or not | |
2378 | if ( | |
2379 | (!empty($migrationInfo['rows'][$key]['main']) | |
2380 | // For custom fields a 0 (e.g in an int field) could be a true conflict. This | |
2381 | // is probably true for other fields too - e.g. 'do_not_email' but | |
2382 | // leaving that investigation as a @todo - until tests can be written. | |
2383 | // Note the handling of this has test coverage - although the data-typing | |
2384 | // of '0' feels flakey we have insurance. | |
723c5a81 | 2385 | || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) === 'move_custom_') |
a2abc387 | 2386 | ) |
2387 | && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other'] | |
2388 | ) { | |
2389 | ||
2390 | // note it down & lets wait for response from the hook. | |
2391 | // For no response $mode will decide if to skip this merge | |
2392 | $conflicts[$key] = NULL; | |
2393 | } | |
2394 | } | |
723c5a81 | 2395 | elseif (substr($key, 0, 14) === 'move_location_' and $val != NULL) { |
a2abc387 | 2396 | $locField = explode('_', $key); |
2397 | $fieldName = $locField[2]; | |
2398 | $fieldCount = $locField[3]; | |
2399 | ||
2400 | // Rule: Catch address conflicts (same address type on both contacts) | |
2401 | if ( | |
2402 | isset($migrationInfo['main_details']['location_blocks'][$fieldName]) && | |
2403 | !empty($migrationInfo['main_details']['location_blocks'][$fieldName]) | |
2404 | ) { | |
2405 | ||
2406 | // Load the address we're inspecting from the 'other' contact | |
2407 | $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount]; | |
9c1bc317 | 2408 | $addressRecordLocTypeId = $addressRecord['location_type_id'] ?? NULL; |
a2abc387 | 2409 | |
2410 | // If it exists on the 'main' contact already, skip it. Otherwise | |
2411 | // if the location type exists already, log a conflict. | |
2412 | foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) { | |
ffcc831f | 2413 | if (!self::locationHasData($mainAddressRecord)) { |
2414 | // Go ahead & overwrite the main address - it has no data in it. | |
2415 | // if it is the primary address then pass that honour to the address that actually has data. | |
2416 | $migrationInfo['location_blocks'][$fieldName][$mainAddressKey]['set_other_primary'] = $mainAddressRecord['is_primary']; | |
2417 | continue; | |
2418 | } | |
a2abc387 | 2419 | if (self::locationIsSame($addressRecord, $mainAddressRecord)) { |
2420 | unset($migrationInfo[$key]); | |
ffcc831f | 2421 | continue; |
a2abc387 | 2422 | } |
ffcc831f | 2423 | if ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) { |
a2abc387 | 2424 | $conflicts[$key] = NULL; |
ffcc831f | 2425 | continue; |
a2abc387 | 2426 | } |
2427 | } | |
2428 | } | |
2429 | ||
2430 | // For other locations, don't merge/add if the values are the same | |
2431 | elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) { | |
2432 | unset($migrationInfo[$key]); | |
2433 | } | |
2434 | } | |
2435 | } | |
2436 | ||
2437 | // A hook to implement other algorithms for choosing which contact to bias to when | |
2438 | // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here | |
2439 | // merge happens with new values filled in here. For a particular field / row not to be merged | |
2440 | // field should be unset from fields_in_conflict. | |
2441 | $migrationData = [ | |
2442 | 'old_migration_info' => $originalMigrationInfo, | |
2443 | 'mode' => $mode, | |
2444 | 'fields_in_conflict' => $conflicts, | |
2445 | 'merge_mode' => $mode, | |
2446 | 'migration_info' => $migrationInfo, | |
2447 | ]; | |
2448 | CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId); | |
2449 | $conflicts = $migrationData['fields_in_conflict']; | |
2450 | // allow hook to override / manipulate migrationInfo as well | |
2451 | $migrationInfo = $migrationData['migration_info']; | |
ffa59d18 | 2452 | foreach ($conflicts as $key => $val) { |
403400d9 | 2453 | // Copy over the resolved values. If we are in aggressive mode we update to null |
2454 | // so as not to copy over. Why it's different to safe mode is a bit murky. | |
2455 | // Working theory is it doesn't matter what we do in safe mode here if $val is NULL. | |
2456 | // as the merge is not gonna happen if $val == NULL | |
2457 | $migrationInfo[$key] = $val ?? ($mode === 'safe' ? $migrationInfo[$key] : NULL); | |
ffa59d18 | 2458 | } |
403400d9 | 2459 | return self::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId, $mode); |
ffa59d18 | 2460 | } |
2461 | ||
2462 | /** | |
2463 | * @param array $conflicts | |
2464 | * @param array $migrationInfo | |
2465 | * @param $toKeepContactLocationBlocks | |
2466 | * @param $toRemoveContactLocationBlocks | |
2467 | * @param $toKeepID | |
2468 | * @param $toRemoveID | |
403400d9 | 2469 | * @param string $mode |
ffa59d18 | 2470 | * |
2471 | * @return mixed | |
2472 | * @throws \CRM_Core_Exception | |
2473 | */ | |
403400d9 | 2474 | protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID, $mode) { |
ffa59d18 | 2475 | $return = []; |
403400d9 | 2476 | $resolved = []; |
2477 | foreach ($conflicts as $key => $val) { | |
2478 | if ($val !== NULL) { | |
2479 | // copy over the resolved values | |
2480 | $resolved[$key] = $val; | |
2481 | unset($conflicts[$key]); | |
2482 | } | |
2483 | elseif ($mode === 'aggressive') { | |
2484 | unset($conflicts[$key]); | |
2485 | if (strpos($key, 'move_location_') !== 0) { | |
2486 | // @todo - just handling plain contact fields for now because I think I need a bigger refactor | |
2487 | // of the below to handle locations & will do as a follow up. | |
2488 | $resolved['contact'][substr($key, 5)] = $migrationInfo[$key]['main']; | |
2489 | } | |
2490 | } | |
2491 | } | |
ffa59d18 | 2492 | foreach (array_keys($conflicts) as $index) { |
2493 | if (substr($index, 0, 14) === 'move_location_') { | |
2494 | $parts = explode('_', $index); | |
2495 | $entity = $parts[2]; | |
2496 | $blockIndex = $parts[3]; | |
2497 | $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id']; | |
2498 | $entityConflicts = [ | |
2499 | 'location_type_id' => $locationTypeID, | |
2500 | 'title' => $migrationInfo[$index]['title'], | |
2501 | ]; | |
2502 | foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) { | |
2503 | if (in_array($fieldName, self::ignoredFields())) { | |
2504 | continue; | |
2505 | } | |
9c1bc317 | 2506 | $toRemoveValue = $toRemoveContactLocationBlocks[$entity][$blockIndex][$fieldName] ?? NULL; |
ffa59d18 | 2507 | if ($fieldValue !== $toRemoveValue) { |
2508 | $entityConflicts[$fieldName] = [ | |
2509 | $toKeepID => $fieldValue, | |
2510 | $toRemoveID => $toRemoveValue, | |
2511 | ]; | |
2512 | } | |
2513 | } | |
2514 | $return[$entity][] = $entityConflicts; | |
2515 | } | |
2516 | elseif (substr($index, 0, 5) === 'move_') { | |
2517 | $contactFieldsToCompare[] = str_replace('move_', '', $index); | |
2518 | $return['contact'][str_replace('move_', '', $index)] = [ | |
2519 | 'title' => $migrationInfo[$index]['title'], | |
2520 | $toKeepID => $migrationInfo[$index]['main'], | |
2521 | $toRemoveID => $migrationInfo[$index]['other'], | |
2522 | ]; | |
2523 | } | |
2524 | else { | |
2525 | // Can't think of why this would be the case but perhaps it's ensuring it isn't as we | |
2526 | // refactor this. | |
2527 | throw new CRM_Core_Exception(ts('Unknown parameter') . $index); | |
2528 | } | |
2529 | } | |
403400d9 | 2530 | return ['conflicts' => $return, 'resolved' => $resolved]; |
a2abc387 | 2531 | } |
2532 | ||
4107e11e | 2533 | /** |
e1e24a57 | 2534 | * Get any duplicate merge pairs that have been previously cached. |
2535 | * | |
2536 | * @param int $rule_group_id | |
2537 | * @param int $group_id | |
2538 | * @param int $batchLimit | |
2539 | * @param bool $isSelected | |
2540 | * @param bool $includeConflicts | |
2541 | * @param array $criteria | |
2542 | * @param int $checkPermissions | |
997a03fe | 2543 | * @param int $searchLimit |
4107e11e | 2544 | * |
2545 | * @return array | |
2546 | */ | |
997a03fe | 2547 | protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit = 0) { |
4107e11e | 2548 | return CRM_Core_BAO_PrevNextCache::retrieve( |
997a03fe | 2549 | self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit), |
4107e11e | 2550 | self::getJoinOnDedupeTable(), |
2551 | self::getWhereString($isSelected), | |
2552 | 0, $batchLimit, | |
2553 | [], '', | |
2554 | $includeConflicts | |
2555 | ); | |
2556 | } | |
2557 | ||
ffa59d18 | 2558 | /** |
2559 | * @return array | |
2560 | */ | |
2561 | protected static function ignoredFields(): array { | |
2562 | $keysToIgnore = [ | |
2563 | 'id', | |
2564 | 'is_primary', | |
2565 | 'is_billing', | |
2566 | 'manual_geo_code', | |
2567 | 'contact_id', | |
2568 | 'reset_date', | |
2569 | 'hold_date', | |
2570 | ]; | |
2571 | return $keysToIgnore; | |
2572 | } | |
2573 | ||
6704a926 | 2574 | /** |
2575 | * Get the field value & label for the given field. | |
2576 | * | |
2577 | * @param $field | |
2578 | * @param $contact | |
2579 | * | |
2580 | * @return array | |
2581 | * @throws \Exception | |
2582 | */ | |
2583 | private static function getFieldValueAndLabel($field, $contact): array { | |
2584 | $fields = self::getMergeFieldsMetadata(); | |
9c1bc317 | 2585 | $value = $label = $contact[$field] ?? NULL; |
6704a926 | 2586 | $fieldSpec = $fields[$field]; |
2587 | if (!empty($fieldSpec['serialize']) && is_array($value)) { | |
2588 | // In practice this only applies to preferred_communication_method as the sub types are skipped above | |
2589 | // and no others are serialized. | |
2590 | $labels = []; | |
2591 | foreach ($value as $individualValue) { | |
2592 | $labels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue); | |
2593 | } | |
2594 | $label = implode(', ', $labels); | |
2595 | // We serialize this due to historic handling but it's likely that if we just left it as an | |
2596 | // array all would be well & we would have less code. | |
2597 | $value = CRM_Core_DAO::serializeField($value, $fieldSpec['serialize']); | |
2598 | } | |
2599 | elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type::T_DATE) { | |
2600 | if ($value) { | |
2601 | $value = str_replace('-', '', $value); | |
2602 | $label = CRM_Utils_Date::customFormat($label); | |
2603 | } | |
2604 | else { | |
2605 | $value = "null"; | |
2606 | } | |
2607 | } | |
2608 | elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) { | |
2609 | if ($label === '0') { | |
2610 | $label = ts('[ ]'); | |
2611 | } | |
2612 | if ($label === '1') { | |
2613 | $label = ts('[x]'); | |
2614 | } | |
2615 | } | |
2616 | elseif (!empty($fieldSpec['pseudoconstant'])) { | |
2617 | $label = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $value); | |
2618 | } | |
2619 | elseif ($field == 'current_employer_id' && !empty($value)) { | |
2620 | $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")"; | |
2621 | } | |
2fd72602 | 2622 | return ['label' => $label, 'value' => $value]; |
6704a926 | 2623 | } |
2624 | ||
1a90ac89 | 2625 | /** |
2626 | * Build up the location block for the contact in dedupe-screen display format. | |
2627 | * | |
2024d5b9 | 2628 | * @param int $cid |
1a90ac89 | 2629 | * @param array $blockInfo |
2630 | * @param string $blockName | |
2631 | * | |
2632 | * @return array | |
2633 | * | |
2634 | * @throws \CiviCRM_API3_Exception | |
2635 | */ | |
2636 | private static function buildLocationBlockForContact($cid, $blockInfo, $blockName): array { | |
2637 | $searchParams = [ | |
2638 | 'contact_id' => $cid, | |
2639 | // CRM-17556 Order by field-specific criteria | |
2640 | 'options' => [ | |
2641 | 'sort' => $blockInfo['sortString'], | |
2642 | ], | |
2643 | ]; | |
2644 | $locationBlock = []; | |
2645 | $values = civicrm_api3($blockName, 'get', $searchParams); | |
2646 | if ($values['count']) { | |
2647 | $cnt = 0; | |
2648 | foreach ($values['values'] as $value) { | |
2649 | $locationBlock[$cnt] = $value; | |
2650 | // Fix address display | |
2651 | if ($blockName == 'address') { | |
2652 | // For performance avoid geocoding while merging https://issues.civicrm.org/jira/browse/CRM-21786 | |
2653 | // we can expect existing geocode values to be retained. | |
2654 | $value['skip_geocode'] = TRUE; | |
2655 | CRM_Core_BAO_Address::fixAddress($value); | |
2656 | unset($value['skip_geocode']); | |
2657 | $locationBlock[$cnt]['display'] = CRM_Utils_Address::format($value); | |
2658 | } | |
2659 | // Fix email display | |
2660 | elseif ($blockName == 'email') { | |
2661 | $locationBlock[$cnt]['display'] = CRM_Utils_Mail::format($value); | |
2662 | } | |
2663 | ||
2664 | $cnt++; | |
2665 | } | |
2666 | } | |
2667 | return $locationBlock; | |
2668 | } | |
2669 | ||
c9f05fb3 | 2670 | /** |
2671 | * Get a lock on the given contact. | |
2672 | * | |
2673 | * The lock is like a gentleman's agreement between php & mysql. It is reserved at the | |
2674 | * mysql level so it works across php processes but it doesn't actually lock the database. | |
2675 | * | |
2676 | * Instead php can check the lock to see if it has been acquired before taking an action. | |
2677 | * | |
2678 | * In this case we really don't want to attempt to dedupe contacts if another process is | |
2679 | * trying to act on the specific contact as it could result in messy deadlocks & possibly data corruption. | |
2680 | * In most databases this would be a rare event but if multiple dedupe processes are running | |
2681 | * at once (for example) or there is also an import process in play there is potential for them to crash. | |
2682 | * By throwing a specific error the calling process can catch it and determine it is worth trying again later without a lot of | |
2683 | * noise. | |
2684 | * | |
2685 | * As of writing no other processes DO grab contact locks but it would be reasonable to consider | |
2686 | * grabbing them doing contact edits in general as well as imports etc. | |
2687 | * | |
2688 | * @param array $contacts | |
2689 | * | |
2690 | * @return array | |
2691 | * | |
2692 | * @throws \CRM_Core_Exception | |
2693 | * @throws \CRM_Core_Exception_ResourceConflictException | |
2694 | */ | |
2695 | protected static function getLocksOnContacts($contacts):array { | |
2696 | $locks = []; | |
2697 | if (!CRM_Utils_SQL::supportsMultipleLocks()) { | |
2698 | return $locks; | |
2699 | } | |
2700 | foreach ($contacts as $contactID) { | |
2701 | $lock = Civi::lockManager()->acquire("data.core.contact.{$contactID}"); | |
2702 | if ($lock->isAcquired()) { | |
2703 | $locks[] = $lock; | |
2704 | } | |
2705 | else { | |
2706 | self::releaseLocks($locks); | |
2707 | throw new CRM_Core_Exception_ResourceConflictException(ts('Contact is in Use'), 'contact_lock'); | |
2708 | } | |
2709 | } | |
2710 | return $locks; | |
2711 | } | |
2712 | ||
2713 | /** | |
2714 | * Release contact locks so another process can alter them if it wants. | |
2715 | * | |
2716 | * @param array $locks | |
2717 | */ | |
2718 | protected static function releaseLocks(array $locks) { | |
2719 | foreach ($locks as $lock) { | |
2720 | /* @var Civi\Core\Lock\LockInterface $lock */ | |
2721 | $lock->release(); | |
2722 | } | |
2723 | } | |
2724 | ||
18226102 | 2725 | /** |
2726 | * @param $mainId | |
2727 | * @param $otherId | |
2728 | * @param $blockInfo | |
2729 | * @param $blockName | |
2730 | * @param array $locations | |
2731 | * @param array $rows | |
2732 | * @param array $elements | |
2733 | * @param array $migrationInfo | |
2734 | * | |
2735 | * @return array | |
2736 | * @throws \CiviCRM_API3_Exception | |
2737 | */ | |
2738 | protected static function addLocationFieldInfo($mainId, $otherId, $blockInfo, $blockName, array $locations, array $rows, array $elements, array $migrationInfo): array { | |
2739 | // Collect existing fields from both 'main' and 'other' contacts first | |
2740 | // This allows us to match up location/types when building the table rows | |
2741 | $locations['main'][$blockName] = self::buildLocationBlockForContact($mainId, $blockInfo, $blockName); | |
2742 | $locations['other'][$blockName] = self::buildLocationBlockForContact($otherId, $blockInfo, $blockName); | |
2743 | ||
2744 | // Now, build the table rows appropriately, based off the information on | |
2745 | // the 'other' contact | |
2746 | if (!empty($locations['other']) && !empty($locations['other'][$blockName])) { | |
2747 | foreach ($locations['other'][$blockName] as $count => $value) { | |
2748 | ||
2749 | $displayValue = $value[$blockInfo['displayField']]; | |
2750 | ||
2751 | // Add this value to the table rows | |
2752 | $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue; | |
46a5c9b7 | 2753 | $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName; |
18226102 | 2754 | |
2755 | // CRM-17556 Only display 'main' contact value if it's the same location + type | |
2756 | // Look it up from main values... | |
2757 | ||
2758 | $lookupLocation = FALSE; | |
2759 | if ($blockInfo['hasLocation']) { | |
2760 | $lookupLocation = $value['location_type_id']; | |
2761 | } | |
2762 | ||
2763 | $lookupType = FALSE; | |
2764 | if ($blockInfo['hasType']) { | |
9c1bc317 | 2765 | $lookupType = $value[$blockInfo['hasType']] ?? NULL; |
18226102 | 2766 | } |
2767 | ||
2768 | // Hold ID of main contact's matching block | |
2769 | $mainContactBlockId = 0; | |
2770 | ||
2771 | if (!empty($locations['main'][$blockName])) { | |
2772 | foreach ($locations['main'][$blockName] as $mainValueCheck) { | |
2773 | // No location/type, or matching location and type | |
2774 | if ( | |
2775 | (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id']) | |
2776 | && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']]) | |
2777 | ) { | |
2778 | // Set this value as the default against the 'other' contact value | |
2779 | $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']]; | |
b3960640 | 2780 | $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'] ?? 0; |
18226102 | 2781 | $mainContactBlockId = $mainValueCheck['id']; |
2782 | break; | |
2783 | } | |
2784 | } | |
2785 | } | |
2786 | ||
2787 | // Add checkbox to migrate data from 'other' to 'main' | |
2788 | $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"]; | |
2789 | ||
2790 | // Add checkbox to set the 'other' location as primary | |
2791 | $elements[] = [ | |
2792 | 'advcheckbox', | |
2793 | "location_blocks[$blockName][$count][set_other_primary]", | |
2794 | NULL, | |
2795 | ts('Set as primary'), | |
2796 | ]; | |
2797 | ||
2798 | // Flag up this field to skipMerge function (@todo: do we need to?) | |
2799 | $migrationInfo["move_location_{$blockName}_{$count}"] = 1; | |
2800 | ||
2801 | // Add a hidden field to store the ID of the target main contact block | |
2802 | $elements[] = [ | |
2803 | 'hidden', | |
2804 | "location_blocks[$blockName][$count][mainContactBlockId]", | |
2805 | $mainContactBlockId, | |
2806 | ]; | |
2807 | ||
2808 | // Setup variables | |
2809 | $thisTypeId = FALSE; | |
2810 | $thisLocId = FALSE; | |
2811 | ||
2812 | // Provide a select drop-down for the location's location type | |
2813 | // eg: Home, Work... | |
2814 | ||
2815 | if ($blockInfo['hasLocation']) { | |
2816 | ||
2817 | // Load the location options for this entity | |
2818 | $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']); | |
2819 | ||
2820 | $thisLocId = $value['location_type_id']; | |
2821 | ||
2822 | // Put this field's location type at the top of the list | |
2823 | $tmpIdList = $locationOptions['values']; | |
2824 | $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]]; | |
2825 | unset($tmpIdList[$thisLocId]); | |
2826 | ||
2827 | // Add the element | |
2828 | $elements[] = [ | |
2829 | 'select', | |
2830 | "location_blocks[$blockName][$count][locTypeId]", | |
2831 | NULL, | |
2832 | $defaultLocId + $tmpIdList, | |
2833 | ]; | |
2834 | ||
2835 | // Add the relevant information to the $migrationInfo | |
2836 | // Keep location-type-id same as that of other-contact | |
2837 | // @todo Check this logic out | |
2838 | $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId; | |
2839 | if ($blockName != 'address') { | |
2840 | $elements[] = [ | |
2841 | 'advcheckbox', | |
2842 | "location_blocks[{$blockName}][$count][operation]", | |
2843 | NULL, | |
2844 | ts('Add new'), | |
2845 | ]; | |
2846 | // always use add operation | |
2847 | $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1; | |
2848 | } | |
2849 | ||
2850 | } | |
2851 | ||
2852 | // Provide a select drop-down for the location's type/provider | |
2853 | // eg websites: Facebook... | |
2854 | ||
2855 | if ($blockInfo['hasType']) { | |
2856 | ||
2857 | // Load the type options for this entity | |
2858 | $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]); | |
2859 | ||
9c1bc317 | 2860 | $thisTypeId = $value[$blockInfo['hasType']] ?? NULL; |
18226102 | 2861 | |
2862 | // Put this field's location type at the top of the list | |
2863 | $tmpIdList = $typeOptions['values']; | |
2864 | $defaultTypeId = [$thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList)]; | |
2865 | unset($tmpIdList[$thisTypeId]); | |
2866 | ||
2867 | // Add the element | |
2868 | $elements[] = [ | |
2869 | 'select', | |
2870 | "location_blocks[$blockName][$count][typeTypeId]", | |
2871 | NULL, | |
2872 | $defaultTypeId + $tmpIdList, | |
2873 | ]; | |
2874 | ||
2875 | // Add the information to the migrationInfo | |
2876 | $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId; | |
2877 | ||
2878 | } | |
2879 | ||
2880 | // Set the label for this row | |
2881 | $rowTitle = $blockInfo['label'] . ' ' . ($count + 1); | |
2882 | if (!empty($thisLocId)) { | |
2883 | $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')'; | |
2884 | } | |
2885 | if (!empty($thisTypeId)) { | |
2886 | $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')'; | |
2887 | } | |
2888 | $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle; | |
2889 | ||
2890 | } // End loop through 'other' locations of this type | |
2891 | ||
2892 | } | |
2893 | return [$locations, $rows, $elements, $migrationInfo]; | |
2894 | } | |
2895 | ||
6a488035 | 2896 | } |