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