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