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