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